hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b98b0138392907109c65543a5c323805c537ccbd
12,731
cpp
C++
src/base/attitude/NadirPointing.cpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
src/base/attitude/NadirPointing.cpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
src/base/attitude/NadirPointing.cpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id$ //------------------------------------------------------------------------------ // Nadir Pointing //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // From Wendy @ 2013.07.16 // Author: Yeerang Lim/KAIST // Created: 2013.05.09 // /** * Class implementation for the Nadir class. * * @note */ //------------------------------------------------------------------------------ //#define DEBUG_NADIRPOINTING //#define DEBUG_NADIR_POINTING_COMPUTE //#define DEBUG_ATTITUDE_SET //#define DEBUG_NADIR_REF_OBJECT #include "Attitude.hpp" #include "AttitudeException.hpp" #include "MessageInterface.hpp" #include "SpaceObject.hpp" #include "NadirPointing.hpp" //------------------------------------------------------------------------------ // static data //------------------------------------------------------------------------------ const Real NadirPointing::DENOMINATOR_TOLERANCE = 1.0e-15; //------------------------------------------------------------------------------ // public methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // NadirPointing(const std::string &itsName) //------------------------------------------------------------------------------ /** * This method creates an object of the Nadir class (constructor). */ //------------------------------------------------------------------------------ NadirPointing::NadirPointing(const std::string &itsName) : Kinematic("NadirPointing",itsName) { parameterCount = NadirPointingParamCount; objectTypeNames.push_back("NadirPointing"); attitudeModelName = "NadirPointing"; setInitialAttitudeAllowed = false; modifyCoordSysAllowed = false; // Reserve spaces to handle attribute comments for owned object // LOJ: 2013.03.01 for GMT-3353 FIX // No rates are computed for this model modelComputesRates = false; FinalizeCreation(); } //------------------------------------------------------------------------------ // NadirPointing(const NadirPointing &att) //------------------------------------------------------------------------------ /** * This method creates an object of the Nadir class as a copy of the * specified Nadir class (copy constructor). * * @param <att> Nadir object to copy. */ //------------------------------------------------------------------------------ NadirPointing::NadirPointing(const NadirPointing& att) : Kinematic(att) { } //------------------------------------------------------------------------------ // NadirPointing& operator= (const NadirPointing& att) //------------------------------------------------------------------------------ /** * Assignment operator for the NadirPointing class. * * @param att the NadirPointing object whose data to assign to "this" * NadirPointing. * * @return "this" NadirPointing with data of input NadirPointing att. */ //------------------------------------------------------------------------------ NadirPointing& NadirPointing::operator=(const NadirPointing& att) { Kinematic::operator=(att); return *this; } //------------------------------------------------------------------------------ // ~NadirPointing() //------------------------------------------------------------------------------ /** * Destroys the NadirPointing class (constructor). */ //------------------------------------------------------------------------------ NadirPointing::~NadirPointing() { // nothing really to do here ... la la la la la } //--------------------------------------------------------------------------- // bool Initialize() //--------------------------------------------------------------------------- /** * Initializes the attitude. * * @return Success flag. * */ //--------------------------------------------------------------------------- bool NadirPointing::Initialize() { if (!Kinematic::Initialize()) return false; // Cannot check refBody value here, as Initialize is called on // Attitude when getting any data value, including when the SpacecraftPanel // is brought up; this happens before the reference body pointer has been // set on the Attitude, so an error message here would be generated // each time the panel is opened. // We can wait until the attitude is computed to do this check. return true; } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * This method returns a clone of the Nadir. * * @return clone of the Nadir. * */ //------------------------------------------------------------------------------ GmatBase* NadirPointing::Clone() const { return (new NadirPointing(*this)); //???(YRL) } //------------------------------------------------------------------------------ // protected methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Rmatrix33 TRIAD(Rvector3& V1, Rvector3& V2, Rvector3& W1, Rvector3& W2) //------------------------------------------------------------------------------ Rmatrix33 NadirPointing::TRIAD(Rvector3& V1, Rvector3& V2, Rvector3& W1, Rvector3& W2) { // V1, V2 : defined in frame A // W1, W2 : defined in frame B // TRIAD algorithm calculates the rotation matrix from A to B Real v1Mag = V1.GetMagnitude(); if (v1Mag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } Rvector3 r1 = V1 / v1Mag; Rvector3 temp = Cross(V1,V2); Real tempMag = temp.GetMagnitude(); if (tempMag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } Rvector3 r2 = temp / tempMag; Rvector3 r3 = Cross(V1,temp); Real r3Mag = r3.GetMagnitude(); if (r3Mag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } r3 = r3 / r3Mag; Real w1Mag = W1.GetMagnitude(); if (w1Mag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } Rvector3 s1 = W1 / w1Mag; temp = Cross(W1,W2); Real temp2Mag = temp.GetMagnitude(); if (temp2Mag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } Rvector3 s2 = temp/temp2Mag; Rvector3 s3 = Cross(W1,temp); Real s3Mag = s3.GetMagnitude(); if (s3Mag < DENOMINATOR_TOLERANCE) { std::string errmsg = "Nadir attitude for spacecraft \""; errmsg += owningSC->GetName() + "\" is singular.\n"; throw AttitudeException(errmsg); } s3 = s3/s3Mag; // YRL, calculate resultRotMatrix Rmatrix33 resultRotMatrix = Outerproduct(s1,r1) + Outerproduct(s2,r2) + Outerproduct(s3,r3) ; return resultRotMatrix; } //------------------------------------------------------------------------------ // virtual void ComputeCosineMatrixAndAngularVelocity(Real atTime) //------------------------------------------------------------------------------ /** * This method computes the current CosineMatrix at the input time atTime. * * @param atTime the A1Mjd time at which to compute the attitude. * * @note This method will update the CosineMatrix parameter of the class. */ //------------------------------------------------------------------------------ void NadirPointing::ComputeCosineMatrixAndAngularVelocity(Real atTime) { #ifdef DEBUG_NADIR_POINTING_COMPUTE MessageInterface::ShowMessage("In NadirPointing, computing at time %le\n", atTime); MessageInterface::ShowMessage("attitudeConstraintType = %s\n", attitudeConstraintType.c_str()); if (!owningSC) MessageInterface::ShowMessage("--- owningSC is NULL!!!!\n"); if (!refBody) MessageInterface::ShowMessage("--- refBody is NULL!!!!\n"); #endif if (!isInitialized || needsReinit) { Initialize(); } // Need to do check for unset reference body here since the needsReinit // flag may not have been set if (!refBody) { std::string attEx = "Reference body "; attEx += refBodyName + " not defined for attitude of type \""; attEx += "NadirPointing\" on spacecraft \""; attEx += owningSC->GetName() + "\"."; throw AttitudeException(attEx); } /// using a spacecraft object, *owningSC A1Mjd theTime(atTime); Rvector6 scState = ((SpaceObject*) owningSC)->GetMJ2000State(theTime); Rvector6 refState = refBody->GetMJ2000State(theTime); Rvector3 pos(scState[0] - refState[0], scState[1] - refState[1], scState[2] - refState[2]); Rvector3 vel(scState[3] - refState[3], scState[4] - refState[4], scState[5] - refState[5]); #ifdef DEBUG_NADIR_POINTING_COMPUTE MessageInterface::ShowMessage(" scState = %s\n", scState.ToString().c_str()); MessageInterface::ShowMessage(" refState = %s\n", refState.ToString().c_str()); MessageInterface::ShowMessage(" pos = %s\n", pos.ToString().c_str()); MessageInterface::ShowMessage(" vel = %s\n", vel.ToString().c_str()); #endif // Error message std::string attErrorMsg = "Nadir Pointing attitude model is singular and/or "; attErrorMsg += "undefined for Spacecraft \""; attErrorMsg += owningSC->GetName() + "\"."; if ((bodyAlignmentVector.GetMagnitude() < 1.0e-5 ) || (bodyConstraintVector.GetMagnitude() < 1.0e-5) || (bodyAlignmentVector.GetUnitVector()* bodyConstraintVector.GetUnitVector() > ( 1.0 - 1.0e-5)) || (pos.GetMagnitude() < 1.0e-5) || (vel.GetMagnitude() < 1.0e-5) || (Cross(pos,vel).GetMagnitude() < 1.0e-5) ) { throw AttitudeException(attErrorMsg); } Rvector3 normal = Cross(pos,vel); Rvector3 xhat = pos/pos.GetMagnitude(); Rvector3 yhat = normal/normal.GetMagnitude(); Rvector3 zhat = Cross(xhat,yhat); Rvector3 referenceVector; Rvector3 constraintVector; #ifdef DEBUG_NADIR_POINTING_COMPUTE MessageInterface::ShowMessage(" normal = %s\n", normal.ToString().c_str()); MessageInterface::ShowMessage(" xhat = %s\n", xhat.ToString().c_str()); MessageInterface::ShowMessage(" yhat = %s\n", yhat.ToString().c_str()); MessageInterface::ShowMessage(" zhat = %s\n", zhat.ToString().c_str()); #endif // RiI calculation (from inertial to LVLH) Rmatrix33 RIi; RIi(0,0) = xhat(0); RIi(1,0) = xhat(1); RIi(2,0) = xhat(2); RIi(0,1) = yhat(0); RIi(1,1) = yhat(1); RIi(2,1) = yhat(2); RIi(0,2) = zhat(0); RIi(1,2) = zhat(1); RIi(2,2) = zhat(2); // Set alignment/constraint vector in body frame if ( attitudeConstraintType == "OrbitNormal" ) { referenceVector[0] = -1; referenceVector[1] = 0; referenceVector[2] = 0; constraintVector[0] = 0; constraintVector[1] = 1; constraintVector[2] = 0; } else if ( attitudeConstraintType == "Velocity" ) { referenceVector[0] = -1; referenceVector[1] = 0; referenceVector[2] = 0; constraintVector[0] = 0; constraintVector[1] = 0; constraintVector[2] = -1; } // RBi calculation using TRIAD (from LVLH to body frame) Rmatrix33 RiB = TRIAD( bodyAlignmentVector, bodyConstraintVector, referenceVector, constraintVector ); // the rotation matrix (from body to inertial) dcm = RIi*RiB; // the final rotation matrix (from inertial to body) dcm = dcm.Transpose(); // We do NOT calculate angular velocity for Nadir. // TODO : Throw AttitudeException?? write warning - but what to return? /* Rmatrix33 wxIBB = - RBi*RiIDot*dcm.Transpose(); Rvector3 wIBB; wIBB.Set(wxIBB(2,1),wxIBB(0,2),wxIBB(1,0)); */ } //------------------------------------------------------------------------------ // private methods //------------------------------------------------------------------------------ // none
34.040107
105
0.510643
[ "object", "vector", "model" ]
b98b4bd90a9ed1f1a176017c69d662b8de2d56ca
4,472
cc
C++
yundun-ds/src/model/DescribePrivilegesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
yundun-ds/src/model/DescribePrivilegesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
yundun-ds/src/model/DescribePrivilegesResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/yundun-ds/model/DescribePrivilegesResult.h> #include <json/json.h> using namespace AlibabaCloud::Yundun_ds; using namespace AlibabaCloud::Yundun_ds::Model; DescribePrivilegesResult::DescribePrivilegesResult() : ServiceResult() {} DescribePrivilegesResult::DescribePrivilegesResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribePrivilegesResult::~DescribePrivilegesResult() {} void DescribePrivilegesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allItemsNode = value["Items"]["Privilege"]; for (auto valueItemsPrivilege : allItemsNode) { Privilege itemsObject; if(!valueItemsPrivilege["Id"].isNull()) itemsObject.id = std::stol(valueItemsPrivilege["Id"].asString()); if(!valueItemsPrivilege["AccountId"].isNull()) itemsObject.accountId = std::stol(valueItemsPrivilege["AccountId"].asString()); if(!valueItemsPrivilege["AccountType"].isNull()) itemsObject.accountType = std::stoi(valueItemsPrivilege["AccountType"].asString()); if(!valueItemsPrivilege["UseAccountId"].isNull()) itemsObject.useAccountId = std::stol(valueItemsPrivilege["UseAccountId"].asString()); if(!valueItemsPrivilege["UseAccountType"].isNull()) itemsObject.useAccountType = std::stoi(valueItemsPrivilege["UseAccountType"].asString()); if(!valueItemsPrivilege["ProductName"].isNull()) itemsObject.productName = valueItemsPrivilege["ProductName"].asString(); if(!valueItemsPrivilege["productCode"].isNull()) itemsObject.productCode = valueItemsPrivilege["productCode"].asString(); if(!valueItemsPrivilege["DataType"].isNull()) itemsObject.dataType = valueItemsPrivilege["DataType"].asString(); if(!valueItemsPrivilege["DataTypeId"].isNull()) itemsObject.dataTypeId = valueItemsPrivilege["DataTypeId"].asString(); if(!valueItemsPrivilege["DataTypeName"].isNull()) itemsObject.dataTypeName = valueItemsPrivilege["DataTypeName"].asString(); if(!valueItemsPrivilege["DataInstance"].isNull()) itemsObject.dataInstance = valueItemsPrivilege["DataInstance"].asString(); if(!valueItemsPrivilege["DataTable"].isNull()) itemsObject.dataTable = valueItemsPrivilege["DataTable"].asString(); if(!valueItemsPrivilege["DataColumn"].isNull()) itemsObject.dataColumn = valueItemsPrivilege["DataColumn"].asString(); if(!valueItemsPrivilege["DataPackage"].isNull()) itemsObject.dataPackage = valueItemsPrivilege["DataPackage"].asString(); if(!valueItemsPrivilege["ResourceName"].isNull()) itemsObject.resourceName = valueItemsPrivilege["ResourceName"].asString(); if(!valueItemsPrivilege["ResourcePath"].isNull()) itemsObject.resourcePath = valueItemsPrivilege["ResourcePath"].asString(); if(!valueItemsPrivilege["Operation"].isNull()) itemsObject.operation = valueItemsPrivilege["Operation"].asString(); if(!valueItemsPrivilege["PolicyCondition"].isNull()) itemsObject.policyCondition = valueItemsPrivilege["PolicyCondition"].asString(); if(!valueItemsPrivilege["Sensitive"].isNull()) itemsObject.sensitive = valueItemsPrivilege["Sensitive"].asString(); items_.push_back(itemsObject); } if(!value["PageSize"].isNull()) pageSize_ = std::stoi(value["PageSize"].asString()); if(!value["CurrentPage"].isNull()) currentPage_ = std::stoi(value["CurrentPage"].asString()); if(!value["TotalCount"].isNull()) totalCount_ = std::stoi(value["TotalCount"].asString()); } int DescribePrivilegesResult::getTotalCount()const { return totalCount_; } int DescribePrivilegesResult::getPageSize()const { return pageSize_; } int DescribePrivilegesResult::getCurrentPage()const { return currentPage_; } std::vector<DescribePrivilegesResult::Privilege> DescribePrivilegesResult::getItems()const { return items_; }
38.886957
92
0.761181
[ "vector", "model" ]
b98bb4be3a1c2f51973b9349f58f1210d80cf2a9
38,734
cpp
C++
td4.cpp
sijnstra/VDK-80-Linux
d5e42f798d8288abf4f4e907d857389bcb3bfc87
[ "RSA-MD" ]
2
2020-06-30T08:47:35.000Z
2022-01-05T23:50:37.000Z
td4.cpp
sijnstra/VDK-80-Linux
d5e42f798d8288abf4f4e907d857389bcb3bfc87
[ "RSA-MD" ]
1
2021-05-30T12:01:07.000Z
2021-07-04T04:56:06.000Z
td4.cpp
sijnstra/VDK-80-Linux
d5e42f798d8288abf4f4e907d857389bcb3bfc87
[ "RSA-MD" ]
2
2022-01-06T02:44:32.000Z
2022-02-08T15:47:31.000Z
/** @file td4.cpp @brief based on TRS-80 Virtual Disk Kit v1.7 for Windows by Miguel Dutra Linux port VDK-80-Linux done by Mike Gore, 2016 @par Tools to Read and Write files inside common TRS-80 emulator images @par Copyright &copy; 2016 Miguel Dutra, GPL License @par You are free to use this code under the terms of GPL please retain a copy of this notice in any code you use it in. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. @par Original Windows Code @see http://www.trs-80.com/wordpress/category/contributors/miguel-dutra/ @see http://www.trs-80.com/wordpress/dsk-and-dmk-image-utilities/ @see Miguel Dutra www.mdutra.com */ //--------------------------------------------------------------------------------- // Operating System Interface for TRSDOS (Model 4) //--------------------------------------------------------------------------------- #include "windows.h" #include "v80.h" #include "vdi.h" #include "osi.h" #include "td4.h" //--------------------------------------------------------------------------------- // Initialize member variables //--------------------------------------------------------------------------------- CTD4::CTD4() : m_pDir(NULL), m_nDirTrack(0), m_nDirSectors(0), m_nMaxDirSectors(0), m_nSides(0), m_nSectorsPerTrack(0), m_nGranulesPerTrack(0), m_nGranulesPerCylinder(0), m_nSectorsPerGranule(0), m_dwFilePos(0), m_wSector(0), m_Buffer() { } //--------------------------------------------------------------------------------- // Release allocated memory //--------------------------------------------------------------------------------- CTD4::~CTD4() { if (m_pDir != NULL) free(m_pDir); } //--------------------------------------------------------------------------------- // Validate DOS version and define operating parameters //--------------------------------------------------------------------------------- DWORD CTD4::Load(CVDI* pVDI, DWORD dwFlags) { BYTE nSides; DWORD dwBytes; DWORD dwError = NO_ERROR; // Copy VDI pointer and user flags to member variables m_pVDI = pVDI; m_dwFlags = dwFlags; // Get disk geometry m_pVDI->GetDG(m_DG); // Calculate the number of disk sides if (m_dwFlags & V80_FLAG_SS) m_nSides = 1; else if (m_dwFlags & V80_FLAG_DS) m_nSides = 2; else m_nSides = m_DG.LT.nLastSide - m_DG.LT.nFirstSide + 1; // Calculate the number of sectors per track m_nSectorsPerTrack = m_DG.LT.nLastSector - m_DG.LT.nFirstSector + 1; // Check internal buffer size (just in case) if (sizeof(m_Buffer) < m_DG.FT.wSectorSize) { dwError = ERROR_INVALID_USER_BUFFER; goto Done; } // Read boot sector if ((dwError = m_pVDI->Read(m_DG.FT.nTrack, m_DG.FT.nFirstSide, m_DG.FT.nFirstSector, m_Buffer, m_DG.FT.wSectorSize)) != NO_ERROR) goto Done; // Get directory track and reset MSB (set on some DOS to indicate the disk density) m_nDirTrack = m_Buffer[2] & 0x7F; // Calculate the number of directory sectors m_nDirSectors = m_nSectorsPerTrack * m_nSides; // Max Dir Sectors = HIT Size / Entries per Sector m_nMaxDirSectors = (m_DG.LT.wSectorSize / (BYTE)(m_DG.LT.wSectorSize / sizeof(TD4_FPDE))); // If dir sectors exceeds max sectors, limit to max if (m_nDirSectors > m_nMaxDirSectors) m_nDirSectors = m_nMaxDirSectors; // If not first Load, release the previously allocated memory if (m_pDir != NULL) free(m_pDir); // Calculate needed memory to hold the entire directory dwBytes = m_nDirSectors * m_DG.LT.wSectorSize + (V80_MEM - (m_nDirSectors * m_DG.LT.wSectorSize) % V80_MEM); // Allocate memory for the entire directory if ((m_pDir = (BYTE*)calloc(dwBytes,1)) == NULL) { dwError = ERROR_OUTOFMEMORY; goto Done; } // Load directory into memory if ((dwError = DirRW(TD4_DIR_READ)) != NO_ERROR) goto Done; // Calculate DOS disk parameters nSides = ((((TD4_GAT*)m_pDir)->nDiskConfig & TD4_GAT_SIDES) >> 5) + 1; if (!(m_dwFlags & (V80_FLAG_SS+V80_FLAG_DS)) && (nSides < m_nSides)) m_nSides = nSides; m_nGranulesPerTrack = (((TD4_GAT*)m_pDir)->nDiskConfig & TD4_GAT_GRANULES) + 1; m_nGranulesPerCylinder = m_nGranulesPerTrack * m_nSides; m_nSectorsPerGranule = m_nSectorsPerTrack / m_nGranulesPerTrack; // GranulesPerCylinder must fit in a 8-bit GAT byte if (m_nGranulesPerCylinder < 2 || m_nGranulesPerCylinder > 8) { dwError = ERROR_NOT_DOS_DISK; goto Done; } // This division must leave no remainder if (m_nSectorsPerTrack % m_nGranulesPerTrack != 0) { dwError = ERROR_NOT_DOS_DISK; goto Done; } // SectorsPerGranule must be either 5 or 8 for SD disks if (m_DG.LT.nDensity == VDI_DENSITY_SINGLE && m_nSectorsPerGranule != 5 && m_nSectorsPerGranule != 8) { dwError = ERROR_NOT_DOS_DISK; goto Done; } // SectorsPerGranule must be either 6 or 10 for DD disks if (m_DG.LT.nDensity == VDI_DENSITY_DOUBLE && m_nSectorsPerGranule != 6 && m_nSectorsPerGranule != 10) { dwError = ERROR_NOT_DOS_DISK; goto Done; } // Check directory structure if (!(m_dwFlags & V80_FLAG_CHKDIR)) if ((dwError = CheckDir()) != NO_ERROR) goto Done; Done: return dwError; } //--------------------------------------------------------------------------------- // Return a pointer to the first/next directory entry //--------------------------------------------------------------------------------- DWORD CTD4::Dir(void** pFile, OSI_DIR nFlag) { TD4_HIT nMode = (nFlag == OSI_DIR_FIND_FIRST ? TD4_HIT_FIND_FIRST_USED : TD4_HIT_FIND_NEXT_USED); DWORD dwError = NO_ERROR; BYTE x; do { dwError = ScanHIT(pFile, nMode); // Return a pointer to the first/next non-empty file entry if (dwError != NO_ERROR) break; // Change the mode to "next" for the remaining searches nMode = TD4_HIT_FIND_NEXT_USED; x = ((TD4_FPDE*)(*pFile))->nAttributes[0]; } // Repeat until we get a pointer to a file entry which is Active and Primary while (!(((TD4_FPDE*)(*pFile))->nAttributes[0] & TD4_ATTR0_ACTIVE) || (((TD4_FPDE*)(*pFile))->nAttributes[0] & TD4_ATTR0_EXTENDED)); return dwError; } //--------------------------------------------------------------------------------- // Return a pointer to the directory entry matching the file name //--------------------------------------------------------------------------------- DWORD CTD4::Open(void** pFile, const char cName[11]) { TD4_HIT nMode = TD4_HIT_FIND_FIRST_USED; BYTE nHash = Hash(cName); DWORD dwError = NO_ERROR; // Invalidate any previous Seek() m_wSector = 0xFFFF; // Repeat while there is no file match while (true) { // Get first/next file whose hash matches the requested name if ((dwError = ScanHIT(pFile, nMode, nHash)) != NO_ERROR) break; // Change mode to "next" for the remaining searches nMode = TD4_HIT_FIND_NEXT_USED; // If file entry is not Active or Primary, skip to the next if (!(((TD4_FPDE*)(*pFile))->nAttributes[0] & TD4_ATTR0_ACTIVE) || (((TD4_FPDE*)(*pFile))->nAttributes[0] & TD4_ATTR0_EXTENDED)) continue; // If entry's filename matches the caller's filename, we are done // FIXME if (memcmp(((TD4_FPDE*)(*pFile))->cName, cName, sizeof(cName)) == 0) if (memcmp(((TD4_FPDE*)(*pFile))->cName, cName, 11) == 0) break; } return dwError; } //--------------------------------------------------------------------------------- // Create a new file with the indicated name and size //--------------------------------------------------------------------------------- DWORD CTD4::Create(void** pFile, OSI_FILE& File) { TD4_EXTENT Extent; void* pPrevious; BYTE nGranules; BYTE nExtent = 0; DWORD dwError = NO_ERROR; // Invalidate any previous Seek() m_wSector = 0xFFFF; // Get a new directory entry if ((dwError = GetFDE(pFile)) != NO_ERROR) goto Abort; // Set directory entry as Active ((TD4_FPDE*)(*pFile))->nAttributes[0] = TD4_ATTR0_ACTIVE; // Set file password ((TD4_FPDE*)(*pFile))->wOwnerHash = 0x4296; ((TD4_FPDE*)(*pFile))->wUserHash = 0x4296; // Set file properties as indicated by the caller SetFile(*pFile, File, false); // Calculate the number of granules needed nGranules = ((TD4_FPDE*)(*pFile))->wERN / m_nSectorsPerGranule + (((TD4_FPDE*)(*pFile))->wERN % m_nSectorsPerGranule > 0 ? 1 : 0); if (nGranules == 0 && ((TD4_FPDE*)(*pFile))->nEOF > 0) nGranules++; // Repeat while the number of needed granules is greater than zero while (nGranules > 0) { // Create one extent with as many granules as possible, based on the calculated quantity if ((dwError = CreateExtent(Extent, nGranules)) != NO_ERROR) goto Abort; // Increment extent counter nExtent++; // Copy extent data to the directory entry if ((dwError = CopyExtent(*pFile, TD4_EXTENT_SET, nExtent, Extent)) != NO_ERROR) { // Abort if error is other than "extent not found" if (dwError != ERROR_NOT_FOUND) goto Abort; // Preserve current file handle pPrevious = *pFile; // Get an additional directory entry if ((dwError = GetFDE(pFile)) != NO_ERROR) goto Abort; // Set a forward link to the newly created directory entry ((TD4_FPDE*)pPrevious)->Link.nCylinder = 0xFE; ((TD4_FPDE*)pPrevious)->Link.nGranules = FDE2DEC(*pFile); // Set a backward link from the previously existing directory entry ((TD4_FPDE*)(*pFile))->nAttributes[0] = TD4_ATTR0_ACTIVE|TD4_ATTR0_EXTENDED; ((TD4_FPDE*)(*pFile))->nAttributes[1] = FDE2DEC(pPrevious); // Copy file name and extention to the new directory entry memcpy(((TD4_FPDE*)pFile)->cName, File.szName, sizeof(File.szName) - 1); memcpy(((TD4_FPDE*)pFile)->cType, File.szType, sizeof(File.szType) - 1); // Set the corresponding HIT DEC with calculated name hash m_pDir[m_DG.LT.wSectorSize + FDE2DEC(pFile)] = Hash((const char *) ((TD4_FPDE*)pFile)->cName); continue; } // Subtract number of allocated granules in this extent from the total required nGranules -= (Extent.nGranules & TD4_GRANULE_COUNT) + 1; } // Write the updated directory data and exit dwError = DirRW(TD4_DIR_WRITE); goto Done; // Restore previous directory state Abort: DirRW(TD4_DIR_READ); Done: return dwError; } //--------------------------------------------------------------------------------- // Move the file pointer //--------------------------------------------------------------------------------- DWORD CTD4::Seek(void* pFile, DWORD dwPos) { TD4_EXTENT Extent; int nGranuleSectors; int nRemainingSectors; int nExtent = 0; DWORD dwError = NO_ERROR; // Calculate the number of sectors required to reach the requested file position nRemainingSectors = dwPos / m_DG.LT.wSectorSize; while (true) { // Increment extent counter nExtent++; // Retrieve the corresponding extent data if ((dwError = CopyExtent(pFile, TD4_EXTENT_GET, nExtent, Extent)) != NO_ERROR) { m_wSector = 0xFFFF; break; } // Calculate the number of contiguous sectors contained in this extent nGranuleSectors = ((Extent.nGranules & TD4_GRANULE_COUNT) + 1) * m_nSectorsPerGranule; // Check whether it exceeds our need if (nGranuleSectors > nRemainingSectors) { // RelativeSector = (Cylinder * GranulesPerCylinder + InitialGranule) * SectorsPerGranule + RemainingSectors m_wSector = ((Extent.nCylinder * m_nGranulesPerCylinder) + ((Extent.nGranules & TD4_GRANULE_INITIAL) >> 5)) * m_nSectorsPerGranule + nRemainingSectors; m_dwFilePos = dwPos; break; } // Otherwise, subtract the number of extent sectors from the total required nRemainingSectors -= nGranuleSectors; } return dwError; } //--------------------------------------------------------------------------------- // Read data from file //--------------------------------------------------------------------------------- DWORD CTD4::Read(void* pFile, BYTE* pBuffer, DWORD& dwBytes) { VDI_TRACK* pTrack; BYTE nTrack; BYTE nSide; BYTE nSector; DWORD dwFileSize; WORD wSectorBegin; WORD wSectorEnd; WORD wLength; DWORD dwRead = 0; DWORD dwError = NO_ERROR; // Get file size dwFileSize = GetFileSize(pFile); // Repeat while there is something left to read while (dwBytes - dwRead > 0) { // Check whether the last Seek() was successful if (m_wSector == 0xFFFF) { dwError = ERROR_SEEK; break; } // Check whether the requested position doesn't exceed the file size if (m_dwFilePos > dwFileSize) { dwError = ERROR_READ_FAULT; break; } // Convert relative sector into Track, Side, Sector CHS(m_wSector, nTrack, nSide, nSector); // Get a pointer to the correct track descriptor pTrack = (nTrack == m_DG.FT.nTrack ? &m_DG.FT : &m_DG.LT); // Read sector into internal buffer if ((dwError = m_pVDI->Read(nTrack, nSide, nSector, m_Buffer, pTrack->wSectorSize)) != NO_ERROR) break; // Calculate the starting transfer point wSectorBegin = m_dwFilePos % pTrack->wSectorSize; // Calculate the ending transfer point wSectorEnd = (dwFileSize - m_dwFilePos >= pTrack->wSectorSize ? pTrack->wSectorSize : dwFileSize % pTrack->wSectorSize); // Calculate the transfer length wLength = ((wSectorEnd - wSectorBegin) <= (dwBytes - dwRead) ? wSectorEnd - wSectorBegin : dwBytes - dwRead); // Copy data from internal buffer to the caller's buffer memcpy(pBuffer, &m_Buffer[wSectorBegin], wLength); // Update bytes count and caller's buffer pointer dwRead += wLength; pBuffer += wLength; // Advance file pointer Seek(pFile, m_dwFilePos + wLength); } dwBytes = dwRead; return dwError; } //--------------------------------------------------------------------------------- // Save data to file //--------------------------------------------------------------------------------- DWORD CTD4::Write(void* pFile, BYTE* pBuffer, DWORD& dwBytes) { VDI_TRACK* pTrack; BYTE nTrack; BYTE nSide; BYTE nSector; DWORD dwFileSize; WORD wSectorBegin; WORD wSectorEnd; WORD wLength; DWORD dwWritten = 0; DWORD dwError = NO_ERROR; dwFileSize = GetFileSize(pFile); while (dwBytes - dwWritten > 0) { // Check whether the last Seek() was successful if (m_wSector == 0xFFFF) { dwError = ERROR_SEEK; break; } // Check whether the requested position doesn't exceed the file size if (m_dwFilePos > dwFileSize) { dwError = ERROR_WRITE_FAULT; break; } // Convert relative sector into Track, Side, Sector CHS(m_wSector, nTrack, nSide, nSector); // Get a pointer to the correct track descriptor pTrack = (nTrack == m_DG.FT.nTrack ? &m_DG.FT : &m_DG.LT); // Calculate the starting transfer point wSectorBegin = m_dwFilePos % pTrack->wSectorSize; // Calculate the ending transfer point wSectorEnd = (dwFileSize - m_dwFilePos >= pTrack->wSectorSize ? pTrack->wSectorSize : dwFileSize % pTrack->wSectorSize); // Calculate the transfer length wLength = ((wSectorEnd - wSectorBegin) <= (dwBytes - dwWritten) ? wSectorEnd - wSectorBegin : dwBytes - dwWritten); // If needed, read sector before writing to it if (wLength < pTrack->wSectorSize) { if ((dwError = m_pVDI->Read(nTrack, nSide, nSector, m_Buffer, pTrack->wSectorSize)) != NO_ERROR) break; } // Copy data from caller's buffer to the internal buffer memcpy(&m_Buffer[wSectorBegin], pBuffer, wLength); // Write sector from internal buffer if ((dwError = m_pVDI->Write(nTrack, nSide, nSector, m_Buffer, pTrack->wSectorSize)) != NO_ERROR) break; // Update bytes count and caller's buffer pointer dwWritten += wLength; pBuffer += wLength; // Advance file pointer Seek(pFile, m_dwFilePos + wLength); } dwBytes = dwWritten; return dwError; } //--------------------------------------------------------------------------------- // Delete file //--------------------------------------------------------------------------------- DWORD CTD4::Delete(void* pFile) { TD4_EXTENT Extent; DWORD dwError = NO_ERROR; // Invalidate any previous Seek() m_wSector = 0xFFFF; // Inactivate directory entry ((TD4_FPDE*)pFile)->nAttributes[0] &= !TD4_ATTR0_ACTIVE; // Release corresponding HIT slot m_pDir[m_DG.LT.wSectorSize + FDE2DEC(pFile)] = 0; // Loop through all extents releasing every allocated granule for (int x = 1; (dwError = CopyExtent(pFile, TD4_EXTENT_GET, x, Extent)) == NO_ERROR; x++) { if ((dwError = DeleteExtent(Extent)) != NO_ERROR) break; } // If exited the loop because reached the end of the extents table if (dwError == ERROR_NO_MATCH) dwError = DirRW(TD4_DIR_WRITE); // Save the directory else DirRW(TD4_DIR_READ); // Otherwise, restore its previous state return dwError; } //--------------------------------------------------------------------------------- // Get DOS information //--------------------------------------------------------------------------------- void CTD4::GetDOS(OSI_DOS& DOS) { // Zero the structure memset(&DOS, 0, sizeof(OSI_DOS)); // Get DOS version DOS.nVersion = ((TD4_GAT*)m_pDir)->nDosVersion; // Get disk name memcpy(DOS.szName, ((TD4_GAT*)m_pDir)->cDiskName, sizeof(DOS.szName) - 1); // Get disk date memcpy(&DOS.szDate, ((TD4_GAT*)m_pDir)->cDiskDate, sizeof(DOS.szDate) - 1); } //--------------------------------------------------------------------------------- // Set DOS information //--------------------------------------------------------------------------------- DWORD CTD4::SetDOS(OSI_DOS& DOS) { // Set DOS version ((TD4_GAT*)m_pDir)->nDosVersion = DOS.nVersion; // Set disk name memcpy(((TD4_GAT*)m_pDir)->cDiskName, DOS.szName, sizeof(DOS.szName) - 1); // Set disk date memcpy(((TD4_GAT*)m_pDir)->cDiskDate, &DOS.szDate, sizeof(DOS.szDate) - 1); return DirRW(TD4_DIR_WRITE); } //--------------------------------------------------------------------------------- // Get file information //--------------------------------------------------------------------------------- void CTD4::GetFile(void* pFile, OSI_FILE& File) { // Zero the structure memset(&File, 0, sizeof(OSI_FILE)); // Copy file name and extention memcpy(File.szName, ((TD4_FPDE*)pFile)->cName, sizeof(File.szName) - 1); memcpy(File.szType, ((TD4_FPDE*)pFile)->cType, sizeof(File.szType) - 1); // Get file size File.dwSize = GetFileSize(pFile); // Get file date File.Date.nMonth = (((TD4_FPDE*)pFile)->nAttributes[1] & TD4_ATTR1_MONTH); File.Date.nDay = (((TD4_FPDE*)pFile)->nAttributes[2] & TD4_ATTR2_DAY) >> 3; File.Date.wYear = (((TD4_FPDE*)pFile)->nAttributes[2] & TD4_ATTR2_YEAR) + (File.Date.nMonth > 0 ? 1980 : 0); // If not a valid date, make it all zeroes if (File.Date.nMonth < 1 || File.Date.nMonth > 12 || File.Date.nDay < 1 || File.Date.nDay > 31) memset(&File.Date, 0, sizeof(File.Date)); // Get file attributes File.nAccess = ((TD4_FPDE*)pFile)->nAttributes[0] & TD4_ATTR0_ACCESS; File.bSystem = ((TD4_FPDE*)pFile)->nAttributes[0] & TD4_ATTR0_SYSTEM; File.bInvisible = ((TD4_FPDE*)pFile)->nAttributes[0] & TD4_ATTR0_INVISIBLE; File.bModified = ((TD4_FPDE*)pFile)->nAttributes[1] & TD4_ATTR1_MODIFIED; } //--------------------------------------------------------------------------------- // Set file information (public) //--------------------------------------------------------------------------------- DWORD CTD4::SetFile(void* pFile, OSI_FILE& File) { return SetFile(pFile, File, true); } //--------------------------------------------------------------------------------- // Set file information (protected) //--------------------------------------------------------------------------------- DWORD CTD4::SetFile(void* pFile, OSI_FILE& File, bool bCommit) { // Copy file name and extention memcpy(((TD4_FPDE*)pFile)->cName, File.szName, sizeof(File.szName) - 1); memcpy(((TD4_FPDE*)pFile)->cType, File.szType, sizeof(File.szType) - 1); // Set corresponding HIT DEC to the newly calculated name hash m_pDir[m_DG.LT.wSectorSize + FDE2DEC(pFile)] = Hash((const char *) ((TD4_FPDE*)pFile)->cName); // Set file size ((TD4_FPDE*)pFile)->nEOF = File.dwSize % m_DG.LT.wSectorSize; ((TD4_FPDE*)pFile)->wERN = File.dwSize / m_DG.LT.wSectorSize + (((TD4_FPDE*)pFile)->nEOF > 0 ? 1 : 0); // Set file date ((TD4_FPDE*)pFile)->nAttributes[1] &= ~TD4_ATTR1_MONTH; ((TD4_FPDE*)pFile)->nAttributes[1] |= File.Date.nMonth; ((TD4_FPDE*)pFile)->nAttributes[2] &= ~TD4_ATTR2_DAY; ((TD4_FPDE*)pFile)->nAttributes[2] |= (File.Date.nDay << 3); ((TD4_FPDE*)pFile)->nAttributes[2] &= ~TD4_ATTR2_YEAR; ((TD4_FPDE*)pFile)->nAttributes[2] |= (File.Date.wYear - (File.Date.nMonth > 0 ? 1980 : 0)); // Set file attributes ((TD4_FPDE*)pFile)->nAttributes[0] &= ~TD4_ATTR0_ACCESS; ((TD4_FPDE*)pFile)->nAttributes[0] |= File.nAccess; ((TD4_FPDE*)pFile)->nAttributes[0] &= ~TD4_ATTR0_SYSTEM; ((TD4_FPDE*)pFile)->nAttributes[0] |= (TD4_ATTR0_SYSTEM * File.bSystem); ((TD4_FPDE*)pFile)->nAttributes[0] &= ~TD4_ATTR0_INVISIBLE; ((TD4_FPDE*)pFile)->nAttributes[0] |= (TD4_ATTR0_INVISIBLE * File.bInvisible); ((TD4_FPDE*)pFile)->nAttributes[1] &= ~TD4_ATTR1_MODIFIED; ((TD4_FPDE*)pFile)->nAttributes[1] |= (TD4_ATTR1_MODIFIED * File.bModified); return (bCommit ? DirRW(TD4_DIR_WRITE) : NO_ERROR); } //--------------------------------------------------------------------------------- // Get file size //--------------------------------------------------------------------------------- DWORD CTD4::GetFileSize(void* pFile) { WORD wERN = ((TD4_FPDE*)pFile)->wERN; BYTE nEOF = ((TD4_FPDE*)pFile)->nEOF; return wERN * m_DG.LT.wSectorSize - (nEOF > 0 ? m_DG.LT.wSectorSize - nEOF : 0); } //--------------------------------------------------------------------------------- // Read or Write the entire directory //--------------------------------------------------------------------------------- DWORD CTD4::DirRW(TD4_DIR nMode) { DWORD dwOffset = 0; DWORD dwError = NO_ERROR; // Go through every side for (BYTE nSide = 0; nSide < m_nSides; nSide++) { // Go through every sector for (BYTE nSector = m_DG.LT.nFirstSector; nSector <= m_DG.LT.nLastSector; nSector++, dwOffset += m_DG.LT.wSectorSize) { // Read or write the sector according to the requested mode if (nMode == TD4_DIR_WRITE) { if ((dwError = m_pVDI->Write(m_nDirTrack, m_DG.LT.nFirstSide + nSide, nSector, &m_pDir[dwOffset], m_DG.LT.wSectorSize)) != NO_ERROR) goto Done; } else { if ((dwError = m_pVDI->Read(m_nDirTrack, m_DG.LT.nFirstSide + nSide, nSector, &m_pDir[dwOffset], m_DG.LT.wSectorSize)) != NO_ERROR) goto Done; } } } Done: return dwError; } //--------------------------------------------------------------------------------- // Check the directory structure //--------------------------------------------------------------------------------- DWORD CTD4::CheckDir(void) { int x; void* pFile = NULL; int nFiles = 0; DWORD dwError = NO_ERROR; // Validate disk name for (x = 0; x < 8; x++) { if (((TD4_GAT*)m_pDir)->cDiskName[x] < ' ' || ((TD4_GAT*)m_pDir)->cDiskName[x] > 'z') goto Error; } // Validate disk date for (x = 0; x < 8; x++) { if (((TD4_GAT*)m_pDir)->cDiskDate[x] < ' ' || ((TD4_GAT*)m_pDir)->cDiskDate[x] > 'z') goto Error; } // Validate each file name in the directory (while counting the number of files) for (nFiles = 0; (dwError = Dir(&pFile, (pFile == NULL ? OSI_DIR_FIND_FIRST : OSI_DIR_FIND_NEXT))) == NO_ERROR; nFiles++) { // First 8 characters can be non-blanks for (x = 0; x < 8 && ((TD4_FPDE*)pFile)->cName[x] >= '0' && ((TD4_FPDE*)pFile)->cName[x] <= 'z'; x++); // But first one must be non-blank to be valid if (x == 0) goto Error; // If a blank is found, then only blanks can be used up to the end of the name for ( ; x < 8 && ((TD4_FPDE*)pFile)->cName[x] == ' '; x++); // If not, then this name is invalid if (x < 8) goto Error; // The extension can have up to 3 non-blank characters for (x = 0; x < 3 && ((TD4_FPDE*)pFile)->cType[x] >= '0' && ((TD4_FPDE*)pFile)->cType[x] <= 'z'; x++); // If a blank is found, then only blanks can be used up to the end of the extension for ( ; x < 3 && ((TD4_FPDE*)pFile)->cType[x] == ' '; x++); // If not, then this extension is invalid if (x < 3) goto Error; } // No error if exiting on "no more files" // but found files if (dwError == ERROR_NO_MORE_FILES) // && nFiles > 0) // The disk may be empty { dwError = NO_ERROR; goto Done; } Error: dwError = ERROR_FILE_CORRUPT; Done: return dwError; } //--------------------------------------------------------------------------------- // Scan the Hash Index Table //--------------------------------------------------------------------------------- DWORD CTD4::ScanHIT(void** pFile, TD4_HIT nMode, BYTE nHash) { static int nLastRow = -1; static int nLastCol = 0; int nRows, nRow; int nCols, nCol; int nSlot; DWORD dwError = NO_ERROR; // If mode is any "Find First", reset static variables if (nMode != TD4_HIT_FIND_NEXT_USED) { nLastRow = -1; nLastCol = 0; } // Retrieve last values from static variables nRow = nLastRow; nCol = nLastCol; // Calculate max HIT rows and columns nRows = m_DG.LT.wSectorSize / sizeof(TD4_FPDE); nCols = m_nDirSectors - 2; while (true) { // Increment row nRow++; // If row reaches max, reset it and advance to the next column if (nRow >= nRows) { nRow = 0; nCol++; } // If column reaches max, then we have reached the end of the HIT if (nCol >= nCols) { if (nHash != 0) dwError = ERROR_FILE_NOT_FOUND; else if (nMode == TD4_HIT_FIND_FIRST_FREE) dwError = ERROR_DISK_FULL; else dwError = ERROR_NO_MORE_FILES; break; } // Get value in HIT[Row * MaxDirSectors + Col] (MaxDirSectors normally equals 32) nSlot = m_pDir[m_DG.LT.wSectorSize + (nRow * m_nMaxDirSectors) + nCol]; // If this is not what we are looking for, skip to the next if ((nMode == TD4_HIT_FIND_FIRST_FREE && nSlot != 0) || (nMode != TD4_HIT_FIND_FIRST_FREE && nSlot == 0)) continue; // If there is a hash to match and it doesn't match, skip to the next if (nHash != 0 && nHash != nSlot) continue; if ((*pFile = DEC2FDE((nRow << 5) + nCol)) == NULL) // Return pointer corresponding to the current Directory Entry Code (DEC) if ((*pFile = DEC2FDE((nRow << 5) + nCol)) == NULL) dwError = ERROR_INVALID_ADDRESS; break; } // Update static variables nLastRow = nRow; nLastCol = nCol; return dwError; } //--------------------------------------------------------------------------------- // Allocate disk space //--------------------------------------------------------------------------------- DWORD CTD4::CreateExtent(TD4_EXTENT& Extent, BYTE nGranules) { BYTE nValidCylinders; BYTE nInitialCylinder = 0; BYTE nInitialGranule = 0; BYTE nCurrentCylinder = 0; BYTE nCurrentGranule = 0; BYTE nAllocatedGranules = 0; DWORD dwError = NO_ERROR; // Requested number of granules must be greater than zero if (nGranules == 0) { dwError = ERROR_INVALID_PARAMETER; goto Done; } // Calculate the number of valid cylinders nValidCylinders = m_DG.LT.nTrack - m_DG.FT.nTrack + 1; // Find first empty slot (0) then continue up to the first non-empty slot (1) for (int nExpectedBit = 0; nExpectedBit < 2; nExpectedBit++) { // Test state of 'CurrentGranule' at GAT[CurrentCylinder] while ((m_pDir[nCurrentCylinder] & (1 << nCurrentGranule)) != nExpectedBit) { // Check if we are in the "continue up to the first non-empty slot" phase if (nExpectedBit == 1) { // Set granule as reserved m_pDir[nCurrentCylinder] |= (1 << nCurrentGranule); nAllocatedGranules++; nGranules--; // Count of allocated granules must fit in 5 bits (so the max is 32) // Also exit when number of requested granules have been reached if (nAllocatedGranules == 32 || nGranules == 0) goto Stop; } // Advance to next granule nCurrentGranule++; // Check whether we've reached the cylinder's limit if (nCurrentGranule == m_nGranulesPerCylinder) { // Reset granule index and advance to the next cylinder nCurrentGranule = 0; nCurrentCylinder++; // Check whether we've reached the disk's limit if (nCurrentCylinder == nValidCylinders) { dwError = ERROR_DISK_FULL; goto Done; } } } // Check whether we are just leaving the "find the first empty slot" phase if (nExpectedBit == 0) { nInitialCylinder = nCurrentCylinder; nInitialGranule = nCurrentGranule; } } // Assemble Extent Stop: Extent.nCylinder = nInitialCylinder; Extent.nGranules = (nInitialGranule << 5) + (nAllocatedGranules - 1); // 3 MSB: Initial Granule, 5 LSB: Contiguous Granules minus 1 Done: return dwError; } //--------------------------------------------------------------------------------- // Release disk space //--------------------------------------------------------------------------------- DWORD CTD4::DeleteExtent(TD4_EXTENT& Extent) { DWORD dwError = NO_ERROR; // Get initial granule and count of granules in the extent int nIndex = (Extent.nGranules & TD4_GRANULE_INITIAL) >> 5; int nCount = (Extent.nGranules & TD4_GRANULE_COUNT) + 1; // Calculate the number of valid cylinders int nCylinders = m_DG.LT.nTrack - m_DG.FT.nTrack + 1; while (true) { // Reset bit nIndex of GAT[nCylinder] m_pDir[Extent.nCylinder] &= ~(1 << nIndex); // Repeat until nCount equals zero if (--nCount == 0) break; // If nIndex reaches the maximum number of granules per cylinder if (++nIndex == m_nGranulesPerCylinder) { // Reset nIndex and advance to the next cylinder nIndex = 0; // If have reached the end of the disk, then something is wrong if (++Extent.nCylinder == nCylinders) { dwError = ERROR_FLOPPY_WRONG_CYLINDER; break; } } } return dwError; } //--------------------------------------------------------------------------------- // Get or Set extent data //--------------------------------------------------------------------------------- DWORD CTD4::CopyExtent(void* pFile, TD4_EXT nMode, BYTE nExtent, TD4_EXTENT& Extent) { TD4_EXTENT* pExtent; DWORD dwError = NO_ERROR; // Go through the extents table for (int x = 1, y = 1; x < 6; x++) { // Point to File.Extent[x-1] pExtent = &(((TD4_FPDE*)pFile)->Extent[x - 1]); // Check whether last extent links this entry to another one if (pExtent->nCylinder == 0xFE && x == 5) { // The other extent field contains the DEC to the extended directory entry (FXDE) if ((pFile = DEC2FDE(pExtent->nGranules)) == NULL) { dwError = ERROR_INVALID_ADDRESS; goto Done; } // Restart from the beginning of the extents list x = 0; continue; } // Check whether we've reached the end of the extents table while trying to GET an extent's data if (pExtent->nCylinder == 0xFF && nMode == TD4_EXTENT_GET) break; // Check whether we've reached the requested extent number (but not a corrupted link) if (y == nExtent && x != 5) { if (nMode == TD4_EXTENT_GET) { Extent.nCylinder = pExtent->nCylinder; Extent.nGranules = pExtent->nGranules; } else { pExtent->nCylinder = Extent.nCylinder; pExtent->nGranules = Extent.nGranules; } goto Done; } // Advance to next extent y++; } dwError = ERROR_NO_MATCH; Done: return dwError; } //--------------------------------------------------------------------------------- // Return a pointer to an available File Directory Entry //--------------------------------------------------------------------------------- DWORD CTD4::GetFDE(void** pFile) { DWORD dwError = NO_ERROR; if ((dwError = ScanHIT(pFile, TD4_HIT_FIND_FIRST_FREE)) != NO_ERROR) goto Done; memset(*pFile, 0, sizeof(TD4_FPDE)); for (int x = 0; x < 5; x++) { ((TD4_FPDE*)(*pFile))->Extent[x].nCylinder = 0xFF; ((TD4_FPDE*)(*pFile))->Extent[x].nGranules = 0xFF; } Done: return dwError; } //--------------------------------------------------------------------------------- // Convert Directory Entry Code (DEC) into a pointer to File Directory Entry (FDE) //--------------------------------------------------------------------------------- void* CTD4::DEC2FDE(BYTE nDEC) { DWORD dwSectorOffset = ((nDEC & TD4_DEC_SECTOR) + 2) * m_DG.LT.wSectorSize; DWORD dwEntryOffset = ((nDEC & TD4_DEC_ENTRY) >> 5) * sizeof(TD4_FPDE); return ((nDEC & TD4_DEC_SECTOR) < m_nDirSectors ? &m_pDir[dwSectorOffset + dwEntryOffset] : NULL); } //--------------------------------------------------------------------------------- // Convert a pointer to a Directory Entry (FDE) into a Directory Entry Code (DEC) //--------------------------------------------------------------------------------- BYTE CTD4::FDE2DEC(void* pFile) { // ((pFile - pDir) - ((GAT + HIT) * SectorSize)) / sizeof(FPDE) BYTE nDEC = (((BYTE*)pFile - m_pDir) - (2 * m_DG.LT.wSectorSize)) / sizeof(TD4_FPDE); // Reorganize bits: 11111000 -> 00011111 return ((nDEC << 5) + (nDEC >> 3)); } //--------------------------------------------------------------------------------- // Return the hash code of a given file name //--------------------------------------------------------------------------------- BYTE CTD4::Hash(const char* pName) { BYTE nHash = 0; for (int x = 0; x < 11; x++) { nHash ^= pName[x]; nHash = (nHash << 1) + ((nHash & 0b10000000) >> 7); // rol nHash, 1 } return (nHash != 0 ? nHash : 0x01); } //--------------------------------------------------------------------------------- // Return the Cylinder/Head/Sector (CHS) of a given relative sector //--------------------------------------------------------------------------------- void CTD4::CHS(WORD wSector, BYTE& nTrack, BYTE& nSide, BYTE& nSector) { // Calculate SectorsPerCylinder int nSectorsPerCylinder = m_nSectorsPerTrack * m_nSides; // Track = RelativeSector / SectorsPerCylinder nTrack = wSector / nSectorsPerCylinder; // Side = Remainder / SectorsPerTrack nSide = (wSector - (nTrack * nSectorsPerCylinder)) / m_nSectorsPerTrack; // Sector = Remainder nSector = (wSector - (nTrack * nSectorsPerCylinder + nSide * m_nSectorsPerTrack)); // Adjust Track, Side, Sector // nTrack += m_DG.FT.nTrack; // Track number in Extent.Cylinder is supposed to be correct (adjusted) nSide += (nTrack == m_DG.FT.nTrack ? m_DG.FT.nFirstSide : m_DG.LT.nFirstSide); nSector += (nTrack == m_DG.FT.nTrack ? m_DG.FT.nFirstSector : m_DG.LT.nFirstSector); }
31.237097
163
0.534104
[ "geometry", "model" ]
b98e9a4df1142641b8a092a266666197585e9590
783
hpp
C++
Outputs/CRT/Internals/Rectangle.hpp
reidrac/CLK
a38974ef2e706d87f8ce7320b91c76c13dcede09
[ "MIT" ]
1
2019-07-05T18:09:34.000Z
2019-07-05T18:09:34.000Z
Outputs/CRT/Internals/Rectangle.hpp
reidrac/CLK
a38974ef2e706d87f8ce7320b91c76c13dcede09
[ "MIT" ]
null
null
null
Outputs/CRT/Internals/Rectangle.hpp
reidrac/CLK
a38974ef2e706d87f8ce7320b91c76c13dcede09
[ "MIT" ]
null
null
null
// // Rectangle.hpp // Clock Signal // // Created by Thomas Harte on 11/07/2018. // Copyright © 2018 Thomas Harte. All rights reserved. // #ifndef Rectangle_hpp #define Rectangle_hpp #include "OpenGL.hpp" #include "Shaders/Shader.hpp" #include <memory> namespace OpenGL { /*! Provides a wrapper for drawing a solid, single-colour rectangle. */ class Rectangle { public: /*! Instantiates an instance of Rectange with the coordinates given. */ Rectangle(float x, float y, float width, float height); /*! Draws this rectangle in the colour supplied. */ void draw(float red, float green, float blue); private: Shader pixel_shader_; GLuint drawing_vertex_array_ = 0, drawing_array_buffer_ = 0; GLint colour_uniform_; }; } #endif /* Rectangle_hpp */
18.642857
67
0.708812
[ "solid" ]
b98f2e6e17f81e31d426f2442b72758c20cd5908
75,125
hpp
C++
src/gnuplot-iostream.hpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/gnuplot-iostream.hpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/gnuplot-iostream.hpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
// vim:foldmethod=marker /* Copyright (c) 2013 Daniel Stahlke (dan@stahlke.org) 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. */ /* A C++ interface to gnuplot. * Web page: http://www.stahlke.org/dan/gnuplot-iostream * Documentation: https://github.com/dstahlke/gnuplot-iostream/wiki * * The whole library consists of this monolithic header file, for ease of installation (the * Makefile and *.cc files are only for examples and tests). * * TODO: * What version of boost is currently required? * Callbacks via gnuplot's 'bind' function. This would allow triggering user functions when * keys are pressed in the gnuplot window. However, it would require a PTY reader thread. * Maybe temporary files read in a thread can replace PTY stuff. */ #ifndef GNUPLOT_IOSTREAM_H #define GNUPLOT_IOSTREAM_H // {{{1 Includes and defines #define GNUPLOT_IOSTREAM_VERSION 2 #ifndef GNUPLOT_ENABLE_CXX11 # define GNUPLOT_ENABLE_CXX11 (__cplusplus >= 201103) #endif // C system includes #include <cstdio> #ifdef GNUPLOT_ENABLE_PTY # include <termios.h> # include <unistd.h> #ifdef __APPLE__ # include <util.h> #else # include <pty.h> #endif #endif // GNUPLOT_ENABLE_PTY // C++ system includes #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <iomanip> #include <vector> #include <complex> #include <cstdlib> #include <cmath> #if GNUPLOT_ENABLE_CXX11 # include <tuple> #endif #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #include <boost/version.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/mpl/bool.hpp> // This is the version of boost which has v3 of the filesystem libraries by default. #if BOOST_VERSION >= 104600 # define GNUPLOT_USE_TMPFILE # include <boost/filesystem.hpp> #endif // BOOST_VERSION // This is used because VS2008 doesn't have stdint.h. #include <boost/cstdint.hpp> // Note: this is here for reverse compatibility. The new way to enable blitz support is to // just include the gnuplot-iostream.h header after you include the blitz header (likewise for // armadillo). #ifdef GNUPLOT_ENABLE_BLITZ # include <blitz/array.h> #endif #ifdef BOOST_STATIC_ASSERT_MSG # define GNUPLOT_STATIC_ASSERT_MSG(cond, msg) BOOST_STATIC_ASSERT_MSG((cond), msg) #else # define GNUPLOT_STATIC_ASSERT_MSG(cond, msg) BOOST_STATIC_ASSERT((cond)) #endif // If this is defined, warn about use of deprecated functions. #ifdef GNUPLOT_DEPRECATE_WARN # ifdef __GNUC__ # define GNUPLOT_DEPRECATE(msg) __attribute__ ((deprecated(msg))) # elif defined(_MSC_VER) # define GNUPLOT_DEPRECATE(msg) __declspec(deprecated(msg)) # else # define GNUPLOT_DEPRECATE(msg) # endif #else # define GNUPLOT_DEPRECATE(msg) #endif // Patch for Windows by Damien Loison #ifdef _WIN32 # include <windows.h> # define GNUPLOT_PCLOSE _pclose # define GNUPLOT_POPEN _popen # define GNUPLOT_FILENO _fileno #else # define GNUPLOT_PCLOSE pclose # define GNUPLOT_POPEN popen # define GNUPLOT_FILENO fileno #endif #ifdef _WIN32 # define GNUPLOT_ISNAN _isnan #else // cppreference.com says std::isnan is only for C++11. However, this seems to work on Linux // and I am assuming that if isnan exists in math.h then std::isnan exists in cmath. # define GNUPLOT_ISNAN std::isnan #endif // MSVC gives a warning saying that fopen and getenv are not secure. But they are secure. // Unfortunately their replacement functions are not simple drop-in replacements. The best // solution is to just temporarily disable this warning whenever fopen or getenv is used. // http://stackoverflow.com/a/4805353/1048959 #if defined(_MSC_VER) && _MSC_VER >= 1400 # define GNUPLOT_MSVC_WARNING_4996_PUSH \ __pragma(warning(push)) \ __pragma(warning(disable:4996)) # define GNUPLOT_MSVC_WARNING_4996_POP \ __pragma(warning(pop)) #else # define GNUPLOT_MSVC_WARNING_4996_PUSH # define GNUPLOT_MSVC_WARNING_4996_POP #endif #ifndef GNUPLOT_DEFAULT_COMMAND #ifdef _WIN32 // "pgnuplot" is considered deprecated according to the Internet. It may be faster. It // doesn't seem to handle binary data though. //# define GNUPLOT_DEFAULT_COMMAND "pgnuplot -persist" // On Windows, gnuplot echos commands to stderr. So we forward its stderr to the bit bucket. // Unfortunately, this means you will miss out on legitimate error messages. # define GNUPLOT_DEFAULT_COMMAND "gnuplot -persist 2> NUL" #else # define GNUPLOT_DEFAULT_COMMAND "gnuplot -persist" #endif #endif // }}}1 namespace gnuplotio { // {{{1 Basic traits helpers // // The mechanisms constructed in this section enable us to detect what sort of datatype has // been passed to a function. // This can be specialized as needed, in order to not use the STL interfaces for specific // classes. template <typename T> struct dont_treat_as_stl_container { typedef boost::mpl::bool_<false> type; }; BOOST_MPL_HAS_XXX_TRAIT_DEF(value_type) BOOST_MPL_HAS_XXX_TRAIT_DEF(const_iterator) template <typename T> struct is_like_stl_container { typedef boost::mpl::and_< typename has_value_type<T>::type, typename has_const_iterator<T>::type, boost::mpl::not_<dont_treat_as_stl_container<T> > > type; static const bool value = type::value; }; template <typename T> struct is_boost_tuple_nulltype { static const bool value = false; typedef boost::mpl::bool_<value> type; }; template <> struct is_boost_tuple_nulltype<boost::tuples::null_type> { static const bool value = true; typedef boost::mpl::bool_<value> type; }; BOOST_MPL_HAS_XXX_TRAIT_DEF(head_type) BOOST_MPL_HAS_XXX_TRAIT_DEF(tail_type) template <typename T> struct is_boost_tuple { typedef boost::mpl::and_< typename has_head_type<T>::type, typename has_tail_type<T>::type > type; static const bool value = type::value; }; // More fine-grained, but doesn't compile! //template <typename T> //struct is_boost_tuple { // typedef boost::mpl::and_< // typename boost::is_class<T>::type, // typename boost::mpl::and_< // typename has_head_type<T>::type, // typename boost::mpl::and_< // typename has_tail_type<T>::type, // typename boost::mpl::or_< // typename is_boost_tuple_nulltype<typename T::tail_type>::type, // typename is_boost_tuple<typename T::tail_type>::type // >::type // >::type // >::type // > type; //}; // //template <> //struct is_boost_tuple<boost::tuples::null_type> { // typedef boost::mpl::bool_<false> type; //}; // }}}1 // {{{1 Tmpfile helper class #ifdef GNUPLOT_USE_TMPFILE // RAII temporary file. File is removed when this object goes out of scope. class GnuplotTmpfile { public: GnuplotTmpfile() : file(boost::filesystem::unique_path( boost::filesystem::temp_directory_path() / "tmp-gnuplot-%%%%-%%%%-%%%%-%%%%")) { } private: // noncopyable GnuplotTmpfile(const GnuplotTmpfile &); const GnuplotTmpfile& operator=(const GnuplotTmpfile &); public: ~GnuplotTmpfile() { // it is never good to throw exceptions from a destructor try { remove(file); } catch(const std::exception &) { std::cerr << "Failed to remove temporary file " << file << std::endl; } } public: boost::filesystem::path file; }; #endif // GNUPLOT_USE_TMPFILE // }}}1 // {{{1 Feedback helper classes // // Used for reading stuff sent from gnuplot via gnuplot's "print" function. // // For example, this is used for capturing mouse clicks in the gnuplot window. There are two // implementations, only the first of which is complete. The first implementation allocates a // PTY (pseudo terminal) which is written to by gnuplot and read by us. This only works in // Linux. The second implementation creates a temporary file which is written to by gnuplot // and read by us. However, this doesn't currently work since fscanf doesn't block. It would // be possible to get this working using a more complicated mechanism (select or threads) but I // haven't had the need for it. class GnuplotFeedback { public: GnuplotFeedback() { } virtual ~GnuplotFeedback() { } virtual std::string filename() const = 0; virtual FILE *handle() const = 0; private: // noncopyable GnuplotFeedback(const GnuplotFeedback &); const GnuplotFeedback& operator=(const GnuplotFeedback &); }; #ifdef GNUPLOT_ENABLE_PTY #define GNUPLOT_ENABLE_FEEDBACK class GnuplotFeedbackPty : public GnuplotFeedback { public: explicit GnuplotFeedbackPty(bool debug_messages) : pty_fn(), pty_fh(NULL), master_fd(-1), slave_fd(-1) { // adapted from http://www.gnuplot.info/files/gpReadMouseTest.c if(0 > openpty(&master_fd, &slave_fd, NULL, NULL, NULL)) { perror("openpty"); throw std::runtime_error("openpty failed"); } char pty_fn_buf[1024]; if(ttyname_r(slave_fd, pty_fn_buf, 1024)) { perror("ttyname_r"); throw std::runtime_error("ttyname failed"); } pty_fn = std::string(pty_fn_buf); if(debug_messages) { std::cerr << "feedback_fn=" << pty_fn << std::endl; } // disable echo struct termios tios; if(tcgetattr(slave_fd, &tios) < 0) { perror("tcgetattr"); throw std::runtime_error("tcgetattr failed"); } tios.c_lflag &= ~(ECHO | ECHONL); if(tcsetattr(slave_fd, TCSAFLUSH, &tios) < 0) { perror("tcsetattr"); throw std::runtime_error("tcsetattr failed"); } pty_fh = fdopen(master_fd, "r"); if(!pty_fh) { throw std::runtime_error("fdopen failed"); } } private: // noncopyable GnuplotFeedbackPty(const GnuplotFeedbackPty &); const GnuplotFeedbackPty& operator=(const GnuplotFeedbackPty &); public: ~GnuplotFeedbackPty() { if(pty_fh) fclose(pty_fh); if(master_fd > 0) ::close(master_fd); if(slave_fd > 0) ::close(slave_fd); } std::string filename() const { return pty_fn; } FILE *handle() const { return pty_fh; } private: std::string pty_fn; FILE *pty_fh; int master_fd, slave_fd; }; //#elif defined GNUPLOT_USE_TMPFILE //// Currently this doesn't work since fscanf doesn't block (need something like "tail -f") //#define GNUPLOT_ENABLE_FEEDBACK //class GnuplotFeedbackTmpfile : public GnuplotFeedback { //public: // explicit GnuplotFeedbackTmpfile(bool debug_messages) : // tmp_file(), // fh(NULL) // { // if(debug_messages) { // std::cerr << "feedback_fn=" << filename() << std::endl; // } // GNUPLOT_MSVC_WARNING_4996_PUSH // fh = std::fopen(filename().c_str(), "a"); // GNUPLOT_MSVC_WARNING_4996_POP // } // // ~GnuplotFeedbackTmpfile() { // fclose(fh); // } // //private: // // noncopyable // GnuplotFeedbackTmpfile(const GnuplotFeedbackTmpfile &); // const GnuplotFeedbackTmpfile& operator=(const GnuplotFeedbackTmpfile &); // //public: // std::string filename() const { // return tmp_file.file.string(); // } // // FILE *handle() const { // return fh; // } // //private: // GnuplotTmpfile tmp_file; // FILE *fh; //}; #endif // GNUPLOT_ENABLE_PTY, GNUPLOT_USE_TMPFILE // }}}1 // {{{1 Traits and printers for entry datatypes // // This section contains the mechanisms for sending scalar and tuple data to gnuplot. Pairs // and tuples are sent by appealing to the senders defined for their component scalar types. // Senders for arrays are defined in a later section. // // There are three classes which need to be specialized for each supported datatype: // 1. TextSender to send data as text. The default is to just send using the ostream's `<<` // operator. // 2. BinarySender to send data as binary, in a format which gnuplot can understand. There is // no default implementation (unimplemented types raise a compile time error), however // inheriting from FlatBinarySender will send the data literally as it is stored in memory. // This suffices for most of the standard built-in types (e.g. uint32_t or double). // 3. BinfmtSender sends a description of the data format to gnuplot (e.g. `%uint32`). Type // `show datafile binary datasizes` in gnuplot to see a list of supported formats. // {{{2 Basic entry datatypes // Default TextSender, sends data using `<<` operator. template <typename T, typename Enable=void> struct TextSender { static void send(std::ostream &stream, const T &v) { stream << v; } }; // Default BinarySender, raises a compile time error. template <typename T, typename Enable=void> struct BinarySender { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "BinarySender class not specialized for this type"); // This is here to avoid further compilation errors, beyond what the assert prints. static void send(std::ostream &stream, const T &v); }; // This is a BinarySender implementation that just sends directly from memory. Data types // which can be sent this way can have their BinarySender specialization inherit from this. template <typename T> struct FlatBinarySender { static void send(std::ostream &stream, const T &v) { stream.write(reinterpret_cast<const char *>(&v), sizeof(T)); } }; // Default BinfmtSender, raises a compile time error. template <typename T, typename Enable=void> struct BinfmtSender { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "BinfmtSender class not specialized for this type"); // This is here to avoid further compilation errors, beyond what the assert prints. static void send(std::ostream &); }; // BinfmtSender implementations for basic data types supported by gnuplot. // Types from boost/cstdint.hpp are used because VS2008 doesn't have stdint.h. template<> struct BinfmtSender< float> { static void send(std::ostream &stream) { stream << "%float"; } }; template<> struct BinfmtSender<double> { static void send(std::ostream &stream) { stream << "%double"; } }; template<> struct BinfmtSender<boost:: int8_t> { static void send(std::ostream &stream) { stream << "%int8"; } }; template<> struct BinfmtSender<boost:: uint8_t> { static void send(std::ostream &stream) { stream << "%uint8"; } }; template<> struct BinfmtSender<boost:: int16_t> { static void send(std::ostream &stream) { stream << "%int16"; } }; template<> struct BinfmtSender<boost::uint16_t> { static void send(std::ostream &stream) { stream << "%uint16"; } }; template<> struct BinfmtSender<boost:: int32_t> { static void send(std::ostream &stream) { stream << "%int32"; } }; template<> struct BinfmtSender<boost::uint32_t> { static void send(std::ostream &stream) { stream << "%uint32"; } }; template<> struct BinfmtSender<boost:: int64_t> { static void send(std::ostream &stream) { stream << "%int64"; } }; template<> struct BinfmtSender<boost::uint64_t> { static void send(std::ostream &stream) { stream << "%uint64"; } }; // BinarySender implementations for basic data types supported by gnuplot. These types can // just be sent as stored in memory, so all these senders inherit from FlatBinarySender. template<> struct BinarySender< float> : public FlatBinarySender< float> { }; template<> struct BinarySender<double> : public FlatBinarySender<double> { }; template<> struct BinarySender<boost:: int8_t> : public FlatBinarySender<boost:: int8_t> { }; template<> struct BinarySender<boost:: uint8_t> : public FlatBinarySender<boost:: uint8_t> { }; template<> struct BinarySender<boost:: int16_t> : public FlatBinarySender<boost:: int16_t> { }; template<> struct BinarySender<boost::uint16_t> : public FlatBinarySender<boost::uint16_t> { }; template<> struct BinarySender<boost:: int32_t> : public FlatBinarySender<boost:: int32_t> { }; template<> struct BinarySender<boost::uint32_t> : public FlatBinarySender<boost::uint32_t> { }; template<> struct BinarySender<boost:: int64_t> : public FlatBinarySender<boost:: int64_t> { }; template<> struct BinarySender<boost::uint64_t> : public FlatBinarySender<boost::uint64_t> { }; // Make char types print as integers, not as characters. template <typename T> struct CastIntTextSender { static void send(std::ostream &stream, const T &v) { stream << int(v); } }; template<> struct TextSender< char> : public CastIntTextSender< char> { }; template<> struct TextSender< signed char> : public CastIntTextSender< signed char> { }; template<> struct TextSender< unsigned char> : public CastIntTextSender< unsigned char> { }; // Make sure that the same not-a-number string is printed on all platforms. template <typename T> struct FloatTextSender { static void send(std::ostream &stream, const T &v) { if(GNUPLOT_ISNAN(v)) { stream << "nan"; } else { stream << v; } } }; template<> struct TextSender< float> : FloatTextSender< float> { }; template<> struct TextSender< double> : FloatTextSender< double> { }; template<> struct TextSender<long double> : FloatTextSender<long double> { }; // }}}2 // {{{2 std::pair support template <typename T, typename U> struct TextSender<std::pair<T, U> > { static void send(std::ostream &stream, const std::pair<T, U> &v) { TextSender<T>::send(stream, v.first); stream << " "; TextSender<U>::send(stream, v.second); } }; template <typename T, typename U> struct BinfmtSender<std::pair<T, U> > { static void send(std::ostream &stream) { BinfmtSender<T>::send(stream); BinfmtSender<U>::send(stream); } }; template <typename T, typename U> struct BinarySender<std::pair<T, U> > { static void send(std::ostream &stream, const std::pair<T, U> &v) { BinarySender<T>::send(stream, v.first); BinarySender<U>::send(stream, v.second); } }; // }}}2 // {{{2 std::complex support template <typename T> struct TextSender<std::complex<T> > { static void send(std::ostream &stream, const std::complex<T> &v) { TextSender<T>::send(stream, v.real()); stream << " "; TextSender<T>::send(stream, v.imag()); } }; template <typename T> struct BinfmtSender<std::complex<T> > { static void send(std::ostream &stream) { BinfmtSender<T>::send(stream); BinfmtSender<T>::send(stream); } }; template <typename T> struct BinarySender<std::complex<T> > { static void send(std::ostream &stream, const std::complex<T> &v) { BinarySender<T>::send(stream, v.real()); BinarySender<T>::send(stream, v.imag()); } }; // }}}2 // {{{2 boost::tuple support template <typename T> struct TextSender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> > > >::type > { static void send(std::ostream &stream, const T &v) { TextSender<typename T::head_type>::send(stream, v.get_head()); stream << " "; TextSender<typename T::tail_type>::send(stream, v.get_tail()); } }; template <typename T> struct TextSender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, is_boost_tuple_nulltype<typename T::tail_type> > >::type > { static void send(std::ostream &stream, const T &v) { TextSender<typename T::head_type>::send(stream, v.get_head()); } }; template <typename T> struct BinfmtSender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> > > >::type > { static void send(std::ostream &stream) { BinfmtSender<typename T::head_type>::send(stream); stream << " "; BinfmtSender<typename T::tail_type>::send(stream); } }; template <typename T> struct BinfmtSender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, is_boost_tuple_nulltype<typename T::tail_type> > >::type > { static void send(std::ostream &stream) { BinfmtSender<typename T::head_type>::send(stream); } }; template <typename T> struct BinarySender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> > > >::type > { static void send(std::ostream &stream, const T &v) { BinarySender<typename T::head_type>::send(stream, v.get_head()); BinarySender<typename T::tail_type>::send(stream, v.get_tail()); } }; template <typename T> struct BinarySender<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, is_boost_tuple_nulltype<typename T::tail_type> > >::type > { static void send(std::ostream &stream, const T &v) { BinarySender<typename T::head_type>::send(stream, v.get_head()); } }; // }}}2 // {{{2 std::tuple support #if GNUPLOT_ENABLE_CXX11 // http://stackoverflow.com/questions/6245735/pretty-print-stdtuple template<std::size_t> struct int_{}; // compile-time counter template <typename Tuple, std::size_t I> void std_tuple_formatcode_helper(std::ostream &stream, const Tuple *, int_<I>) { std_tuple_formatcode_helper(stream, (const Tuple *)(0), int_<I-1>()); stream << " "; BinfmtSender<typename std::tuple_element<I, Tuple>::type>::send(stream); } template <typename Tuple> void std_tuple_formatcode_helper(std::ostream &stream, const Tuple *, int_<0>) { BinfmtSender<typename std::tuple_element<0, Tuple>::type>::send(stream); } template <typename... Args> struct BinfmtSender<std::tuple<Args...> > { typedef typename std::tuple<Args...> Tuple; static void send(std::ostream &stream) { std_tuple_formatcode_helper(stream, (const Tuple *)(0), int_<sizeof...(Args)-1>()); } }; template <typename Tuple, std::size_t I> void std_tuple_textsend_helper(std::ostream &stream, const Tuple &v, int_<I>) { std_tuple_textsend_helper(stream, v, int_<I-1>()); stream << " "; TextSender<typename std::tuple_element<I, Tuple>::type>::send(stream, std::get<I>(v)); } template <typename Tuple> void std_tuple_textsend_helper(std::ostream &stream, const Tuple &v, int_<0>) { TextSender<typename std::tuple_element<0, Tuple>::type>::send(stream, std::get<0>(v)); } template <typename... Args> struct TextSender<std::tuple<Args...> > { typedef typename std::tuple<Args...> Tuple; static void send(std::ostream &stream, const Tuple &v) { std_tuple_textsend_helper(stream, v, int_<sizeof...(Args)-1>()); } }; template <typename Tuple, std::size_t I> void std_tuple_binsend_helper(std::ostream &stream, const Tuple &v, int_<I>) { std_tuple_binsend_helper(stream, v, int_<I-1>()); BinarySender<typename std::tuple_element<I, Tuple>::type>::send(stream, std::get<I>(v)); } template <typename Tuple> void std_tuple_binsend_helper(std::ostream &stream, const Tuple &v, int_<0>) { BinarySender<typename std::tuple_element<0, Tuple>::type>::send(stream, std::get<0>(v)); } template <typename... Args> struct BinarySender<std::tuple<Args...> > { typedef typename std::tuple<Args...> Tuple; static void send(std::ostream &stream, const Tuple &v) { std_tuple_binsend_helper(stream, v, int_<sizeof...(Args)-1>()); } }; #endif // GNUPLOT_ENABLE_CXX11 // }}}2 // }}}1 // {{{1 ArrayTraits and Range classes // // This section handles sending of array data to gnuplot. It is rather complicated because of // the diversity of storage schemes supported. For example, it treats a // `std::pair<std::vector<T>, std::vector<U>>` in the same way as a // `std::vector<std::pair<T, U>>`, iterating through the two arrays in lockstep, and sending // pairs <T,U> to gnuplot as columns. In fact, any nested combination of pairs, tuples, STL // containers, Blitz arrays, and Armadillo arrays is supported (with the caveat that, for // instance, Blitz arrays should never be put into an STL container or you will suffer // unpredictable results due the way Blitz handles assignment). Nested containers are // considered to be multidimensional arrays. Although gnuplot only supports 1D and 2D arrays, // our module is in principle not limited. // // The ArrayTraits class is specialized for every supported array or container type (the // default, unspecialized, version of ArrayTraits exists only to tell you that something is // *not* a container, via the is_container flag). ArrayTraits tells you the depth of a nested // (or multidimensional) container, as well as the value type, and provides a specialized // sort of iterator (a.k.a. "range"). Ranges are sort of like STL iterators, except that they // have built-in knowledge of the end condition so you don't have to carry around both a // begin() and an end() iterator like in STL. // // As an example of how this works, consider a std::pair of std::vectors. Ultimately this gets // sent to gnuplot as two columns, so the two vectors need to be iterated in lockstep. // The `value_type` of `std::pair<std::vector<T>, std::vector<U>>` is then `std::pair<T, U>` // and this is what deferencing the range (iterator) gives. Internally, this range is built // out of a pair of ranges (PairOfRange class), the `inc()` (advance to next element) // method calls `inc()` on each of the children, and `deref()` calls `deref()` on each child // and combines the results to return a `std::pair`. Tuples are handled as nested pairs. // // In addition to PairOfRange, there is also a VecOfRange class that can be used to treat the // outermost part of a nested container as if it were a tuple. Since tuples are printed as // columns, this is like treating a multidimensional array as if it were column-major. A // VecOfRange is obtained by calling `get_columns_range`. This is used by, for instance, // `send1d_colmajor`. The implementation is similar to that of PairOfRange. // // The range, accessed via `ArrayTraits<T>::get_range`, will be of a different class depending // on T, and this is defined by the ArrayTraits specialization for T. It will always have // methods `inc()` to advance to the next element and `is_end()` for checking whether one has // advanced past the final element. For nested containers, `deref_subiter()` returns a range // iterator for the next nesting level. When at the innermost level of nesting, `deref()` // returns the value of the entry the iterator points to (a scalar, pair, or tuple). // Only one of `deref()` or `deref_subiter()` will be available, depending on whether there are // deeper levels of nesting. The typedefs `value_type` and `subiter_type` tell the return // types of these two methods. // // Support for standard C++ and boost containers and tuples of containers is provided in this // section. Support for third party packages like Blitz and Armadillo is in a later section. // {{{2 ArrayTraits generic class and defaults // Error messages involving this stem from treating something that was not a container as if it // was. This is only here to allow compiliation without errors in normal cases. struct Error_WasNotContainer { // This is just here to make VC++ happy. // https://connect.microsoft.com/VisualStudio/feedback/details/777612/class-template-specialization-that-compiles-in-g-but-not-visual-c typedef void subiter_type; }; // Error messages involving this stem from calling deref instead of deref_subiter for a nested // container. struct Error_InappropriateDeref { }; // The unspecialized version of this class gives traits for things that are *not* arrays. template <typename T, typename Enable=void> class ArrayTraits { public: // The value type of elements after all levels of nested containers have been dereferenced. typedef Error_WasNotContainer value_type; // The type of the range (a.k.a. iterator) that `get_range()` returns. typedef Error_WasNotContainer range_type; // Tells whether T is in fact a container type. static const bool is_container = false; // This flag supports the legacy behavior of automatically guessing whether the data should // be treated as column major. This guessing happens when `send()` is called rather than // `send1d()` or `send2d()`. This is deprecated, but is still supported for reverse // compatibility. static const bool allow_auto_unwrap = false; // The number of levels of nesting, or the dimension of multidimensional arrays. static const size_t depth = 0; // Returns the range (iterator) for an array. static range_type get_range(const T &) { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T)==0), "argument was not a container"); throw std::logic_error("static assert should have been triggered by this point"); } }; // Most specializations of ArrayTraits should inherit from this (with V set to the value type). // It sets some default values. template <typename V> class ArrayTraitsDefaults { public: typedef V value_type; static const bool is_container = true; static const bool allow_auto_unwrap = true; static const size_t depth = ArrayTraits<V>::depth + 1; }; // This handles reference types, such as are given with boost::tie. // It also allows for instance "ArrayTraits<T[N]>" to match "ArrayTraits<T (&) [N]>". // I think this is okay to do... The alternative is to use remove_reference all over the place. template <typename T> class ArrayTraits<T&> : public ArrayTraits<T> { }; // FIXME - is this okay? // It supports gp.send1d(std::forward_as_tuple(x, std::move(y))); #if GNUPLOT_ENABLE_CXX11 template <typename T> class ArrayTraits<T&&> : public ArrayTraits<T> { }; #endif // }}}2 // {{{2 STL container support template <typename TI, typename TV> class IteratorRange { public: IteratorRange() { } IteratorRange(const TI &_it, const TI &_end) : it(_it), end(_end) { } static const bool is_container = ArrayTraits<TV>::is_container; typedef typename boost::mpl::if_c<is_container, Error_InappropriateDeref, TV>::type value_type; typedef typename ArrayTraits<TV>::range_type subiter_type; bool is_end() const { return it == end; } void inc() { ++it; } value_type deref() const { GNUPLOT_STATIC_ASSERT_MSG(sizeof(TV) && !is_container, "deref called on nested container"); if(is_end()) { throw std::runtime_error("attepted to dereference past end of iterator"); } return *it; } subiter_type deref_subiter() const { GNUPLOT_STATIC_ASSERT_MSG(sizeof(TV) && is_container, "deref_subiter called on non-nested container"); if(is_end()) { throw std::runtime_error("attepted to dereference past end of iterator"); } return ArrayTraits<TV>::get_range(*it); } private: TI it, end; }; template <typename T> class ArrayTraits<T, typename boost::enable_if<is_like_stl_container<T> >::type > : public ArrayTraitsDefaults<typename T::value_type> { public: typedef IteratorRange<typename T::const_iterator, typename T::value_type> range_type; static range_type get_range(const T &arg) { return range_type(arg.begin(), arg.end()); } }; // }}}2 // {{{2 C style array support template <typename T, size_t N> class ArrayTraits<T[N]> : public ArrayTraitsDefaults<T> { public: typedef IteratorRange<const T*, T> range_type; static range_type get_range(const T (&arg)[N]) { return range_type(arg, arg+N); } }; // }}}2 // {{{2 std::pair support template <typename RT, typename RU> class PairOfRange { template <typename T, typename U, typename PrintMode> friend void deref_and_print(std::ostream &, const PairOfRange<T, U> &, PrintMode); public: PairOfRange() { } PairOfRange(const RT &_l, const RU &_r) : l(_l), r(_r) { } static const bool is_container = RT::is_container && RU::is_container; typedef std::pair<typename RT::value_type, typename RU::value_type> value_type; typedef PairOfRange<typename RT::subiter_type, typename RU::subiter_type> subiter_type; bool is_end() const { bool el = l.is_end(); bool er = r.is_end(); if(el != er) { throw std::length_error("columns were different lengths"); } return el; } void inc() { l.inc(); r.inc(); } value_type deref() const { return std::make_pair(l.deref(), r.deref()); } subiter_type deref_subiter() const { return subiter_type(l.deref_subiter(), r.deref_subiter()); } private: RT l; RU r; }; template <typename T, typename U> class ArrayTraits<std::pair<T, U> > { public: typedef PairOfRange<typename ArrayTraits<T>::range_type, typename ArrayTraits<U>::range_type> range_type; typedef std::pair<typename ArrayTraits<T>::value_type, typename ArrayTraits<U>::value_type> value_type; static const bool is_container = ArrayTraits<T>::is_container && ArrayTraits<U>::is_container; // Don't allow colwrap since it's already wrapped. static const bool allow_auto_unwrap = false; // It is allowed for l_depth != r_depth, for example one column could be 'double' and the // other column could be 'vector<double>'. static const size_t l_depth = ArrayTraits<T>::depth; static const size_t r_depth = ArrayTraits<U>::depth; static const size_t depth = (l_depth < r_depth) ? l_depth : r_depth; static range_type get_range(const std::pair<T, U> &arg) { return range_type( ArrayTraits<T>::get_range(arg.first), ArrayTraits<U>::get_range(arg.second) ); } }; // }}}2 // {{{2 boost::tuple support template <typename T> class ArrayTraits<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, boost::mpl::not_<is_boost_tuple_nulltype<typename T::tail_type> > > >::type > : public ArrayTraits< typename std::pair< typename T::head_type, typename T::tail_type > > { public: typedef typename T::head_type HT; typedef typename T::tail_type TT; typedef ArrayTraits<typename std::pair<HT, TT> > parent; static typename parent::range_type get_range(const T &arg) { return typename parent::range_type( ArrayTraits<HT>::get_range(arg.get_head()), ArrayTraits<TT>::get_range(arg.get_tail()) ); } }; template <typename T> class ArrayTraits<T, typename boost::enable_if< boost::mpl::and_< is_boost_tuple<T>, is_boost_tuple_nulltype<typename T::tail_type> > >::type > : public ArrayTraits< typename T::head_type > { typedef typename T::head_type HT; typedef ArrayTraits<HT> parent; public: static typename parent::range_type get_range(const T &arg) { return parent::get_range(arg.get_head()); } }; // }}}2 // {{{2 std::tuple support #if GNUPLOT_ENABLE_CXX11 template <typename Tuple, size_t idx> struct StdTupUnwinder { typedef std::pair< typename StdTupUnwinder<Tuple, idx-1>::type, typename std::tuple_element<idx, Tuple>::type > type; static typename ArrayTraits<type>::range_type get_range(const Tuple &arg) { return typename ArrayTraits<type>::range_type( StdTupUnwinder<Tuple, idx-1>::get_range(arg), ArrayTraits<typename std::tuple_element<idx, Tuple>::type>::get_range(std::get<idx>(arg)) ); } }; template <typename Tuple> struct StdTupUnwinder<Tuple, 0> { typedef typename std::tuple_element<0, Tuple>::type type; static typename ArrayTraits<type>::range_type get_range(const Tuple &arg) { return ArrayTraits<type>::get_range(std::get<0>(arg)); } }; template <typename... Args> class ArrayTraits<std::tuple<Args...> > : public ArrayTraits<typename StdTupUnwinder<std::tuple<Args...>, sizeof...(Args)-1>::type> { typedef std::tuple<Args...> Tuple; typedef ArrayTraits<typename StdTupUnwinder<Tuple, sizeof...(Args)-1>::type> parent; public: static typename parent::range_type get_range(const Tuple &arg) { return StdTupUnwinder<std::tuple<Args...>, sizeof...(Args)-1>::get_range(arg); } }; #endif // GNUPLOT_ENABLE_CXX11 // }}}2 // {{{2 Support column unwrap of container (VecOfRange) // // VecOfRange (created via `get_columns_range()`) treats the outermost level of a nested // container as if it were a tuple. Since tuples are sent to gnuplot as columns, this has the // effect of addressing a multidimensional array in column major order. template <typename RT> class VecOfRange { template <typename T, typename PrintMode> friend void deref_and_print(std::ostream &, const VecOfRange<T> &, PrintMode); public: VecOfRange() { } explicit VecOfRange(const std::vector<RT> &_rvec) : rvec(_rvec) { } static const bool is_container = RT::is_container; // Don't allow colwrap since it's already wrapped. static const bool allow_auto_unwrap = false; typedef std::vector<typename RT::value_type> value_type; typedef VecOfRange<typename RT::subiter_type> subiter_type; bool is_end() const { if(rvec.empty()) return true; bool ret = rvec[0].is_end(); for(size_t i=1; i<rvec.size(); i++) { if(ret != rvec[i].is_end()) { throw std::length_error("columns were different lengths"); } } return ret; } void inc() { for(size_t i=0; i<rvec.size(); i++) { rvec[i].inc(); } } value_type deref() const { value_type ret(rvec.size()); for(size_t i=0; i<rvec.size(); i++) { ret[i] = rvec[i].deref(); } return ret; } subiter_type deref_subiter() const { std::vector<typename RT::subiter_type> subvec(rvec.size()); for(size_t i=0; i<rvec.size(); i++) { subvec[i] = rvec[i].deref_subiter(); } return subiter_type(subvec); } private: std::vector<RT> rvec; }; template <typename T> VecOfRange<typename ArrayTraits<T>::range_type::subiter_type> get_columns_range(const T &arg) { typedef typename ArrayTraits<T>::range_type::subiter_type U; std::vector<U> rvec; typename ArrayTraits<T>::range_type outer = ArrayTraits<T>::get_range(arg); while(!outer.is_end()) { rvec.push_back(outer.deref_subiter()); outer.inc(); } VecOfRange<U> ret(rvec); return ret; } // }}}2 // }}}1 // {{{1 Array printing functions // // This section coordinates the sending of data to gnuplot. The ArrayTraits mechanism tells us // about nested containers and provides iterators over them. Here we make use of this, // deciding what dimensions should be treated as rows, columns, or blocks, telling gnuplot the // size of the array if needed, and so on. // If this is set, then text-mode data will be sent in a format that is not compatible with // gnuplot, but which helps the programmer tell what the library is thinking. Basically it // puts brackets around groups of items and puts a message delineating blocks of data. static bool debug_array_print = 0; // This is thrown when an empty container is being plotted. This exception should always // be caught and should not propagate to the user. class plotting_empty_container : public std::length_error { public: plotting_empty_container() : std::length_error("plotting empty container") { } }; // {{{2 Tags (like enums for metaprogramming) // These tags define what our goal is, what sort of thing should ultimately be sent to the // ostream. These tags are passed to the PrintMode template argument of the functions in this // section. // // ModeText - Sends the data in an array in text format // ModeBinary - Sends the data in an array in binary format // ModeBinfmt - Sends the gnuplot format code for binary data (e.g. "%double%double") // ModeSize - Sends the size of an array. Needed when sending binary data. struct ModeText { static const bool is_text = 1; static const bool is_binfmt = 0; static const bool is_size = 0; }; struct ModeBinary { static const bool is_text = 0; static const bool is_binfmt = 0; static const bool is_size = 0; }; struct ModeBinfmt { static const bool is_text = 0; static const bool is_binfmt = 1; static const bool is_size = 0; }; struct ModeSize { static const bool is_text = 0; static const bool is_binfmt = 0; static const bool is_size = 1; }; // Whether to treat the outermost level of a nested container as columns (column major mode). struct ColUnwrapNo { }; struct ColUnwrapYes { }; // The user must give a hint to describe how nested containers are to be interpreted. This is // done by calling e.g. `send1d_colmajor()` or `send2d()`. This hint is then described by the // following tags. This is passed to the OrganizationMode template argument. struct Mode1D { static std::string class_name() { return "Mode1D" ; } }; struct Mode2D { static std::string class_name() { return "Mode2D" ; } }; struct Mode1DUnwrap { static std::string class_name() { return "Mode1DUnwrap"; } }; struct Mode2DUnwrap { static std::string class_name() { return "Mode2DUnwrap"; } }; // Support for the legacy behavior that guesses which of the above four modes should be used. struct ModeAuto { static std::string class_name() { return "ModeAuto" ; } }; // }}}2 // {{{2 ModeAutoDecoder // // ModeAuto guesses which of Mode1D, Mode2D, Mode1DUnwrap, or Mode2DUnwrap should be used. // This is provided for reverse compatibility; it is better to specify explicitly which mode to // use. Since this is only for reverse compatibility, and shouldn't be used, I'm not going to // spell out what the rules are. See below for details. template <typename T, typename Enable=void> struct ModeAutoDecoder { }; template <typename T> struct ModeAutoDecoder<T, typename boost::enable_if_c< (ArrayTraits<T>::depth == 1) >::type> { typedef Mode1D mode; }; template <typename T> struct ModeAutoDecoder<T, typename boost::enable_if_c< (ArrayTraits<T>::depth == 2) && !ArrayTraits<T>::allow_auto_unwrap >::type> { typedef Mode2D mode; }; template <typename T> struct ModeAutoDecoder<T, typename boost::enable_if_c< (ArrayTraits<T>::depth == 2) && ArrayTraits<T>::allow_auto_unwrap >::type> { typedef Mode1DUnwrap mode; }; template <typename T> struct ModeAutoDecoder<T, typename boost::enable_if_c< (ArrayTraits<T>::depth > 2) && ArrayTraits<T>::allow_auto_unwrap >::type> { typedef Mode2DUnwrap mode; }; template <typename T> struct ModeAutoDecoder<T, typename boost::enable_if_c< (ArrayTraits<T>::depth > 2) && !ArrayTraits<T>::allow_auto_unwrap >::type> { typedef Mode2D mode; }; // }}}2 // The data is processed using several levels of functions that call each other in sequence, // each defined in a subsection of code below. Because C++ wants you to declare a function // before using it, we begin with the innermost function. So in order to see the sequence in // which these are called, you should read the following subsections in reverse order. Nested // arrays are formated into blocks (for 2D data) and lines (for 1D or 2D data), then further // nesting levels are formatted into columns. Also tag dispatching is used in order to define // various sorts of behavior. Each of these tasks is handled by one of the following // subsections. // {{{2 send_scalar() // // Send a scalar in one of three possible ways: via TextSender, BinarySender, or BinfmtSender, // depending on which PrintMode tag is passed to the function. template <typename T> void send_scalar(std::ostream &stream, const T &arg, ModeText) { TextSender<T>::send(stream, arg); } template <typename T> void send_scalar(std::ostream &stream, const T &arg, ModeBinary) { BinarySender<T>::send(stream, arg); } template <typename T> void send_scalar(std::ostream &stream, const T &, ModeBinfmt) { BinfmtSender<T>::send(stream); } // }}}2 // {{{2 deref_and_print() // // Dereferences and prints the given range (iterator). At this point we are done with treating // containers as blocks (for 2D data) and lines (for 1D or 2D data). Any further levels of // nested containers will at this point be treated as columns. // If arg is not a container, then print it via send_scalar(). template <typename T, typename PrintMode> typename boost::disable_if_c<T::is_container>::type deref_and_print(std::ostream &stream, const T &arg, PrintMode) { const typename T::value_type &v = arg.deref(); send_scalar(stream, v, PrintMode()); } // If arg is a container (but not a PairOfRange or VecOfRange, which are handled below) then // treat the contents as columns, iterating over the contents recursively. If outputting in // text mode, put a space between columns. template <typename T, typename PrintMode> typename boost::enable_if_c<T::is_container>::type deref_and_print(std::ostream &stream, const T &arg, PrintMode) { if(arg.is_end()) throw plotting_empty_container(); typename T::subiter_type subrange = arg.deref_subiter(); if(PrintMode::is_binfmt && subrange.is_end()) throw plotting_empty_container(); if(debug_array_print && PrintMode::is_text) stream << "{"; bool first = true; while(!subrange.is_end()) { if(!first && PrintMode::is_text) stream << " "; first = false; deref_and_print(stream, subrange, PrintMode()); subrange.inc(); } if(debug_array_print && PrintMode::is_text) stream << "}"; } // PairOfRange is treated as columns. In text mode, put a space between columns. template <typename T, typename U, typename PrintMode> void deref_and_print(std::ostream &stream, const PairOfRange<T, U> &arg, PrintMode) { deref_and_print(stream, arg.l, PrintMode()); if(PrintMode::is_text) stream << " "; deref_and_print(stream, arg.r, PrintMode()); } // VecOfRange is treated as columns. In text mode, put a space between columns. template <typename T, typename PrintMode> void deref_and_print(std::ostream &stream, const VecOfRange<T> &arg, PrintMode) { if(PrintMode::is_binfmt && arg.rvec.empty()) throw plotting_empty_container(); for(size_t i=0; i<arg.rvec.size(); i++) { if(i && PrintMode::is_text) stream << " "; deref_and_print(stream, arg.rvec[i], PrintMode()); } } // }}}2 // {{{2 print_block() // // Here we format nested containers into blocks (for 2D data) and lines. Actually, block and // line formatting is only truely needed for text mode output, but for uniformity this function // is also invoked in binary mode (the PrintMode tag determines the output mode). If the goal // is to just print the array size or the binary format string, then the loops exit after the // first iteration. // // The Depth argument tells how deep to recurse. It will be either `2` for 2D data, formatted // into blocks and lines, with empty lines between blocks, or `1` for 1D data formatted into // lines but not blocks. Gnuplot only supports 1D and 2D data, but if it were to support 3D in // the future (e.g. volume rendering), all that would be needed would be some trivial changes // in this section. After Depth number of nested containers have been recursed into, control // is passed to deref_and_print(), which treats any further nested containers as columns. // Depth==1 and we are not asked to print the size of the array. Send each element of the // range to deref_and_print() for further processing into columns. template <size_t Depth, typename T, typename PrintMode> typename boost::enable_if_c<(Depth==1) && !PrintMode::is_size>::type print_block(std::ostream &stream, T &arg, PrintMode) { if(PrintMode::is_binfmt && arg.is_end()) throw plotting_empty_container(); for(; !arg.is_end(); arg.inc()) { //print_entry(arg.deref()); deref_and_print(stream, arg, PrintMode()); // If asked to print the binary format string, only the first element needs to be // looked at. if(PrintMode::is_binfmt) break; if(PrintMode::is_text) stream << std::endl; } } // Depth>1 and we are not asked to print the size of the array. Loop over the range and // recurse into print_block() with Depth -> Depth-1. template <size_t Depth, typename T, typename PrintMode> typename boost::enable_if_c<(Depth>1) && !PrintMode::is_size>::type print_block(std::ostream &stream, T &arg, PrintMode) { if(PrintMode::is_binfmt && arg.is_end()) throw plotting_empty_container(); bool first = true; for(; !arg.is_end(); arg.inc()) { if(first) { first = false; } else { if(PrintMode::is_text) stream << std::endl; } if(debug_array_print && PrintMode::is_text) stream << "<block>" << std::endl; if(arg.is_end()) throw plotting_empty_container(); typename T::subiter_type sub = arg.deref_subiter(); print_block<Depth-1>(stream, sub, PrintMode()); // If asked to print the binary format string, only the first element needs to be // looked at. if(PrintMode::is_binfmt) break; } } // Determine how many elements are in the given range. Used in the functions below. template <typename T> size_t get_range_size(const T &arg) { // FIXME - not the fastest way. Implement a size() method for range. size_t ret = 0; for(T i=arg; !i.is_end(); i.inc()) ++ret; return ret; } // Depth==1 and we are asked to print the size of the array. template <size_t Depth, typename T, typename PrintMode> typename boost::enable_if_c<(Depth==1) && PrintMode::is_size>::type print_block(std::ostream &stream, T &arg, PrintMode) { stream << get_range_size(arg); } // Depth>1 and we are asked to print the size of the array. template <size_t Depth, typename T, typename PrintMode> typename boost::enable_if_c<(Depth>1) && PrintMode::is_size>::type print_block(std::ostream &stream, T &arg, PrintMode) { if(arg.is_end()) throw plotting_empty_container(); // It seems that size for two dimensional arrays needs the fastest varying index first, // contrary to intuition. The gnuplot documentation is not too clear on this point. typename T::subiter_type sub = arg.deref_subiter(); print_block<Depth-1>(stream, sub, PrintMode()); stream << "," << get_range_size(arg); } // }}}2 // {{{2 handle_colunwrap_tag() // // If passed the ColUnwrapYes then treat the outermost nested container as columns by calling // get_columns_range(). Otherwise just call get_range(). The range iterator is then passed to // print_block() for further processing. template <size_t Depth, typename T, typename PrintMode> void handle_colunwrap_tag(std::ostream &stream, const T &arg, ColUnwrapNo, PrintMode) { GNUPLOT_STATIC_ASSERT_MSG(ArrayTraits<T>::depth >= Depth, "container not deep enough"); typename ArrayTraits<T>::range_type range = ArrayTraits<T>::get_range(arg); print_block<Depth>(stream, range, PrintMode()); } template <size_t Depth, typename T, typename PrintMode> void handle_colunwrap_tag(std::ostream &stream, const T &arg, ColUnwrapYes, PrintMode) { GNUPLOT_STATIC_ASSERT_MSG(ArrayTraits<T>::depth >= Depth+1, "container not deep enough"); VecOfRange<typename ArrayTraits<T>::range_type::subiter_type> cols = get_columns_range(arg); print_block<Depth>(stream, cols, PrintMode()); } // }}}2 // {{{2 handle_organization_tag() // // Parse the OrganizationMode tag then forward to handle_colunwrap_tag() for further // processing. If passed the Mode1D or Mode2D tags, then set Depth=1 or Depth=2. If passed // Mode{1,2}DUnwrap then use the ColUnwrapYes tag. If passed ModeAuto (which is for legacy // support) then use ModeAutoDecoder to guess which of Mode1D, Mode2D, etc. should be used. template <typename T, typename PrintMode> void handle_organization_tag(std::ostream &stream, const T &arg, Mode1D, PrintMode) { handle_colunwrap_tag<1>(stream, arg, ColUnwrapNo(), PrintMode()); } template <typename T, typename PrintMode> void handle_organization_tag(std::ostream &stream, const T &arg, Mode2D, PrintMode) { handle_colunwrap_tag<2>(stream, arg, ColUnwrapNo(), PrintMode()); } template <typename T, typename PrintMode> void handle_organization_tag(std::ostream &stream, const T &arg, Mode1DUnwrap, PrintMode) { handle_colunwrap_tag<1>(stream, arg, ColUnwrapYes(), PrintMode()); } template <typename T, typename PrintMode> void handle_organization_tag(std::ostream &stream, const T &arg, Mode2DUnwrap, PrintMode) { handle_colunwrap_tag<2>(stream, arg, ColUnwrapYes(), PrintMode()); } template <typename T, typename PrintMode> void handle_organization_tag(std::ostream &stream, const T &arg, ModeAuto, PrintMode) { handle_organization_tag(stream, arg, typename ModeAutoDecoder<T>::mode(), PrintMode()); } // }}}2 // The entry point for the processing defined in this section. It just forwards immediately to // handle_organization_tag(). This function is only here to give a sane name to the entry // point. // // The allowed values for the OrganizationMode and PrintMode tags are defined in the beginning // of this section. template <typename T, typename OrganizationMode, typename PrintMode> void top_level_array_sender(std::ostream &stream, const T &arg, OrganizationMode, PrintMode) { handle_organization_tag(stream, arg, OrganizationMode(), PrintMode()); } // }}}1 // {{{1 FileHandleWrapper // This holds the file handle that gnuplot commands will be sent to. The purpose of this // wrapper is twofold: // 1. It allows storing the FILE* before it gets passed to the boost::iostreams::stream // constructor (which is a base class of the main Gnuplot class). This is accomplished // via multiple inheritance as described at http://stackoverflow.com/a/3821756/1048959 // 2. It remembers whether the handle needs to be closed via fclose or pclose. struct FileHandleWrapper { FileHandleWrapper(std::FILE *_fh, bool _should_use_pclose) : wrapped_fh(_fh), should_use_pclose(_should_use_pclose) { } void fh_close() { if(should_use_pclose) { if(GNUPLOT_PCLOSE(wrapped_fh)) { std::cerr << "pclose returned error" << std::endl; } } else { if(fclose(wrapped_fh)) { std::cerr << "fclose returned error" << std::endl; } } } int fh_fileno() { return GNUPLOT_FILENO(wrapped_fh); } std::FILE *wrapped_fh; bool should_use_pclose; }; // }}}1 // {{{1 Main class class Gnuplot : // Some setup needs to be done before obtaining the file descriptor that gets passed to // boost::iostreams::stream. This is accomplished by using a multiple inheritance trick, // as described at http://stackoverflow.com/a/3821756/1048959 private FileHandleWrapper, public boost::iostreams::stream<boost::iostreams::file_descriptor_sink> { private: static std::string get_default_cmd() { GNUPLOT_MSVC_WARNING_4996_PUSH char *from_env = std::getenv("GNUPLOT_IOSTREAM_CMD"); GNUPLOT_MSVC_WARNING_4996_POP if(from_env && from_env[0]) { return from_env; } else { return GNUPLOT_DEFAULT_COMMAND; } } static FileHandleWrapper open_cmdline(const std::string &in) { std::string cmd = in.empty() ? get_default_cmd() : in; assert(!cmd.empty()); if(cmd[0] == '>') { std::string fn = cmd.substr(1); GNUPLOT_MSVC_WARNING_4996_PUSH FILE *fh = std::fopen(fn.c_str(), "w"); GNUPLOT_MSVC_WARNING_4996_POP if(!fh) throw(std::ios_base::failure("cannot open file "+fn)); return FileHandleWrapper(fh, false); } else { FILE *fh = GNUPLOT_POPEN(cmd.c_str(), "w"); if(!fh) throw(std::ios_base::failure("cannot open pipe "+cmd)); return FileHandleWrapper(fh, true); } } public: explicit Gnuplot(const std::string &_cmd="") : FileHandleWrapper(open_cmdline(_cmd)), boost::iostreams::stream<boost::iostreams::file_descriptor_sink>( fh_fileno(), #if BOOST_VERSION >= 104400 boost::iostreams::never_close_handle #else false #endif ), feedback(NULL), tmp_files(), debug_messages(false) { *this << std::scientific << std::setprecision(18); // refer <iomanip> } explicit Gnuplot(FILE *_fh) : FileHandleWrapper(_fh, 0), boost::iostreams::stream<boost::iostreams::file_descriptor_sink>( fh_fileno(), #if BOOST_VERSION >= 104400 boost::iostreams::never_close_handle #else false #endif ), feedback(NULL), tmp_files(), debug_messages(false) { *this << std::scientific << std::setprecision(18); // refer <iomanip> } private: // noncopyable Gnuplot(const Gnuplot &); const Gnuplot& operator=(const Gnuplot &); public: ~Gnuplot() { if(debug_messages) { std::cerr << "ending gnuplot session" << std::endl; } // FIXME - boost's close method calls close() on the file descriptor, but we need to // use sometimes use pclose instead. For now, just skip calling boost's close and use // flush just in case. do_flush(); // Wish boost had a pclose method... //close(); fh_close(); delete feedback; } void clearTmpfiles() { // destructors will cause deletion tmp_files.clear(); } private: void do_flush() { *this << std::flush; fflush(wrapped_fh); } std::string make_tmpfile() { #ifdef GNUPLOT_USE_TMPFILE boost::shared_ptr<GnuplotTmpfile> tmp_file(new GnuplotTmpfile()); // The file will be removed once the pointer is removed from the // tmp_files container. tmp_files.push_back(tmp_file); return tmp_file->file.string(); #else throw(std::logic_error("no filename given and temporary files not enabled")); #endif // GNUPLOT_USE_TMPFILE } public: // {{{2 Generic sender routines. // // These are declared public, but are undocumented. It is recommended to use the functions in // the next section, which serve as adapters that pass specific values for the OrganizationMode // tag. template <typename T, typename OrganizationMode> Gnuplot &send(const T &arg, OrganizationMode) { top_level_array_sender(*this, arg, OrganizationMode(), ModeText()); *this << "e" << std::endl; // gnuplot's "end of array" token do_flush(); // probably not really needed, but doesn't hurt return *this; } template <typename T, typename OrganizationMode> Gnuplot &sendBinary(const T &arg, OrganizationMode) { top_level_array_sender(*this, arg, OrganizationMode(), ModeBinary()); do_flush(); // probably not really needed, but doesn't hurt return *this; } template <typename T, typename OrganizationMode> std::string binfmt(const T &arg, const std::string &arr_or_rec, OrganizationMode) { assert((arr_or_rec == "array") || (arr_or_rec == "record")); std::string ret; try { std::ostringstream tmp; tmp << " format='"; top_level_array_sender(tmp, arg, OrganizationMode(), ModeBinfmt()); tmp << "' " << arr_or_rec << "=("; top_level_array_sender(tmp, arg, OrganizationMode(), ModeSize()); tmp << ")"; tmp << " "; ret = tmp.str(); } catch(const plotting_empty_container &) { ret = std::string(" format='' ") + arr_or_rec + "=(0) "; } return ret; } // NOTE: empty filename makes temporary file template <typename T, typename OrganizationMode> std::string file(const T &arg, std::string filename, OrganizationMode) { if(filename.empty()) filename = make_tmpfile(); std::fstream tmp_stream(filename.c_str(), std::fstream::out); top_level_array_sender(tmp_stream, arg, OrganizationMode(), ModeText()); tmp_stream.close(); std::ostringstream cmdline; // FIXME - hopefully filename doesn't contain quotes or such... cmdline << " '" << filename << "' "; return cmdline.str(); } // NOTE: empty filename makes temporary file template <typename T, typename OrganizationMode> std::string binaryFile(const T &arg, std::string filename, const std::string &arr_or_rec, OrganizationMode) { if(filename.empty()) filename = make_tmpfile(); std::fstream tmp_stream(filename.c_str(), std::fstream::out | std::fstream::binary); top_level_array_sender(tmp_stream, arg, OrganizationMode(), ModeBinary()); tmp_stream.close(); std::ostringstream cmdline; // FIXME - hopefully filename doesn't contain quotes or such... cmdline << " '" << filename << "' binary" << binfmt(arg, arr_or_rec, OrganizationMode()); return cmdline.str(); } // }}}2 // {{{2 Deprecated data sending interface that guesses an appropriate OrganizationMode. This is here // for reverse compatibility. Don't use it. A warning will be printed if // GNUPLOT_DEPRECATE_WARN is defined. template <typename T> Gnuplot GNUPLOT_DEPRECATE("use send1d or send2d") &send(const T &arg) { return send(arg, ModeAuto()); } template <typename T> std::string GNUPLOT_DEPRECATE("use binfmt1d or binfmt2d") binfmt(const T &arg, const std::string &arr_or_rec="array") { return binfmt(arg, arr_or_rec, ModeAuto()); } template <typename T> Gnuplot GNUPLOT_DEPRECATE("use sendBinary1d or sendBinary2d") &sendBinary(const T &arg) { return sendBinary(arg, ModeAuto()); } template <typename T> std::string GNUPLOT_DEPRECATE("use file1d or file2d") file(const T &arg, const std::string &filename="") { return file(arg, filename, ModeAuto()); } template <typename T> std::string GNUPLOT_DEPRECATE("use binArr1d or binArr2d") binaryFile(const T &arg, const std::string &filename="", const std::string &arr_or_rec="array") { return binaryFile(arg, filename, arr_or_rec, ModeAuto()); } // }}}2 // {{{2 Public (documented) data sending interface. // // It seems odd to define 16 different functions, but I think this ends up being the most // convenient in terms of usage by the end user. template <typename T> Gnuplot &send1d (const T &arg) { return send(arg, Mode1D ()); } template <typename T> Gnuplot &send2d (const T &arg) { return send(arg, Mode2D ()); } template <typename T> Gnuplot &send1d_colmajor(const T &arg) { return send(arg, Mode1DUnwrap()); } template <typename T> Gnuplot &send2d_colmajor(const T &arg) { return send(arg, Mode2DUnwrap()); } template <typename T> Gnuplot &sendBinary1d (const T &arg) { return sendBinary(arg, Mode1D ()); } template <typename T> Gnuplot &sendBinary2d (const T &arg) { return sendBinary(arg, Mode2D ()); } template <typename T> Gnuplot &sendBinary1d_colmajor(const T &arg) { return sendBinary(arg, Mode1DUnwrap()); } template <typename T> Gnuplot &sendBinary2d_colmajor(const T &arg) { return sendBinary(arg, Mode2DUnwrap()); } template <typename T> std::string file1d (const T &arg, const std::string &filename="") { return file(arg, filename, Mode1D ()); } template <typename T> std::string file2d (const T &arg, const std::string &filename="") { return file(arg, filename, Mode2D ()); } template <typename T> std::string file1d_colmajor(const T &arg, const std::string &filename="") { return file(arg, filename, Mode1DUnwrap()); } template <typename T> std::string file2d_colmajor(const T &arg, const std::string &filename="") { return file(arg, filename, Mode2DUnwrap()); } template <typename T> std::string binFmt1d (const T &arg, const std::string &arr_or_rec) { return binfmt(arg, arr_or_rec, Mode1D ()); } template <typename T> std::string binFmt2d (const T &arg, const std::string &arr_or_rec) { return binfmt(arg, arr_or_rec, Mode2D ()); } template <typename T> std::string binFmt1d_colmajor(const T &arg, const std::string &arr_or_rec) { return binfmt(arg, arr_or_rec, Mode1DUnwrap()); } template <typename T> std::string binFmt2d_colmajor(const T &arg, const std::string &arr_or_rec) { return binfmt(arg, arr_or_rec, Mode2DUnwrap()); } template <typename T> std::string binFile1d (const T &arg, const std::string &arr_or_rec, const std::string &filename="") { return binaryFile(arg, filename, arr_or_rec, Mode1D ()); } template <typename T> std::string binFile2d (const T &arg, const std::string &arr_or_rec, const std::string &filename="") { return binaryFile(arg, filename, arr_or_rec, Mode2D ()); } template <typename T> std::string binFile1d_colmajor(const T &arg, const std::string &arr_or_rec, const std::string &filename="") { return binaryFile(arg, filename, arr_or_rec, Mode1DUnwrap()); } template <typename T> std::string binFile2d_colmajor(const T &arg, const std::string &arr_or_rec, const std::string &filename="") { return binaryFile(arg, filename, arr_or_rec, Mode2DUnwrap()); } // }}}2 #ifdef GNUPLOT_ENABLE_FEEDBACK public: // Input variables are set to the mouse position and button. If the gnuplot // window is closed, button -1 is returned. The msg parameter is the prompt // that is printed to the console. void getMouse( double &mx, double &my, int &mb, std::string msg="Click Mouse!" ) { allocFeedback(); *this << "set mouse" << std::endl; *this << "pause mouse \"" << msg << "\\n\"" << std::endl; *this << "if (exists(\"MOUSE_X\")) print MOUSE_X, MOUSE_Y, MOUSE_BUTTON; else print 0, 0, -1;" << std::endl; if(debug_messages) { std::cerr << "begin scanf" << std::endl; } if(3 != fscanf(feedback->handle(), "%50lf %50lf %50d", &mx, &my, &mb)) { throw std::runtime_error("could not parse reply"); } if(debug_messages) { std::cerr << "end scanf" << std::endl; } } private: void allocFeedback() { if(!feedback) { #ifdef GNUPLOT_ENABLE_PTY feedback = new GnuplotFeedbackPty(debug_messages); //#elif defined GNUPLOT_USE_TMPFILE //// Currently this doesn't work since fscanf doesn't block (need something like "tail -f") // feedback = new GnuplotFeedbackTmpfile(debug_messages); #else // This shouldn't happen because we are in an `#ifdef GNUPLOT_ENABLE_FEEDBACK` // block which should only be activated if GNUPLOT_ENABLE_PTY is defined. GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "No feedback mechanism defined."); #endif *this << "set print \"" << feedback->filename() << "\"" << std::endl; } } #endif // GNUPLOT_ENABLE_FEEDBACK private: GnuplotFeedback *feedback; #ifdef GNUPLOT_USE_TMPFILE std::vector<boost::shared_ptr<GnuplotTmpfile> > tmp_files; #else // just a placeholder std::vector<int> tmp_files; #endif // GNUPLOT_USE_TMPFILE public: bool debug_messages; }; // }}}1 } // namespace gnuplotio // The first version of this library didn't use namespaces, and now this must be here forever // for reverse compatibility. using gnuplotio::Gnuplot; #endif // GNUPLOT_IOSTREAM_H // {{{1 Support for 3rd party array libraries // {{{2 Blitz support // This is outside of the main header guard so that it will be compiled when people do // something like this: // #include "gnuplot-iostream.h" // #include <blitz/array.h> // #include "gnuplot-iostream.h" // Note that it has its own header guard to avoid double inclusion. #ifdef BZ_BLITZ_H #ifndef GNUPLOT_BLITZ_SUPPORT_LOADED #define GNUPLOT_BLITZ_SUPPORT_LOADED namespace gnuplotio { template <typename T, int N> struct BinfmtSender<blitz::TinyVector<T, N> > { static void send(std::ostream &stream) { for(int i=0; i<N; i++) { BinfmtSender<T>::send(stream); } } }; template <typename T, int N> struct TextSender<blitz::TinyVector<T, N> > { static void send(std::ostream &stream, const blitz::TinyVector<T, N> &v) { for(int i=0; i<N; i++) { if(i) stream << " "; TextSender<T>::send(stream, v[i]); } } }; template <typename T, int N> struct BinarySender<blitz::TinyVector<T, N> > { static void send(std::ostream &stream, const blitz::TinyVector<T, N> &v) { for(int i=0; i<N; i++) { BinarySender<T>::send(stream, v[i]); } } }; class Error_WasBlitzPartialSlice { }; template <typename T, int ArrayDim, int SliceDim> class BlitzIterator { public: BlitzIterator() : p(NULL) { } BlitzIterator( const blitz::Array<T, ArrayDim> *_p, const blitz::TinyVector<int, ArrayDim> _idx ) : p(_p), idx(_idx) { } typedef Error_WasBlitzPartialSlice value_type; typedef BlitzIterator<T, ArrayDim, SliceDim-1> subiter_type; static const bool is_container = true; // FIXME - it would be nice to also handle one-based arrays bool is_end() const { return idx[ArrayDim-SliceDim] == p->shape()[ArrayDim-SliceDim]; } void inc() { ++idx[ArrayDim-SliceDim]; } value_type deref() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "cannot deref a blitz slice"); throw std::logic_error("static assert should have been triggered by this point"); } subiter_type deref_subiter() const { return BlitzIterator<T, ArrayDim, SliceDim-1>(p, idx); } private: const blitz::Array<T, ArrayDim> *p; blitz::TinyVector<int, ArrayDim> idx; }; template <typename T, int ArrayDim> class BlitzIterator<T, ArrayDim, 1> { public: BlitzIterator() : p(NULL) { } BlitzIterator( const blitz::Array<T, ArrayDim> *_p, const blitz::TinyVector<int, ArrayDim> _idx ) : p(_p), idx(_idx) { } typedef T value_type; typedef Error_WasNotContainer subiter_type; static const bool is_container = false; // FIXME - it would be nice to also handle one-based arrays bool is_end() const { return idx[ArrayDim-1] == p->shape()[ArrayDim-1]; } void inc() { ++idx[ArrayDim-1]; } value_type deref() const { return (*p)(idx); } subiter_type deref_subiter() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "argument was not a container"); throw std::logic_error("static assert should have been triggered by this point"); } private: const blitz::Array<T, ArrayDim> *p; blitz::TinyVector<int, ArrayDim> idx; }; template <typename T, int ArrayDim> class ArrayTraits<blitz::Array<T, ArrayDim> > : public ArrayTraitsDefaults<T> { public: static const bool allow_auto_unwrap = false; static const size_t depth = ArrayTraits<T>::depth + ArrayDim; typedef BlitzIterator<T, ArrayDim, ArrayDim> range_type; static range_type get_range(const blitz::Array<T, ArrayDim> &arg) { blitz::TinyVector<int, ArrayDim> start_idx; start_idx = 0; return range_type(&arg, start_idx); } }; } // namespace gnuplotio #endif // GNUPLOT_BLITZ_SUPPORT_LOADED #endif // BZ_BLITZ_H // }}}2 // {{{2 Armadillo support // This is outside of the main header guard so that it will be compiled when people do // something like this: // #include "gnuplot-iostream.h" // #include <armadillo> // #include "gnuplot-iostream.h" // Note that it has its own header guard to avoid double inclusion. #ifdef ARMA_INCLUDES #ifndef GNUPLOT_ARMADILLO_SUPPORT_LOADED #define GNUPLOT_ARMADILLO_SUPPORT_LOADED namespace gnuplotio { template <typename T> struct dont_treat_as_stl_container<arma::Row <T> > { typedef boost::mpl::bool_<true> type; }; template <typename T> struct dont_treat_as_stl_container<arma::Col <T> > { typedef boost::mpl::bool_<true> type; }; template <typename T> struct dont_treat_as_stl_container<arma::Mat <T> > { typedef boost::mpl::bool_<true> type; }; template <typename T> struct dont_treat_as_stl_container<arma::Cube <T> > { typedef boost::mpl::bool_<true> type; }; template <typename T> struct dont_treat_as_stl_container<arma::field<T> > { typedef boost::mpl::bool_<true> type; }; // {{{3 Cube template <typename T> class ArrayTraits<arma::Cube<T> > : public ArrayTraitsDefaults<T> { class SliceRange { public: SliceRange() : p(NULL), col(0), slice(0) { } explicit SliceRange(const arma::Cube<T> *_p, size_t _row, size_t _col) : p(_p), row(_row), col(_col), slice(0) { } typedef T value_type; typedef Error_WasNotContainer subiter_type; static const bool is_container = false; bool is_end() const { return slice == p->n_slices; } void inc() { ++slice; } value_type deref() const { return (*p)(row, col, slice); } subiter_type deref_subiter() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "argument was not a container"); throw std::logic_error("static assert should have been triggered by this point"); } private: const arma::Cube<T> *p; size_t row, col, slice; }; class ColRange { public: ColRange() : p(NULL), row(0), col(0) { } explicit ColRange(const arma::Cube<T> *_p, size_t _row) : p(_p), row(_row), col(0) { } typedef T value_type; typedef SliceRange subiter_type; static const bool is_container = true; bool is_end() const { return col == p->n_cols; } void inc() { ++col; } value_type deref() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "can't call deref on an armadillo cube col"); throw std::logic_error("static assert should have been triggered by this point"); } subiter_type deref_subiter() const { return subiter_type(p, row, col); } private: const arma::Cube<T> *p; size_t row, col; }; class RowRange { public: RowRange() : p(NULL), row(0) { } explicit RowRange(const arma::Cube<T> *_p) : p(_p), row(0) { } typedef T value_type; typedef ColRange subiter_type; static const bool is_container = true; bool is_end() const { return row == p->n_rows; } void inc() { ++row; } value_type deref() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "can't call deref on an armadillo cube row"); throw std::logic_error("static assert should have been triggered by this point"); } subiter_type deref_subiter() const { return subiter_type(p, row); } private: const arma::Cube<T> *p; size_t row; }; public: static const bool allow_auto_unwrap = false; static const size_t depth = ArrayTraits<T>::depth + 3; typedef RowRange range_type; static range_type get_range(const arma::Cube<T> &arg) { //std::cout << arg.n_elem << "," << arg.n_rows << "," << arg.n_cols << std::endl; return range_type(&arg); } }; // }}}3 // {{{3 Mat and Field template <typename RF, typename T> class ArrayTraits_ArmaMatOrField : public ArrayTraitsDefaults<T> { class ColRange { public: ColRange() : p(NULL), row(0), col(0) { } explicit ColRange(const RF *_p, size_t _row) : p(_p), row(_row), col(0) { } typedef T value_type; typedef Error_WasNotContainer subiter_type; static const bool is_container = false; bool is_end() const { return col == p->n_cols; } void inc() { ++col; } value_type deref() const { return (*p)(row, col); } subiter_type deref_subiter() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "argument was not a container"); throw std::logic_error("static assert should have been triggered by this point"); } private: const RF *p; size_t row, col; }; class RowRange { public: RowRange() : p(NULL), row(0) { } explicit RowRange(const RF *_p) : p(_p), row(0) { } typedef T value_type; typedef ColRange subiter_type; static const bool is_container = true; bool is_end() const { return row == p->n_rows; } void inc() { ++row; } value_type deref() const { GNUPLOT_STATIC_ASSERT_MSG((sizeof(T) == 0), "can't call deref on an armadillo matrix row"); throw std::logic_error("static assert should have been triggered by this point"); } subiter_type deref_subiter() const { return subiter_type(p, row); } private: const RF *p; size_t row; }; public: static const bool allow_auto_unwrap = false; static const size_t depth = ArrayTraits<T>::depth + 2; typedef RowRange range_type; static range_type get_range(const RF &arg) { //std::cout << arg.n_elem << "," << arg.n_rows << "," << arg.n_cols << std::endl; return range_type(&arg); } }; template <typename T> class ArrayTraits<arma::field<T> > : public ArrayTraits_ArmaMatOrField<arma::field<T>, T> { }; template <typename T> class ArrayTraits<arma::Mat<T> > : public ArrayTraits_ArmaMatOrField<arma::Mat<T>, T> { }; // }}}3 // {{{3 Row template <typename T> class ArrayTraits<arma::Row<T> > : public ArrayTraitsDefaults<T> { public: static const bool allow_auto_unwrap = false; typedef IteratorRange<typename arma::Row<T>::const_iterator, T> range_type; static range_type get_range(const arma::Row<T> &arg) { //std::cout << arg.n_elem << "," << arg.n_rows << "," << arg.n_cols << std::endl; return range_type(arg.begin(), arg.end()); } }; // }}}3 // {{{3 Col template <typename T> class ArrayTraits<arma::Col<T> > : public ArrayTraitsDefaults<T> { public: static const bool allow_auto_unwrap = false; typedef IteratorRange<typename arma::Col<T>::const_iterator, T> range_type; static range_type get_range(const arma::Col<T> &arg) { //std::cout << arg.n_elem << "," << arg.n_rows << "," << arg.n_cols << std::endl; return range_type(arg.begin(), arg.end()); } }; // }}}3 } // namespace gnuplotio #endif // GNUPLOT_ARMADILLO_SUPPORT_LOADED #endif // ARMA_INCLUDES // }}}2 // }}}1
33.537946
197
0.715927
[ "object", "shape", "vector", "3d" ]
b9939d423ce492a7ae87f832614aceb47aa0b36b
1,050
cc
C++
components/arc/intent_helper/local_activity_resolver.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
components/arc/intent_helper/local_activity_resolver.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/arc/intent_helper/local_activity_resolver.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 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 "components/arc/intent_helper/local_activity_resolver.h" #include "url/gurl.h" namespace arc { LocalActivityResolver::LocalActivityResolver() = default; LocalActivityResolver::~LocalActivityResolver() = default; bool LocalActivityResolver::ShouldChromeHandleUrl(const GURL& url) { if (!url.SchemeIsHTTPOrHTTPS()) { // Chrome will handle everything that is not http and https. return true; } for (const IntentFilter& filter : intent_filters_) { if (filter.Match(url)) return false; } // Didn't find any matches for Android so let Chrome handle it. return true; } void LocalActivityResolver::UpdateIntentFilters( std::vector<mojom::IntentFilterPtr> mojo_intent_filters) { intent_filters_.clear(); for (mojom::IntentFilterPtr& mojo_filter : mojo_intent_filters) intent_filters_.emplace_back(mojo_filter); } } // namespace arc
27.631579
73
0.749524
[ "vector" ]
b993d93958923cec84ae415680ca458d16fbeb62
2,997
cpp
C++
development/core/src/SOSrv/SOSrvTraceEx.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
19
2021-05-19T11:03:57.000Z
2022-03-18T06:53:48.000Z
development/core/src/SOSrv/SOSrvTraceEx.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
8
2021-04-26T10:47:20.000Z
2022-03-15T11:25:07.000Z
development/core/src/SOSrv/SOSrvTraceEx.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
11
2021-05-28T06:35:20.000Z
2022-03-31T14:07:25.000Z
//----------------------------------------------------------------------------- // | // Softing Industrial Automation GmbH | // Richard-Reitzner-Allee 6 | // 85540 Haar, Germany | // | // This is a part of the Softing OPC Toolkit | // Copyright (c) 2005-2020 Softing Industrial Automation GmbH | // All Rights Reserved | // | //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // OPC Toolkit - SOSrv | // | // Filename : SOSrvTraceEx.cpp | // Version : 4.47.1 | // Date : 27-July-2020 | // | // Description : OPC Server monitoring classes | // - SOSrvWebTrace: watch object | // | //----------------------------------------------------------------------------- #include "stdafx.h" #ifdef SOSRV #ifdef SOFEATURE_SOAP #include "SOSrvTraceEx.h" //----------------------------------------------------------------------------- // SOSrvWebTrace | //----------------------------------------------------------------------------- SOSrvWebTrace::SOSrvWebTrace(void) { m_nextLine = 0; } SOSrvWebTrace::~SOSrvWebTrace(void) { } void SOSrvWebTrace::onTrace( IN LPCTSTR traceString, IN USHORT /* traceStringLen */, IN USHORT /* level */, IN DWORD /* mask */, IN LPCTSTR /* objId */, IN LPCTSTR /* text */) { SOCmnSingleLock<SOCmnSync> lock(&m_getLock); m_line[m_nextLine].getBuffer((DWORD)_tcslen(traceString) + 5); m_line[m_nextLine] = traceString; // m_line[m_nextLine] += _T("<br>"); m_nextLine++; if (m_nextLine >= SOSRVWEBTRACE_LINE_CNT) { m_nextLine = 0; } } void SOSrvWebTrace::getTrace(SOCmnStringEx& trace) { SOCmnSingleLock<SOCmnSync> lock(&m_getLock); DWORD i, j; trace.getBuffer(SOSRVWEBTRACE_LINE_CNT * 200); j = m_nextLine; for (i = 0; i < SOSRVWEBTRACE_LINE_CNT; i++) { trace += m_line[j]; j++; if (j >= SOSRVWEBTRACE_LINE_CNT) { j = 0; } } } #endif // SOFEATURE_SOAP #endif // SOSRV
34.848837
82
0.326326
[ "object" ]
b99502bc9ee4b76f2d49e7b1166239dc887de371
10,556
cc
C++
chromeos/dbus/nfc_client_helpers.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
chromeos/dbus/nfc_client_helpers.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
chromeos/dbus/nfc_client_helpers.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2013 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 "chromeos/dbus/nfc_client_helpers.h" #include "base/stl_util.h" #include "dbus/values_util.h" namespace chromeos { namespace nfc_client_helpers { const char kNoResponseError[] = "org.chromium.Error.NoResponse"; const char kUnknownObjectError[] = "org.chromium.Error.UnknownObject"; void OnSuccess(const base::Closure& callback, dbus::Response* response) { DCHECK(response); callback.Run(); } void OnError(const ErrorCallback& error_callback, dbus::ErrorResponse* response) { // Error response has optional error message argument. std::string error_name; std::string error_message; if (response) { dbus::MessageReader reader(response); error_name = response->GetErrorName(); reader.PopString(&error_message); } else { error_name = kNoResponseError; error_message = ""; } error_callback.Run(error_name, error_message); } void AppendValueDataAsVariant(dbus::MessageWriter* writer, const base::Value& value) { switch (value.GetType()) { case base::Value::TYPE_DICTIONARY: { const base::DictionaryValue* dictionary = NULL; value.GetAsDictionary(&dictionary); dbus::MessageWriter variant_writer(NULL); dbus::MessageWriter array_writer(NULL); writer->OpenVariant("a{sv}", &variant_writer); variant_writer.OpenArray("{sv}", &array_writer); for (base::DictionaryValue::Iterator iter(*dictionary); !iter.IsAtEnd(); iter.Advance()) { dbus::MessageWriter entry_writer(NULL); array_writer.OpenDictEntry(&entry_writer); entry_writer.AppendString(iter.key()); AppendValueDataAsVariant(&entry_writer, iter.value()); array_writer.CloseContainer(&entry_writer); } variant_writer.CloseContainer(&array_writer); writer->CloseContainer(&variant_writer); break; } case base::Value::TYPE_LIST: { const base::ListValue* list = NULL; value.GetAsList(&list); dbus::MessageWriter variant_writer(NULL); dbus::MessageWriter array_writer(NULL); writer->OpenVariant("av", &variant_writer); variant_writer.OpenArray("v", &array_writer); for (base::ListValue::const_iterator iter = list->begin(); iter != list->end(); ++iter) { const base::Value* value = *iter; AppendValueDataAsVariant(&array_writer, *value); } variant_writer.CloseContainer(&array_writer); writer->CloseContainer(&variant_writer); break; } case base::Value::TYPE_BOOLEAN: case base::Value::TYPE_INTEGER: case base::Value::TYPE_DOUBLE: case base::Value::TYPE_STRING: dbus::AppendBasicTypeValueDataAsVariant(writer, value); break; default: DLOG(ERROR) << "Unexpected type: " << value.GetType(); } } DBusObjectMap::DBusObjectMap(const std::string& service_name, Delegate* delegate, dbus::Bus* bus) : bus_(bus), service_name_(service_name), delegate_(delegate) { DCHECK(bus_); DCHECK(delegate_); } DBusObjectMap::~DBusObjectMap() { // Clean up the Properties structures. We don't explicitly delete the object // proxies, as they are owned by dbus::Bus. for (ObjectMap::iterator iter = object_map_.begin(); iter != object_map_.end(); ++iter) { const dbus::ObjectPath& object_path = iter->first; ObjectPropertyPair pair = iter->second; delegate_->ObjectRemoved(object_path); CleanUpObjectPropertyPair(pair); } } dbus::ObjectProxy* DBusObjectMap::GetObjectProxy( const dbus::ObjectPath& object_path) { return GetObjectPropertyPair(object_path).first; } NfcPropertySet* DBusObjectMap::GetObjectProperties( const dbus::ObjectPath& object_path) { return GetObjectPropertyPair(object_path).second; } void DBusObjectMap::UpdateObjects(const ObjectPathVector& object_paths) { // This set is used to query if an object path was removed, while updating // the removed paths below. The iterator is used as a hint to accelerate // insertion. std::set<dbus::ObjectPath> object_path_set; std::set<dbus::ObjectPath>::iterator object_path_set_iter = object_path_set.begin(); // Add all objects. for (ObjectPathVector::const_iterator iter = object_paths.begin(); iter != object_paths.end(); ++iter) { const dbus::ObjectPath &object_path = *iter; AddObject(object_path); // Neard usually returns object paths in ascending order. Give a hint here // to make insertion amortized constant. object_path_set_iter = object_path_set.insert(object_path_set_iter, object_path); } // Remove all objects that are not in |object_paths|. ObjectMap::const_iterator iter = object_map_.begin(); while (iter != object_map_.end()) { // It is safe to use a const reference here, as DBusObjectMap::RemoveObject // won't access it after the iterator becomes invalidated. const dbus::ObjectPath &object_path = iter->first; ++iter; if (!ContainsKey(object_path_set, object_path)) RemoveObject(object_path); } } bool DBusObjectMap::AddObject(const dbus::ObjectPath& object_path) { ObjectMap::iterator iter = object_map_.find(object_path); if (iter != object_map_.end()) return false; DCHECK(bus_); DCHECK(delegate_); dbus::ObjectProxy* object_proxy = bus_->GetObjectProxy(service_name_, object_path); // Create the properties structure. NfcPropertySet* properties = delegate_->CreateProperties(object_proxy); properties->ConnectSignals(); properties->GetAll(); ObjectPropertyPair object = std::make_pair(object_proxy, properties); object_map_[object_path] = object; VLOG(1) << "Created proxy for object with Path: " << object_path.value() << ", Service: " << service_name_; delegate_->ObjectAdded(object_path); return true; } void DBusObjectMap::RemoveObject(const dbus::ObjectPath& object_path) { DCHECK(bus_); DCHECK(delegate_); ObjectMap::iterator iter = object_map_.find(object_path); if (iter == object_map_.end()) return; // Notify the delegate, so that it can perform any clean up that is // necessary. delegate_->ObjectRemoved(object_path); // Clean up the object proxy and the properties structure. ObjectPropertyPair pair = iter->second; CleanUpObjectPropertyPair(pair); object_map_.erase(iter); VLOG(1) << "Object proxy removed for object path: " << object_path.value(); } void DBusObjectMap::RefreshProperties(const dbus::ObjectPath& object_path) { NfcPropertySet* properties = GetObjectProperties(object_path); if (properties) properties->GetAll(); } void DBusObjectMap::RefreshAllProperties() { for (ObjectMap::const_iterator iter = object_map_.begin(); iter != object_map_.end(); ++iter) { const dbus::ObjectPath& object_path = iter->first; RefreshProperties(object_path); } } ObjectPathVector DBusObjectMap::GetObjectPaths() { std::vector<dbus::ObjectPath> object_paths; for (ObjectMap::const_iterator iter = object_map_.begin(); iter != object_map_.end(); ++iter) { const dbus::ObjectPath& object_path = iter->first; object_paths.push_back(object_path); } return object_paths; } DBusObjectMap::ObjectPropertyPair DBusObjectMap::GetObjectPropertyPair( const dbus::ObjectPath& object_path) { ObjectMap::iterator iter = object_map_.find(object_path); if (iter != object_map_.end()) return iter->second; return std::make_pair(static_cast<dbus::ObjectProxy*>(NULL), static_cast<NfcPropertySet*>(NULL)); } void DBusObjectMap::CleanUpObjectPropertyPair(const ObjectPropertyPair& pair) { // Don't remove the object proxy. There is a bug in dbus::Bus that causes a // crash when object proxies are removed, due to the proxy objects not being // properly reference counted. (See crbug.com/170182 and crbug.com/328264). NfcPropertySet* properties = pair.second; delete properties; } ObjectProxyTree::ObjectProxyTree() { } ObjectProxyTree::~ObjectProxyTree() { for (PathsToObjectMapsType::iterator iter = paths_to_object_maps_.begin(); iter != paths_to_object_maps_.end(); ++iter) { DBusObjectMap* object_map = iter->second; delete object_map; } } bool ObjectProxyTree::CreateObjectMap(const dbus::ObjectPath& object_path, const std::string& service_name, DBusObjectMap::Delegate* delegate, dbus::Bus* bus) { if (ContainsKey(paths_to_object_maps_, object_path)) { LOG(ERROR) << "Mapping already exists for object path: " << object_path.value(); return false; } paths_to_object_maps_[object_path] = new DBusObjectMap(service_name, delegate, bus); return true; } void ObjectProxyTree::RemoveObjectMap(const dbus::ObjectPath& object_path) { PathsToObjectMapsType::iterator iter = paths_to_object_maps_.find(object_path); if (iter == paths_to_object_maps_.end()) return; DBusObjectMap* object_map = iter->second; paths_to_object_maps_.erase(iter); delete object_map; } DBusObjectMap* ObjectProxyTree::GetObjectMap( const dbus::ObjectPath& object_path) { PathsToObjectMapsType::iterator iter = paths_to_object_maps_.find(object_path); if (iter == paths_to_object_maps_.end()) return NULL; return iter->second; } dbus::ObjectProxy* ObjectProxyTree::FindObjectProxy( const dbus::ObjectPath& object_proxy_path) { for (PathsToObjectMapsType::iterator iter = paths_to_object_maps_.begin(); iter != paths_to_object_maps_.end(); ++iter) { DBusObjectMap* object_map = iter->second; dbus::ObjectProxy* object_proxy = object_map->GetObjectProxy(object_proxy_path); if (object_proxy) return object_proxy; } return NULL; } NfcPropertySet* ObjectProxyTree::FindObjectProperties( const dbus::ObjectPath& object_proxy_path) { for (PathsToObjectMapsType::iterator iter = paths_to_object_maps_.begin(); iter != paths_to_object_maps_.end(); ++iter) { DBusObjectMap* object_map = iter->second; NfcPropertySet* properties = object_map->GetObjectProperties(object_proxy_path); if (properties) return properties; } return NULL; } } // namespace nfc_client_helpers } // namespace chromeos
34.838284
79
0.697992
[ "object", "vector" ]
b9a063f3cd3697c949e786b26e0c243ab1dc546b
3,026
cpp
C++
crystal/operator/generic/ConvertToRecordArray.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
2
2020-10-02T03:31:50.000Z
2020-12-31T09:41:48.000Z
crystal/operator/generic/ConvertToRecordArray.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
null
null
null
crystal/operator/generic/ConvertToRecordArray.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017-present Yeolar * * 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 "crystal/operator/generic/ConvertToRecordArray.h" #include "crystal/serializer/DynamicEncoding.h" namespace crystal { namespace op { struct ItemMeta { std::string name; size_t jIndex; ItemType type; }; void serializeItemToRecord( const DataView& view, size_t i, const ItemMeta& meta, int tag, Record& record) { switch (meta.type.type) { #define ENCODE(_type, enum_type) \ case DataType::enum_type: { \ if (meta.type.count != 1) { \ auto value = view.get<Array<_type>>(i, meta.jIndex); \ record.set<Array<_type>>(tag, *value); \ } else { \ auto value = view.get<_type>(i, meta.jIndex); \ record.set<_type>(tag, *value); \ } \ } ENCODE(bool, BOOL) ENCODE(int8_t, INT8) ENCODE(int16_t, INT16) ENCODE(int32_t, INT32) ENCODE(int64_t, INT64) ENCODE(uint8_t, UINT8) ENCODE(uint16_t, UINT16) ENCODE(uint32_t, UINT32) ENCODE(uint64_t, UINT64) ENCODE(float, FLOAT) ENCODE(double, DOUBLE) ENCODE(std::string_view, STRING) #undef ENCODE case DataType::UNKNOWN: CRYSTAL_LOG(ERROR) << "unsupport data type: " << dataTypeToString(meta.type.type); break; } } RecordArray ConvertToRecordArray::compose(DataView& view) const { std::vector<ItemMeta> metas; for (auto p : view.fieldIndex().index) { ItemMeta meta = { p.first, p.second, view.getColType(p.second), }; metas.push_back(meta); } RecordMeta recordMeta; int tag = 1; for (auto& meta : metas) { recordMeta.addMeta(FieldMeta(meta.name, tag++, meta.type.type, sizeOf(meta.type.type) * 8, meta.type.count)); } RecordArray out(recordMeta); for (auto i : view.docIndex()) { Record record = out.createRecord(); tag = 1; for (auto& meta : metas) { serializeItemToRecord(view, i, meta, tag++, record); } } return out; } dynamic ConvertToRecordArray::toDynamic() const { return dynamic::object ("ConvertToRecordArray", dynamic::object); } } // namespace op } // namespace crystal
29.096154
75
0.583609
[ "object", "vector" ]
b9a53d0c772f6fda02908cb0f81ae2099b6013b4
1,941
cpp
C++
unitTests/PerformanceLab.cpp
andersc/efp
57b50b58b29d35b4fc8451a912d985001cff4060
[ "MIT" ]
17
2020-05-12T14:38:55.000Z
2021-11-18T08:13:24.000Z
efp/unitTests/PerformanceLab.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
2
2020-09-15T15:22:39.000Z
2020-09-28T08:59:22.000Z
efp/unitTests/PerformanceLab.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
1
2021-09-28T13:22:59.000Z
2021-09-28T13:22:59.000Z
// // Created by Anders Cedronius on 2019-12-05. // //PerformanceLab just send packets / recieve and profile the code #include "PerformanceLab.h" void PerformanceLab::sendData(const std::vector<uint8_t> &subPacket) { ElasticFrameMessages info = myEFPReciever->receiveFragment(subPacket, 0); if (info != ElasticFrameMessages::noError) { std::cout << "Error-> " << signed(info) << std::endl; } } void PerformanceLab::gotData(ElasticFrameProtocolReceiver::pFramePtr &packet) { if (!(++unitTestPacketNumberReciever % 100)) { std::cout << "Got packet number " << unsigned(unitTestPacketNumberReciever) << std::endl; } } bool PerformanceLab::startUnitTest() { ElasticFrameMessages result; std::vector<uint8_t> mydata; uint8_t streamID = 1; myEFPReciever = new(std::nothrow) ElasticFrameProtocolReceiver(5, 2); myEFPPacker = new(std::nothrow) ElasticFrameProtocolSender(MTU); if (myEFPReciever == nullptr || myEFPPacker == nullptr) { if (myEFPReciever) delete myEFPReciever; if (myEFPPacker) delete myEFPPacker; return false; } myEFPPacker->sendCallback = std::bind(&PerformanceLab::sendData, this, std::placeholders::_1); myEFPReciever->receiveCallback = std::bind(&PerformanceLab::gotData, this, std::placeholders::_1); uint64_t packetNumber = 0; while (true) { mydata.clear(); size_t randSize = rand() % 1000000 + 1; mydata.resize(randSize); result = myEFPPacker->packAndSend(mydata, ElasticFrameContent::h264, packetNumber, packetNumber, EFP_CODE('A', 'N', 'X', 'B'), streamID, NO_FLAGS); packetNumber++; if (result != ElasticFrameMessages::noError) { std::cout << " Failed in the packAndSend method. Error-> " << signed(result) << std::endl; delete myEFPPacker; delete myEFPReciever; return false; } } }
37.326923
155
0.655848
[ "vector" ]
b9a7e50facdafaa6943a02fbf11cef3ee17c52ee
11,722
cpp
C++
packages/monte_carlo/collision/photon/test/tstEfficientCoherentScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/photon/test/tstEfficientCoherentScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/photon/test/tstEfficientCoherentScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstEfficientCoherentScatteringDistribution.cpp //! \author Alex Robinson //! \brief Efficient coherent scattering distribution unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> #include <limits> // FRENSIE Includes #include "MonteCarlo_EfficientCoherentScatteringDistribution.hpp" #include "MonteCarlo_StandardFormFactorSquared.hpp" #include "Data_ACEFileHandler.hpp" #include "Data_XSSEPRDataExtractor.hpp" #include "Utility_DiscreteDistribution.hpp" #include "Utility_TabularDistribution.hpp" #include "Utility_RandomNumberGenerator.hpp" #include "Utility_InverseSquareAngstromUnit.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Testing Variable //---------------------------------------------------------------------------// std::shared_ptr<MonteCarlo::PhotonScatteringDistribution> distribution; std::shared_ptr<MonteCarlo::AdjointPhotonScatteringDistribution> adjoint_distribution; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the distribution can be evaluated FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, evaluate ) { double dist_value = distribution->evaluate( 0.1, 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 3.354834939813898e3, 1e-15 ); dist_value = distribution->evaluate( 0.1, 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 4.17273487105470142, 1e-15 ); dist_value = distribution->evaluate( 0.1, -1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 3.59244179705391486, 1e-15 ); dist_value = distribution->evaluate( 1.0, 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 3354.83493981389802, 1e-15 ); dist_value = distribution->evaluate( 1.0, 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 0.00346135656968035591, 1e-15 ); dist_value = distribution->evaluate( 1.0, -1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( dist_value, 0.00114806389085036088, 1e-15 ); } //---------------------------------------------------------------------------// // Check that the distribution pdf can be evaluated FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, evaluatePDF ) { double pdf_value = distribution->evaluatePDF( 0.1, 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 49.4688663359142353, 1e-15 ); pdf_value = distribution->evaluatePDF( 0.1, 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 0.0615292457884274099, 1e-15 ); pdf_value = distribution->evaluatePDF( 0.1, -1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 0.0529725087124166966, 1e-15 ); pdf_value = distribution->evaluatePDF( 1.0, 1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 3673.12567843006855, 1e-15 ); pdf_value = distribution->evaluatePDF( 1.0, 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 0.00378975357249642037, 1e-15 ); pdf_value = distribution->evaluatePDF( 1.0, -1.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( pdf_value, 0.00125698671726446362, 1e-15 ); } //---------------------------------------------------------------------------// // Check that the integrated cross section can be evaluated FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, evaluateIntegratedCrossSection ) { double cross_section = distribution->evaluateIntegratedCrossSection( 0.1, 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 6.78170976677162821e1, 1e-15 ); cross_section = distribution->evaluateIntegratedCrossSection( 1.0, 1e-3 ); FRENSIE_CHECK_FLOATING_EQUALITY( cross_section, 9.13346080019725521e-1, 1e-15 ); } //---------------------------------------------------------------------------// // Check that the distribution can be sampled from FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, sample ) { double outgoing_energy, scattering_angle_cosine; // Set up the random number stream std::vector<double> fake_stream( 4 ); fake_stream[0] = 0.5; fake_stream[1] = 0.942; // reject fake_stream[2] = 0.5; fake_stream[3] = 0.941; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); distribution->sample( 0.1, outgoing_energy, scattering_angle_cosine ); FRENSIE_CHECK_EQUAL( outgoing_energy, 0.1 ); FRENSIE_CHECK_FLOATING_EQUALITY( scattering_angle_cosine, 0.940007827406442842, 1e-15 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that the distribution can be sampled from FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, sampleAndRecordTrials ) { double outgoing_energy, scattering_angle_cosine; MonteCarlo::PhotonScatteringDistribution::Counter trials = 0; // Set up the random number stream std::vector<double> fake_stream( 4 ); fake_stream[0] = 0.5; fake_stream[1] = 0.942; // reject fake_stream[2] = 0.5; fake_stream[3] = 0.941; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); distribution->sampleAndRecordTrials( 0.1, outgoing_energy, scattering_angle_cosine, trials ); FRENSIE_CHECK_EQUAL( outgoing_energy, 0.1 ); FRENSIE_CHECK_FLOATING_EQUALITY( scattering_angle_cosine, 0.940007827406442842, 1e-15 ); FRENSIE_CHECK_EQUAL( 1.0/trials, 0.5 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a photon can be scattered coherently FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, scatterPhoton ) { MonteCarlo::ParticleBank bank; MonteCarlo::PhotonState photon( 0 ); photon.setEnergy( 4.95936772145E-03 ); photon.setDirection( 0.0, 0.0, 1.0 ); Data::SubshellType shell_of_interaction; // Set up the random number stream std::vector<double> fake_stream( 5 ); fake_stream[0] = 1.00475965594E-03; // sample form factor function squared (y = 1E6 cm) fake_stream[1] = 9.98800000000E-01; // reject the cosine scattering angle form function rejection loop fake_stream[2] = 6.50327467413E-01; // sample form factor function squared (y = 3E7 cm) fake_stream[3] = 5.07800000000E-01; // accept the cosine scattering angle form function rejection loop fake_stream[4] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); distribution->scatterPhoton( photon, bank, shell_of_interaction ); Utility::RandomNumberGenerator::unsetFakeStream(); FRENSIE_CHECK_FLOATING_EQUALITY( photon.getEnergy(), 4.95936772145E-03, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( photon.getZDirection(), -0.125019990362325473, 1e-14 ); FRENSIE_CHECK_EQUAL( shell_of_interaction, Data::UNKNOWN_SUBSHELL ); } //---------------------------------------------------------------------------// // Check that an adjoint photon can be scattered coherently FRENSIE_UNIT_TEST( EfficientCoherentScatteringDistribution, scatterAdjointPhoton ) { MonteCarlo::ParticleBank bank; MonteCarlo::AdjointPhotonState adjoint_photon( 0 ); adjoint_photon.setEnergy( 4.95936772145E-03 ); adjoint_photon.setDirection( 0.0, 0.0, 1.0 ); Data::SubshellType shell_of_interaction; // Set up the random number stream std::vector<double> fake_stream( 5 ); fake_stream[0] = 1.00475965594E-03; // sample form factor function squared (y = 1E6 cm) fake_stream[1] = 9.98800000000E-01; // reject the cosine scattering angle form function rejection loop fake_stream[2] = 6.50327467413E-01; // sample form factor function squared (y = 3E7 cm) fake_stream[3] = 5.07800000000E-01; // accept the cosine scattering angle form function rejection loop fake_stream[4] = 0.0; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); adjoint_distribution->scatterAdjointPhoton( adjoint_photon, bank, shell_of_interaction ); Utility::RandomNumberGenerator::unsetFakeStream(); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getEnergy(), 4.95936772145E-03, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( adjoint_photon.getZDirection(), -0.125019990362325473, 1e-14 ); FRENSIE_CHECK_EQUAL( shell_of_interaction, Data::UNKNOWN_SUBSHELL ); } //---------------------------------------------------------------------------// // Custom Setup //---------------------------------------------------------------------------// FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN(); std::string test_ace_file_name; unsigned test_ace_file_start_line; FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS() { ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_ace_file", test_ace_file_name, "", "Test ACE file name" ); ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_ace_file_start_line", test_ace_file_start_line, 1, "Test ACE file start line" ); } FRENSIE_CUSTOM_UNIT_TEST_INIT() { { // Create a file handler and data extractor std::shared_ptr<Data::ACEFileHandler> ace_file_handler( new Data::ACEFileHandler( test_ace_file_name, "82000.12p", test_ace_file_start_line ) ); std::shared_ptr<Data::XSSEPRDataExtractor> xss_data_extractor( new Data::XSSEPRDataExtractor( ace_file_handler->getTableNXSArray(), ace_file_handler->getTableJXSArray(), ace_file_handler->getTableXSSArray() ) ); // Extract the form factor Utility::ArrayView<const double> jcohe_block = xss_data_extractor->extractJCOHEBlock(); unsigned form_factor_size = jcohe_block.size()/3; std::vector<double> recoil_momentum_squared( jcohe_block( 0, form_factor_size ) ); std::vector<double> form_factor_squared( jcohe_block( 2*form_factor_size, form_factor_size ) ); for( unsigned i = 0; i < form_factor_size; ++i ) { recoil_momentum_squared[i] *= recoil_momentum_squared[i]; form_factor_squared[i] *= form_factor_squared[i]; } std::shared_ptr<Utility::UnitAwareTabularUnivariateDistribution<Utility::Units::InverseSquareAngstrom,void> > raw_form_factor_squared( new Utility::UnitAwareTabularDistribution<Utility::LinLin,Utility::Units::InverseSquareAngstrom,void>( recoil_momentum_squared, form_factor_squared ) ); std::shared_ptr<const MonteCarlo::FormFactorSquared> form_factor_obj( new MonteCarlo::StandardFormFactorSquared<Utility::Units::InverseSquareAngstrom>( raw_form_factor_squared ) ); // Create the scattering distribution distribution.reset( new MonteCarlo::EfficientCoherentScatteringDistribution( form_factor_obj ) ); adjoint_distribution.reset( new MonteCarlo::EfficientCoherentScatteringDistribution( form_factor_obj ) ); } // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); } FRENSIE_CUSTOM_UNIT_TEST_SETUP_END(); //---------------------------------------------------------------------------// // end tstEfficientCoherentScatteringDistribution.cpp //---------------------------------------------------------------------------//
36.63125
113
0.643917
[ "vector" ]
b9a8d0c213a240add8523a0b30d42e53a44e7302
96,571
cpp
C++
IUI/Control/ControlCore/RichTextBox/RichEditSrc/select.cpp
jiaojian8063868/portsip-softphone-windows
df1b6391ff5d074cbc98cb559e52b181ef8e1b17
[ "BSD-2-Clause" ]
null
null
null
IUI/Control/ControlCore/RichTextBox/RichEditSrc/select.cpp
jiaojian8063868/portsip-softphone-windows
df1b6391ff5d074cbc98cb559e52b181ef8e1b17
[ "BSD-2-Clause" ]
null
null
null
IUI/Control/ControlCore/RichTextBox/RichEditSrc/select.cpp
jiaojian8063868/portsip-softphone-windows
df1b6391ff5d074cbc98cb559e52b181ef8e1b17
[ "BSD-2-Clause" ]
2
2021-12-31T03:42:48.000Z
2022-02-20T08:37:41.000Z
/* * @doc INTERNAL * * @module SELECT.C -- Implement the CTxtSelection class | * * This module implements the internal CTxtSelection methods. * See select2.c and range2.c for the ITextSelection methods * * Authors: <nl> * Original RichEdit code: David R. Fulmer <nl> * Christian Fortini <nl> * Murray Sargent <nl> * * @devnote * The selection UI is one of the more intricate parts of an editor. * One common area of confusion is the "ambiguous cp", that is, * a cp at the beginning of one line, which is also the cp at the * end of the previous line. We control which location to use by * the _fCaretNotAtBOL flag. Specifically, the caret is OK at the * beginning of the line (BOL) (_fCaretNotAtBOL = FALSE) except in * three cases: * * 1) the user clicked at or past the end of a wrapped line, * 2) the user typed End key on a wrapped line, * 3) the active end of a nondegenerate selection is at the EOL. * * Copyright (c) 1995-1996, Microsoft Corporation. All rights reserved. */ #include "stdafx.h" #include "_common.h" #include "_select.h" #include "_edit.h" #include "_disp.h" #include "_measure.h" #include "_font.h" #include "_NLSPRCS.h" #ifndef MACPORT #include "_ime.h" // default FE Fonts for handling autoFont switching TCHAR lpJapanFontName[] = { 0x0FF2D, 0x0FF33, L' ', 0x0660E, 0x0671D, 0x0 }; TCHAR lpKoreanFontName[] = { 0x0AD74, 0x0B9BC, 0x0CCB4, 0x0 }; TCHAR lpSChineseFontName[] = { 0x05B8B, 0x04F53, 0x0 }; TCHAR lpTChineseFontName[] = { 0x065B0, 0x07D30, 0x0660E, 0x09AD4, 0x0 }; #endif /* * GetCaretDelta () * * @func Get size of caret to add to current caret position to get the * maximum extent needed to display caret. * * @rdesc Size of caret over 1 pixel * * @devnote This exists solely to abstract this calculation so that if we ever * get a variable size caret, we just change this spot. */ inline int GetCaretDelta() { return dxCaret - 1; } ASSERTDATA // ======================= Invariant stuff and Constructors ====================================================== #define DEBUG_CLASSNAME CTxtSelection #include "_invar.h" #ifdef DEBUG BOOL CTxtSelection::Invariant(void) const { // FUTURE: maybe add some thoughtful asserts... static LONG numTests = 0; numTests++; // how many times we've been called. return CTxtRange::Invariant(); } #endif CTxtSelection::CTxtSelection(CDisplay *const pdp) : CTxtRange(pdp->GetED()) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::CTxtSelection"); Assert(pdp); _fSel = TRUE; // This range is a selection _pdp = pdp; // Set the show selection flag to the inverse of the hide selection flag in // the PED. _fShowSelection = !pdp->GetED()->fHideSelection(); // When we are initialized we don't have a selection therefore, // we do want to show the caret. _fShowCaret = TRUE; } inline void SelectionNull(CTxtEdit *ped) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "SelectionNull"); if (ped) { ped->SetSelectionToNull(); } } CTxtSelection::~CTxtSelection() { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::~CTxtSelection"); // Notify edit object that we are gone (if there's a nonNULL ped, i.e., // if the selection isn't a zombie). SelectionNull(GetPed()); } //////////////////////////////// Assignments ///////////////////////////////////////// CRchTxtPtr &CTxtSelection::operator =(const CRchTxtPtr &rtp) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::operator ="); _TEST_INVARIANT_ return CTxtRange::operator =(rtp); } CTxtRange &CTxtSelection::operator =(const CTxtRange &rg) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::operator ="); _TEST_INVARIANT_ return CTxtRange::operator =(rg); } ////////////////////// Update caret & selection mechanism /////////////////////////////// /* * CTxtSelection::Update(fScrollIntoView) * * @mfunc * Update selection and/or caret on screen. As a side * effect, this methods ends deferring updates. * * @rdesc * TRUE if success, FALSE otherwise */ BOOL CTxtSelection::Update( BOOL fScrollIntoView) //@parm TRUE if should scroll caret into view { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Update"); _TEST_INVARIANT_ if (!GetPed()->fInplaceActive() || GetPed()->IsStreaming()) { // nothing to do while inactive or streaming in text or RTF data. return TRUE; } // Recalc up to active end (caret) if (!_pdp->WaitForRecalc(GetCp(), -1)) { // Line recalc failure Set(0, 0); // Put caret at start of text } ShowCaret(!_cch); UpdateCaret(fScrollIntoView); // Update Caret position, possibly // scrolling it into view GetPed()->TxShowCaret(FALSE); UpdateSelection(); // Show new selection GetPed()->TxShowCaret(TRUE); return TRUE; } /* * CTxtSelection::UpdateCaret(fScrollIntoView) * * @mfunc * This routine updates caret/selection active end on screen. * It figures its position, size, clipping, etc. It can optionally * scroll the caret into view. * * @rdesc * TRUE if view was scrolled, FALSE otherwise * * @devnote * The caret is actually shown on screen only if _fShowCaret is TRUE. */ BOOL CTxtSelection::UpdateCaret( BOOL fScrollIntoView) //@parm If TRUE, scroll caret into view if we have // focus or if not and selection isn't hidden { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::UpdateCaret"); // of focus _TEST_INVARIANT_ // Is the display currently frozen if (_pdp->IsFrozen()) { // Save this call for another time. _pdp->SaveUpdateCaret(fScrollIntoView); return FALSE; } BOOL fAutoVScroll = FALSE; BOOL fAutoHScroll = FALSE; CTxtEdit *ped = _pdp->GetED(); POINT pt; CLinePtr rp(_pdp); RECT rcClient; RECT rcView; LONG xWidthView; LONG yHeightView; LONG xScroll = _pdp->GetXScroll(); LONG yScroll = _pdp->GetYScroll();; INT yAbove = 0; // ascent of line above & beyond IP INT yAscent; // ascent of IP INT yAscentLine; LONG yBase; // base of IP & line INT yBelow = 0; // descent of line below & beyond IP INT yDescent; // descent of IP INT yDescentLine; const INT yHeightSave = _yHeightCaret; INT ySum; LONG yViewTop; LONG yViewBottom; DWORD dwScrollBars = ped->TxGetScrollBars(); if (ped->IsStreaming()) { // don't bother doing anything if we are loading in text or RTF // data. return FALSE; } _yCurrentDescent = -1; // We better be inplace active if we get here AssertSz(GetPed()->fInplaceActive(), "CTxtSelection::UpdateCaret no inplace active"); // Get the client rectangle once to save various // callers getting it. GetPed()->TxGetClientRect(&rcClient); _pdp->GetViewRect(rcView, &rcClient); // View can be bigger than client rect because insets can be negative. // We don't want the caret to be any bigger than the client view otherwise // the caret will leave pixel dust on other windows. yViewTop = max(rcView.top, rcClient.top); yViewBottom = min(rcView.bottom, rcClient.bottom); xWidthView = rcView.right - rcView.left; yHeightView = yViewBottom - yViewTop; if (fScrollIntoView) { fAutoVScroll = (dwScrollBars & ES_AUTOVSCROLL) != 0; fAutoHScroll = (dwScrollBars & ES_AUTOHSCROLL) != 0; // If we're not forcing a scroll, only scroll if window has focus // or selection isn't hidden fScrollIntoView = ped->_fFocus || !ped->fHideSelection(); } if (!fScrollIntoView && (fAutoVScroll || fAutoHScroll)) { // Would scroll but don't have ped->_fScrollCaretOnFocus = TRUE; // focus. Signal to scroll fAutoVScroll = fAutoHScroll = FALSE; // when we do get focus } if (_pdp->PointFromTp(*this, &rcClient, _fCaretNotAtBOL, pt, &rp, TA_BASELINE) < 0) { goto not_visible; } // HACK ALERT - Because plain-text multiline controls do not have the // automatic EOP, we need to special case their processing here because // if you are at the end of the document and last character is an EOP, // you need to be on the next line in the display not the current line. if (CheckPlainTextFinalEOP()) // terminated by an EOP { if (GetPF()->wAlignment == PFA_CENTER) { pt.x = (rcView.left + rcView.right) >> 1; } else // Set the x to the beginning of the line { pt.x = rcView.left; } pt.x -= xScroll; // Absolute coordinate // Bump the y up a line. We get away with the calculation because // the document is plain text so all lines have the same height. // Also, note that the rp below is used only for height // calculations, so it is perfectly valid for the same reason // even though it is not actually pointing to the correct line. // (I told you this is a hack.) pt.y += rp->_yHeight; } _xCaret = (LONG) pt.x; yBase = (LONG) pt.y; // Compute caret height, ascent, and descent yAscent = GetCaretHeight(&yDescent); yAscent -= yDescent; // Default to line empty case. Use what came back from the default // calculation above. yDescentLine = yDescent; yAscentLine = yAscent; if (rp.IsValid()) { if (rp->_yDescent != -1) { // Line has been measured so we can use the values in the // line. yDescentLine = rp->_yDescent; yAscentLine = rp->_yHeight - yDescentLine; } } if (yAscent + yDescent == 0) { yAscent = yAscentLine; yDescent = yDescentLine; } else { // this is a bit counter-intuitive at first. Basically, // even if the caret should be large (i.e. due to a // large font at the insertion point), we can only make it // as big as the line. If a character is inserted, then // the line becomes bigger, and we can make the caret // the correct size. yAscent = min(yAscent, yAscentLine); yDescent = min(yDescent, yDescentLine); } if (fAutoVScroll) { Assert(yDescentLine >= yDescent); Assert(yAscentLine >= yAscent); yBelow = yDescentLine - yDescent; yAbove = yAscentLine - yAscent; ySum = yAscent; // Scroll as much as possible into view, giving priorities // primarily to IP and secondarily ascents if (ySum > yHeightView) { yAscent = yHeightView; yDescent = 0; yAbove = 0; yBelow = 0; } else if ((ySum += yDescent) > yHeightView) { yDescent = yHeightView - yAscent; yAbove = 0; yBelow = 0; } else if ((ySum += yAbove) > yHeightView) { yAbove = yHeightView - (ySum - yAbove); yBelow = 0; } else if ((ySum += yBelow) > yHeightView) { yBelow = yHeightView - (ySum - yBelow); } } #ifdef DEBUG else { AssertSz(yAbove == 0, "yAbove non-zero"); AssertSz(yBelow == 0, "yBelow non-zero"); } #endif // Update real caret x pos (constant during vertical moves) _xCaretReally = _xCaret - rcView.left + xScroll; Assert(_xCaretReally >= 0); if (_xCaret + GetCaretDelta() > rcView.right && // Caret off right edge, !((dwScrollBars & ES_AUTOHSCROLL) || // not auto hscrolling _pdp->IsHScrollEnabled())) // and no scrollbar: { // Back caret up to _xCaret = rcView.right - dxCaret; // exactly the right edge } // From this point on we need a new caret _fCaretCreated = FALSE; if (ped->_fFocus) { ped->TxShowCaret(FALSE); // Hide old caret before } // making a new one if (yBase + yDescent + yBelow > yViewTop && yBase - yAscent - yAbove < yViewBottom) { if (yBase - yAscent - yAbove < yViewTop) // Caret is partially { // visible if (fAutoVScroll) // Top isn't visible { goto scrollit; } Assert(yAbove == 0); yAscent = yBase - yViewTop; // Change ascent to amount if (yBase < yViewTop) // visible { // Move base to top yDescent += yAscent; yAscent = 0; yBase = yViewTop; } } if (yBase + yDescent + yBelow > yViewBottom) { if (fAutoVScroll) // Bottom isn't visible { goto scrollit; } Assert(yBelow == 0); yDescent = yViewBottom - yBase; // Change descent to amount if (yBase > yViewBottom) // visible { // Move base to bottom yAscent += yDescent; yDescent = 0; yBase = yViewBottom; } } // Anything still visible? if (yAscent <= 0 && yDescent <= 0) { goto not_visible; } if (((_xCaret <= (rcView.left + CDisplay::_xWidthSys))// Left isn't visible && (xScroll != 0)) || (_xCaret + GetCaretDelta() > rcView.right))// Right isn't visible { if (fAutoHScroll) { goto scrollit; } goto not_visible; } _yCaret = yBase - yAscent; _yHeightCaret = (INT) yAscent + yDescent; _yCurrentDescent = yDescent; } else if (fAutoHScroll || fAutoVScroll) // Caret isn't visible { goto scrollit; // scroll it into view } else { not_visible: // Caret isn't visible, don't show it _xCaret = -32000; _yCaret = -32000; _yHeightCaret = 1; } // Now update caret for real on screen // We only want to show the caret if it is in the view // and there is no selection. if ((ped->_fFocus) && _fShowCaret && (0 == _cch)) { CreateCaret(); ped->TxShowCaret(TRUE); CheckChangeKeyboardLayout(FALSE); } #ifdef DBCS UpdateIMEWindow(); FSetIMEFontH(ped->_hwnd, AttGetFontHandle(ped, ped->_cpCaret)); #endif return FALSE; scrollit: if (fAutoVScroll) { // Scroll to top for cp = 0. This is important if the first line // contains object(s) taller than the client area is high. The // resulting behavior agrees with the Word UI in all ways except in // Backspacing (deleting) the char at cp = 0 when it is followed by // other chars that preceed the large object. if (!GetCp()) { yScroll = 0; } else if (yBase - yAscent - yAbove < yViewTop) // Top invisible { yScroll -= yViewTop - (yBase - yAscent - yAbove); // Make it so } else if (yBase + yDescent + yBelow > yViewBottom) // Bottom invisible { yScroll += yBase + yDescent + yBelow - yViewBottom; // Make it so // Don't do following special adjust if the current line is bigger // than the client area if (rp->_yHeight < yViewBottom - yViewTop) { yScroll = _pdp->AdjustToDisplayLastLine(yBase + rp->_yHeight, yScroll); } } } if (fAutoHScroll) { if (_xCaret <= (rcView.left + CDisplay::_xWidthSys)) // Left invisible { xScroll -= rcView.left - _xCaret; // Make it visible if (xScroll > 0) // Scroll left in { // chunks to make xScroll -= xWidthView / 3; // typing faster xScroll = max(0, xScroll); } } else if (_xCaret + GetCaretDelta() > rcView.right) // right invisible xScroll += _xCaret + dxCaret - rcView.left // Make it visible - xWidthView; // We don't scroll // in chunks because // this more edit // control like. //- xWidthView * 2 / 3; // scrolling in } // chunks if (yScroll != _pdp->GetYScroll() || xScroll != _pdp->GetXScroll()) { return _pdp->ScrollView(xScroll, yScroll, FALSE, FALSE); } #ifdef DBCS VwUpdateIMEWindow(ped); FSetIMEFontH(ped->_hwnd, AttGetFontHandle(ped, ped->_cpCaret)); #endif return FALSE; } /* * CTxtSelection::GetCaretHeight(pyDescent) * * @mfunc * Add a given amount to _xCaret (to make special case of inserting * a character nice and fast) * * @rdesc * Caret height, <lt> 0 if failed */ INT CTxtSelection::GetCaretHeight( INT *pyDescent) const //@parm Out parm to receive caret descent { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::GetCaretHeight"); // (undefined if the return value is <lt> 0) _TEST_INVARIANT_ const CCharFormat *pcf = GetPed()->GetCharFormat(_iFormat); const CDevDesc *pdd = _pdp->GetDdRender(); INT CaretHeight = -1; HDC hdc; CCcs *pccs; hdc = pdd->GetDC(); if (!hdc) { return -1; } pccs = fc().GetCcs(hdc, pcf, _pdp->GetZoomNumerator(), _pdp->GetZoomDenominator(), GetDeviceCaps(hdc, LOGPIXELSY)); if (!pccs) { goto ret; } if (pyDescent) { *pyDescent = (INT) pccs->_yDescent; } CaretHeight = pccs->_yHeight; pccs->Release(); ret: pdd->ReleaseDC(hdc); return CaretHeight; } /* * CTxtSelection::ShowCaret(fShow) * * @mfunc * Hide or show caret * * @rdesc * TRUE if caret was previously shown, FALSE if it was hidden */ BOOL CTxtSelection::ShowCaret( BOOL fShow) //@parm TRUE for showing, FALSE for hiding { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::ShowCaret"); _TEST_INVARIANT_ const BOOL fRet = _fShowCaret; if (fRet != fShow) { _fShowCaret = fShow; if (GetPed()->_fFocus) { if (fShow && !_fCaretCreated) { CreateCaret(); } GetPed()->TxShowCaret(fShow); } } return fRet; } /* * CTxtSelection::IsCaretInView() * * @mfunc * Returns TRUE iff caret is inside visible view */ BOOL CTxtSelection::IsCaretInView() const { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::IsCaretInView"); _TEST_INVARIANT_ RECT rc; _pdp->GetViewRect(rc); return (_xCaret + dxCaret > rc.left) && (_xCaret < rc.right) && (_yCaret + _yHeightCaret > rc.top) && (_yCaret < rc.bottom); } /* * CTxtSelection::CaretNotAtBOL() * * @mfunc * Returns TRUE iff caret is not allowed at BOL */ BOOL CTxtSelection::CaretNotAtBOL() const { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::CaretNotAtBOL"); _TEST_INVARIANT_ return _cch ? (_cch > 0) : _fCaretNotAtBOL; } /* * CTxtSelection::LineLength() * * @mfunc * get # unselected chars on lines touched by current selection * * @rdesc * said number of chars */ LONG CTxtSelection::LineLength() const { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::LineLength"); _TEST_INVARIANT_ LONG cch; CLinePtr rp(_pdp); if (!_cch) // Insertion point { rp.RpSetCp(GetCp(), _fCaretNotAtBOL); cch = rp.GetAdjustedLineLength(); } else { LONG cpMin, cpMost, cchLast; GetRange(cpMin, cpMost); rp.RpSetCp(cpMin, FALSE); // Selections can't start at EOL cch = rp.RpGetIch(); rp.RpSetCp(cpMost, TRUE); // Selections can't end at BOL // now remove the trailing EOP (if it exists and isn't // already selected). cchLast = rp.GetAdjustedLineLength() - rp.RpGetIch(); if (cchLast > 0) { cch += cchLast; } } return cch; } /* * CTxtSelection::ShowSelection(fShow) * * @mfunc * Update, hide or show selection on screen * * @rdesc * TRUE iff selection was previously shown */ BOOL CTxtSelection::ShowSelection( BOOL fShow) //@parm TRUE for showing, FALSE for hiding { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::ShowSelection"); _TEST_INVARIANT_ const BOOL fShowPrev = _fShowSelection; const BOOL fInplaceActive = GetPed()->fInplaceActive(); LONG cpSelSave = _cpSel; LONG cchSelSave = _cchSel; // Sleep(1000); _fShowSelection = fShow; if (fShowPrev && !fShow) { if (cchSelSave) // Hide old selection { // Set up selection before telling the display to update _cpSel = 0; _cchSel = 0; if (fInplaceActive) { _pdp->InvertRange(cpSelSave, cchSelSave, selSetNormal); } } } else if (!fShowPrev && fShow) { if (_cch) // Show new selection { // Set up selection before telling the display to update _cpSel = GetCp(); _cchSel = _cch; if (fInplaceActive) { _pdp->InvertRange(GetCp(), _cch, selSetHiLite); } } } return fShowPrev; } /* * CTxtSelection::UpdateSelection() * * @mfunc * Updates selection on screen * * Note: * This method inverts the delta between old and new selections */ VOID CTxtSelection::UpdateSelection() { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::UpdateSelection"); _TEST_INVARIANT_ LONG cp = GetCp(); LONG cpNA = cp - _cch; LONG cpSelNA = _cpSel - _cchSel; LONG cpMin, cpMost, cpMinSel, cpMostSel; CObjectMgr *pobjmgr = NULL; LONG NumObjInSel = 0, NumObjInOldSel = 0; LONG cpSelSave = _cpSel; LONG cchSelSave = _cchSel; GetRange(cpMin, cpMost); //We need to know if there were objects is the previous and current //selections to determine how they should be selected. if (GetPed()->HasObjects()) { pobjmgr = GetPed()->GetObjectMgr(); if (pobjmgr) { CTxtRange tr(GetPed(), _cpSel, _cchSel); tr.GetRange(cpMinSel, cpMostSel); NumObjInSel = pobjmgr->CountObjectsInRange(cpMin, cpMost); NumObjInOldSel = pobjmgr->CountObjectsInRange(cpMinSel, cpMostSel); } } //If the old selection contained a single object and nothing else //we need to notify the object manager that this is no longer the //case if the selection is changing. if (NumObjInOldSel && (abs(_cchSel) == 1) && !(cpMin == cpMinSel && cpMost == cpMostSel)) { if (pobjmgr) { pobjmgr->HandleSingleSelect(GetPed(), cpMinSel, /* fHilite */ FALSE); } } // Update selection data before the invert so the selection can be // painted by the render _cpSel = GetCp(); _cchSel = _cch; if (_fShowSelection) { if (!_cch || !cchSelSave || // Old/new selection missing, cpMost < min(cpSelSave, cpSelNA) || // or new preceeds old, cpMin > max(cpSelSave, cpSelNA)) // or new follows old, so { // they don't intersect if (_cch) { _pdp->InvertRange(cp, _cch, selSetHiLite); } if (cchSelSave) { _pdp->InvertRange(cpSelSave, cchSelSave, selSetNormal); } } else { if (cpNA != cpSelNA) // Old & new dead ends differ { // Invert text between them _pdp->InvertRange(cpNA, cpNA - cpSelNA, selUpdateNormal); } if (cp != cpSelSave) // Old & new active ends differ { // Invert text between them _pdp->InvertRange(cp, cp - cpSelSave, selUpdateHiLite); } } } //If the new selection contains a single object and nothing else //we need to notify the object manager as long as it's not the same //object. if (NumObjInSel && (abs(_cch) == 1) && !(cpMin == cpMinSel && cpMost == cpMostSel)) { if (pobjmgr) { pobjmgr->HandleSingleSelect(GetPed(), cpMin, /* fHiLite */ TRUE); } } } /* * CTxtSelection::SetSelection(cpFirst, cpMost) * * @mfunc * Set selection between two cp's * * @devnote * <p cpFirst> and <p cpMost> must be greater than 0, but may extend * past the current max cp. In that case, the cp will be truncated to * the max cp (at the end of the text). */ VOID CTxtSelection::SetSelection( LONG cpMin, //@parm Start of selection and dead end LONG cpMost) //@parm End of selection and active end { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SetSelection"); _TEST_INVARIANT_ IUndoMgr *pundo = GetPed()->GetUndoMgr(); if (pundo) { pundo->StopGroupTyping(); } _fCaretNotAtBOL = FALSE; // Put caret for ambiguous cp at BOL Set(cpMost, cpMost - cpMin); // Set() validates cpMin, cpMost if (GetPed()->fInplaceActive()) { // Inplace active - update the selection now. Update(TRUE); } else { // Update the selection data used for screen display // so whenever we get displayed the selection will be // displayed. _cpSel = GetCp(); _cchSel = _cch; if (!GetPed()->fHideSelection()) { // Selection is not hidden so tell container to // update the display when it feels like. GetPed()->TxInvalidateRect(NULL, FALSE); GetPed()->TxUpdateWindow(); } } CancelModes(); // Cancel word selection mode } /* * CTxtSelection::PointInSel(pt, prcClient) * * @mfunc * Figures whether a given point is within the selection * * @rdesc * TRUE if point inside selection, FALSE otherwise */ BOOL CTxtSelection::PointInSel( const POINT pt, //@parm Point in containing window client coords const RECT *prcClient //@parm Client rectangle can be NULL if active ) const { LONG cp; LONG cpMin, cpMost; POINT temppt; CRchTxtPtr rtp(GetPed(), 0); TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::PointInSel"); _TEST_INVARIANT_ if (!_cch) // Degenerate range (no selection): { return FALSE; // mouse can't be in } cp = _pdp->CpFromPoint(pt, prcClient, NULL, NULL, FALSE); GetRange(cpMin, cpMost); // we have to test boundary cases separately--we want to make // sure the point is in the bounding box of the selection, but cp // from point will artificially extend that bounding box to half of // the next/previous character. Think of it this way, when you click // in the middle of a character, the insertion point has to go // somewhere to the left or the right. if (cp > cpMin && cp < cpMost) { return TRUE; } else if (cp == cpMin) { rtp.SetCp(cp); _pdp->PointFromTp(rtp, prcClient, FALSE, temppt, NULL, TA_TOP); if (pt.x >= temppt.x) { return TRUE; } } else if (cp == cpMost) { rtp.SetCp(cp); _pdp->PointFromTp(rtp, prcClient, TRUE, temppt, NULL, TA_TOP); if (pt.x <= temppt.x) { return TRUE; } } return FALSE; } ////////////////////////////////// Selection with the mouse /////////////////////////////////// /* * CTxtSelection::SetCaret(pt, fUpdate) * * @mfunc * Sets caret at a given point * * @devnote * In the plain-text case, placing the caret at the beginning of the * line following the final EOP requires some extra code, since the * underlying rich-text engine doesn't assign a line to a final EOP * (plain-text doesn't currently have the rich-text final EOP). We * handle this by checking to see if the count of lines times the * plain-text line height is below the actual y position. If so, we * move the cp to the end of the story. */ void CTxtSelection::SetCaret( const POINT pt, //@parm Point of click BOOL fUpdate) //@parm If TRUE, update the selection/caret { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SetCaret"); _TEST_INVARIANT_ LONG cp; RECT rcView; CLinePtr rp(_pdp); CRchTxtPtr rtp(GetPed()); LONG y; IUndoMgr *pundo = GetPed()->GetUndoMgr(); if (pundo) { pundo->StopGroupTyping(); } // Set caret at point if (_pdp->CpFromPoint(pt, NULL, &rtp, &rp, FALSE) >= 0) { // Set the selection to the correct location. If plain-text // multiline control, we need to check to see if pt.y is below // the last line of text. If so and if the text ends with an EOP, // we need to set the cp at the end of the story and set up to // display the caret at the beginning of the line below the last // line of text cp = rtp.GetCp(); if (!GetPed()->IsRich() && // Plain-text, GetPed()->TxGetMultiLine()) // multiline control { _pdp->GetViewRect(rcView, NULL); y = pt.y + _pdp->GetYScroll() - rcView.top; if (y > (LONG)rp.Count()*rp->_yHeight) // Below last line of { // text rtp.Advance(tomForward); // Move rtp to end of text if (rtp._rpTX.IsAfterEOP()) // If text ends with an { // EOP, set up to move cp = rtp.GetCp(); // selection there rp.AdvanceCp(-(LONG)rp.GetIch());// Set rp._ich = 0 to } // set _fCaretNotAtBOL } // = FALSE to display } // caret at next BOL Set(cp, 0); _fCaretNotAtBOL = rp.RpGetIch() != 0; // Caret OK at BOL if click if (fUpdate) { Update(TRUE); } UpdateForAutoWord(GetCp()); _SelMode = smNone; // Cancel word selection mode } } /* * CTxtSelection::SelectWord(pt) * * @mfunc * Select word around a given point */ void CTxtSelection::SelectWord( const POINT pt) //@parm Point of click { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SelectWord"); _TEST_INVARIANT_ // Get rp where the hit is if (_pdp->CpFromPoint(pt, NULL, this, NULL, FALSE) >= 0) { // Extend both active and dead ends on word boundaries _cch = 0; // Start with IP at pt SetExtend(FALSE); FindWordBreak(WB_MOVEWORDRIGHT); // Go to end of word SetExtend(TRUE); FindWordBreak(WB_MOVEWORDLEFT); // Extend to start of word GetRange(_cpAnchorMin, _cpAnchorMost); GetRange(_cpWordMin, _cpWordMost); if (!_fInAutoWordSel) { _SelMode = smWord; } // cpMost needs to be the active end if (_cch < 0) { FlipRange(); } Update(FALSE); } } /* * CTxtSelection::SelectLine(pt) * * @mfunc * Select entire line around a given point * and enter line selection mode */ void CTxtSelection::SelectLine( const POINT pt) //@parm Point of click { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SelectLine"); _TEST_INVARIANT_ CLinePtr rp(_pdp); // Get rp where the hit is if (_pdp->CpFromPoint(pt, NULL, this, &rp, FALSE) >= 0) { _cch = 0; // Start with insertion point at pt SetExtend(FALSE); Advance(-rp.RpGetIch()); // Go to SOL SetExtend(TRUE); Advance(rp->_cch); // Extend to EOL GetRange(_cpAnchorMin, _cpAnchorMost); _SelMode = smLine; Update(FALSE); } } /* * CTxtSelection::SelectPara(pt) * * @mfunc * Select paragraph around a given point * and enter paragraph selection mode * * @devnote * TKTK: May need to WaitForRecalc() in going forward */ void CTxtSelection::SelectPara( const POINT pt) //@parm Point of click { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SelectPara"); _TEST_INVARIANT_ CLinePtr rp(_pdp); // Get rp and selection active end where the hit is if (_pdp->CpFromPoint(pt, NULL, this, &rp, FALSE) >= 0) { SetExtend(FALSE); Advance(rp.FindParagraph(FALSE)); // Go to start of para SetExtend(TRUE); Advance(rp.FindParagraph(TRUE)); // Extend to end of para GetRange(_cpAnchorMin, _cpAnchorMost); _SelMode = smPara; Update(FALSE); } } /* * CTxtSelection::SelectAll() * * @mfunc * Select all text in story */ void CTxtSelection::SelectAll() { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SelectAll"); _TEST_INVARIANT_ IUndoMgr *pundo = GetPed()->GetUndoMgr(); if (pundo) { pundo->StopGroupTyping(); } LONG cchText = GetTextLength(); Set(cchText, cchText); Update(FALSE); } /* * CTxtSelection::ExtendSelection(pt) * * @mfunc * Extend/Shrink selection (moves active end) to given point */ void CTxtSelection::ExtendSelection( const POINT pt) //@parm Point to extend to { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::ExtendSelection"); _TEST_INVARIANT_ LONG cch; LONG cchPrev = _cch; LONG cp; LONG cpMin, cpMost; BOOL fAfterEOP; const BOOL fWasInAutoWordSel = _fInAutoWordSel; INT iDir; CTxtEdit *ped = _pdp->GetED(); CLinePtr rp(_pdp); CRchTxtPtr rtp(GetPed()); IUndoMgr *pundo = GetPed()->GetUndoMgr(); if (pundo) { pundo->StopGroupTyping(); } // Get rp and rtp at the point pt if (_pdp->CpFromPoint(pt, NULL, &rtp, &rp, TRUE) < 0) { return; } // If we are in word, line, or paragraph select mode, we need to make // sure the active end is correct. If we are extending backward from // the first Unit selected, we want the active end to be at cpMin. If // we are extending forward from the first Unit selected, we want the // active end to be at cpMost. if (_SelMode != smNone) { cch = _cpAnchorMost - _cpAnchorMin; GetRange(cpMin, cpMost); cp = rtp.GetCp(); if (cp <= cpMin && _cch > 0) // If active end changes, { Set(_cpAnchorMin, -cch); // select the original } // Unit (will be extended if (cp >= cpMost && _cch < 0) // below) { Set(_cpAnchorMost, cch); } } SetExtend(TRUE); cch = rp.RpGetIch(); if ((_SelMode > smWord) && // If in line or para select cch == (LONG)rp->_cch) // modes and pt at EOL, { // make sure we stay on that rtp.Advance(-cch); // line rp.RpAdvanceCp(-cch); cch = 0; } SetCp(rtp.GetCp()); // Move active end to pt // Caret OK at BOL _unless_ _fCaretNotAtBOL = _cch > 0; // forward selection // Now adjust selection if (_SelMode == smLine) // depending on mode { // Extend selection by line if (_cch >= 0) // Active end at cpMost { cch -= rp->_cch; // Setup to add chars to EOL } Advance(-cch); } else if (_SelMode == smPara) { Advance(rp.FindParagraph(_cch >= 0)); // Extend selection by para } else { // If the sign of _cch has changed this means that the direction // of the selection is changing and we want to reset the auto // selection information. if ((_cch ^ cchPrev) < 0) { _fAutoSelectAborted = FALSE; _cpWordMin = _cpAnchorMin; _cpWordMost = _cpAnchorMost; } cp = rtp.GetCp(); fAfterEOP = rtp._rpTX.IsAfterEOP(); _fInAutoWordSel = _SelMode != smWord && GetPed()->TxGetAutoWordSel() && !_fAutoSelectAborted && (cp < _cpWordMin || cp > _cpWordMost); if (_fInAutoWordSel && !fWasInAutoWordSel) { CTxtPtr txtptr(GetPed(), _cpAnchor); // Extend both ends dead to word boundaries ExtendToWordBreak(fAfterEOP, _cch < 0 ? WB_MOVEWORDLEFT : WB_MOVEWORDRIGHT); if (_cch < 0) { // Direction is left so update word border on left _cpWordPrev = _cpWordMin; _cpWordMin = GetCp(); } else { // Direction is right so update word border on right _cpWordPrev = _cpWordMost; _cpWordMost = GetCp(); } //If we are at the beginning of a word already, we don't //need to extend the selection in the other direction. if (!txtptr.IsAtBOWord()) { FlipRange(); // start extending from the anchor Advance(_cpAnchor - GetCp()); FindWordBreak(_cch < 0 ? WB_MOVEWORDLEFT : WB_MOVEWORDRIGHT); if (_cch > 0) { // Direction is right so update word border on right _cpWordMost = GetCp(); } else { // Direction is left so update word border on left _cpWordMin = GetCp(); } FlipRange(); } } else if (_fInAutoWordSel || _SelMode == smWord) { // Save direction iDir = cp <= _cpWordMin ? WB_MOVEWORDLEFT : WB_MOVEWORDRIGHT; // Extend selection by word if (_SelMode == smWord) { if (cp > _cpAnchorMost || cp < _cpAnchorMin) { FindWordBreak(iDir); } else { Set(_cpAnchorMin, _cpAnchorMin - _cpAnchorMost); } } else { ExtendToWordBreak(fAfterEOP, iDir); } if (_fInAutoWordSel) { if (WB_MOVEWORDLEFT == iDir) { // Direction is left so update word border on left _cpWordPrev = _cpWordMin; _cpWordMin = GetCp(); } else { // Direction is right so update word border on right _cpWordPrev = _cpWordMost; _cpWordMost = GetCp(); } } } else if (fWasInAutoWordSel) { // If we are in between where the previous word ended and // the cp we auto selected to, then we want to stay in // auto select mode. if (_cch < 0) { if (cp >= _cpWordMin && cp < _cpWordPrev) { // Set direction for end of word search iDir = WB_MOVEWORDLEFT; // Mark that we are still in auto select mode _fInAutoWordSel = TRUE; } } else if (cp <= _cpWordMost && cp >= _cpWordPrev) { // Mark that we are still in auto select mode _fInAutoWordSel = TRUE; // Set direction for end of word search iDir = WB_MOVEWORDRIGHT; } //We have to check to see if we are on the boundary between //words because we don't want to extend the selection until //we are actually beyond the current word. if (cp != _cpWordMost && cp != _cpWordMin) { if (_fInAutoWordSel) { // Auto selection still on so make sure we have the // entire word we are on selected ExtendToWordBreak(fAfterEOP, iDir); } else { // FUTURE: Word has a behavior where it extends the // selection one word at a time unless you back up // and then start extending the selection again, in // which case it extends one char at a time. We // follow this behavior. However, Word will resume // extending a word at a time if you continue extending // for several words. We just keep extending on char // at a time. We might want to change this sometime. _fAutoSelectAborted = TRUE; } } } if (_fAutoSelectAborted) { // If we are in the range of a word we previously selected // we want to leave that selected. If we have moved back // a word we want to pop back an entire word. Otherwise, // leave the cp were it is. if (_cch < 0) { if (cp > _cpWordMin && cp < _cpWordPrev) { // In the range leave the range at the beginning of the word ExtendToWordBreak(fAfterEOP, WB_MOVEWORDLEFT); } else if (cp >= _cpWordPrev) { AutoSelGoBackWord(&_cpWordMin, WB_MOVEWORDRIGHT, WB_MOVEWORDLEFT); } } else if (cp < _cpWordMost && cp >= _cpWordPrev) { // In the range leave the range at the beginning of the word ExtendToWordBreak(fAfterEOP, WB_MOVEWORDRIGHT); } else if (cp < _cpWordPrev) { AutoSelGoBackWord(&_cpWordMost, WB_MOVEWORDLEFT, WB_MOVEWORDRIGHT); } } } // Save the current state of the _fCaretNotAtBOL flag since it affects a // a number of places. BOOL fCaretNotAtBOLSave = _fCaretNotAtBOL; // Is the selection at the beginning of the line? if (rp.RpGetIch() == 0) { // REVIEW (murrays): presumably we don't need this since _fCaretNotAtBOL // is always FALSE at this point thanks to correcting a bug above. // Yes - then temporarily set the flag so that UpdateCaret will not // back up the cp to the end of the previous line. This backup has // the unfortunate effect of causing the the screen to go back and // forth between the end of the previous line and the beginning of // the line that the cp is on because the _xScroll is changed even // though the cp isn't and this change in turn affects the cp. _fCaretNotAtBOL = FALSE; } // Restore the flag to its original state. _fCaretNotAtBOL = fCaretNotAtBOLSave; // An OLE object cannot have an anchor point <b> inside </b> it, // but sometimes we'd like it to behave like a word. So, if // the direction changed, the object has to stay selected -- // this is the "right thing" (kind of word selection mode) // if we had something selected and the direction changed if (cchPrev && (_cch ^ cchPrev) < 0) { FlipRange(); // see if an object was selected on the other end BOOL fObjectWasSelected = (_cch > 0 ? _rpTX.GetChar() : _rpTX.GetPrevChar()) == WCH_EMBEDDING; // if it was, we want it to stay selected if (fObjectWasSelected) { Advance(_cch > 0 ? 1 : -1); } FlipRange(); } Update(TRUE); } /* * CTxtSelection::ExtendToWordBreak (fAfterEOP, iAction) * * @mfunc * Moves active end of selection to the word break in the direction * given by iDir unless fAfterEOP = TRUE. When this is TRUE, the * cursor just follows an EOP marker and selection should be suppressed. * Otherwise moving the cursor to the left of the left margin would * select the EOP on the line above, and moving the cursor to the * right of the right margin would select the first word in the line * below. */ void CTxtSelection::ExtendToWordBreak( BOOL fAfterEOP, //@parm Cursor is after an EOP INT iAction) //@parm Word break action (WB_MOVEWORDRIGHT/LEFT) { if (!fAfterEOP) { FindWordBreak(iAction); } } /* * CTxtSelection::CancelModes(fAutoWordSel) * * @mfunc * Cancel either all modes or Auto Select Word mode only */ void CTxtSelection::CancelModes( BOOL fAutoWordSel) //@parm TRUE cancels Auto Select Word mode only { // FALSE cancels word, line and para sel mode TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::CancelModes"); _TEST_INVARIANT_ if (fAutoWordSel) { if (_fInAutoWordSel) { _fInAutoWordSel = FALSE; _fAutoSelectAborted = FALSE; } } else { _SelMode = smNone; } } /////////////////////////////////// Keyboard movements //////////////////////////////////// /* * CTxtSelection::Left(fCtrl) * * @mfunc * do what cursor-keypad left-arrow key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * Left/Right-arrow IPs can go to within one character (treating CRLF * as a character) of EOL. They can never be at the actual EOL, so * _fCaretNotAtBOL is always FALSE for these cases. This includes * the case with a right-arrow collapsing a selection that goes to * the EOL, i.e, the caret ends up at the next BOL. Furthermore, * these cases don't care whether the initial caret position is at * the EOL or the BOL of the next line. All other cursor keypad * commands may care. * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Left( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Left"); _TEST_INVARIANT_ LONG cp; IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (!_fExtend && _cch) // Collapse selection to { // nearest whole Unit before if (fCtrl) // cpMin { Expander(tomWord, FALSE, NULL, &cp, NULL); } Collapser(tomStart); // Collapse to cpMin } else // Not collapsing selection { if (!GetCp()) // Already at beginning of { // story GetPed()->Sound(); return FALSE; } if (fCtrl) // WordLeft { FindWordBreak(WB_MOVEWORDLEFT); } else // CharLeft { BackupCRLF(); } } if (!_fExtend) // If no selection, { UpdateForAutoWord(GetCp()); // update autoword info } _fCaretNotAtBOL = FALSE; // Caret always OK at BOL Update(TRUE); return TRUE; } /* * CTxtSelection::Right(fCtrl) * * @mfunc * do what cursor-keypad right-arrow key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * Right-arrow selection can go to the EOL, but the cp of the other * end identifies whether the selection ends at the EOL or starts at * the beginning of the next line. Hence here and in general for * selections, _fCaretNotAtBOL is not needed to resolve EOL/BOL * ambiguities. It should be set to FALSE to get the correct * collapse character. See also comments for Left() above. * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Right( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Right"); _TEST_INVARIANT_ LONG cchText; LONG cp; IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (!_fExtend && _cch) // Collapse selection to { // nearest whole Unit after if (fCtrl) // cpMost { Expander(tomWord, FALSE, NULL, NULL, &cp); } Collapser(tomEnd); } else // Not collapsing selection { cchText = _fExtend ? GetTextLength() : GetAdjustedTextLength(); if (GetCp() >= cchText) // Already at end of story { GetPed()->Sound(); // Tell the user return FALSE; } if (fCtrl) // WordRight { FindWordBreak(WB_MOVEWORDRIGHT); } else // CharRight { AdvanceCRLF(); } } if (!_fExtend) // If no selection, update { UpdateForAutoWord(GetCp()); // autoword info } _fCaretNotAtBOL = _fExtend; // If extending to EOL, need Update(TRUE); // TRUE to get _xCaretReally return TRUE; // at EOL } /* * CTxtSelection::Up(fCtrl) * * @mfunc * do what cursor-keypad up-arrow key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * Up arrow doesn't go to EOL regardless of _xCaretPosition (stays * to left of EOL break character), so _fCaretNotAtBOL is always FALSE * for Up arrow. Ctrl-Up/Down arrows always end up at BOPs or the EOD. * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Up( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Up"); _TEST_INVARIANT_ LONG cchSave = _cch; // Save starting position for LONG cpSave = GetCp(); // change check BOOL fCollapse = _cch && !_fExtend; // Collapse nondegenerate sel BOOL fPTNotAtEnd; LONG ich; CLinePtr rp(_pdp); LONG xCaretReally = _xCaretReally; // Save desired caret x pos IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (fCollapse) // Collapse selection at cpMin { Collapser(tomTrue); _fCaretNotAtBOL = FALSE; // Selections can't begin at } // EOL rp.RpSetCp(GetCp(), _fCaretNotAtBOL); // Initialize line ptr if (fCtrl) // Move to beginning of para { if (!fCollapse && // If no selection collapsed rp > 0 && !rp.RpGetIch()) // and are at BOL, { // backup to prev BOL to make rp--; // sure we move to prev. para Advance(-(LONG)rp->_cch); } Advance(rp.FindParagraph(FALSE)); // Go to beginning of para _fCaretNotAtBOL = FALSE; // Caret always OK at BOL } else // Move up a line { // If on first line, can't go fPTNotAtEnd = !CheckPlainTextFinalEOP(); if (rp <= 0 && fPTNotAtEnd) // (Don't use !rp, which means { // rp that's out of range) if (!_fExtend) // &&_pdp->GetYScroll()) // up { UpdateCaret(TRUE); // Be sure caret in view } } else { ich = 0; if (fPTNotAtEnd) { ich = rp.RpGetIch(); rp--; } Advance(-(LONG)(rp->_cch + ich)); // Move to previous BOL if (!SetXPosition(xCaretReally, rp)) // Set this cp corresponding { return FALSE; // to xCaretReally } } // here, but agree on Down() } if (GetCp() == cpSave && _cch == cchSave) { // Continue to select to the beginning of the first line // This is what 1.0 is doing if (_fExtend) { return Home(fCtrl); } GetPed()->Sound(); // Nothing changed, so beep return FALSE; } Update(TRUE); // Update and then restore if (!_cch && !fCtrl) // _xCaretReally conditionally { _xCaretReally = xCaretReally; // Need to use _cch instead of } // cchSave in case of collapse return TRUE; } /* * CTxtSelection::Down(fCtrl) * * @mfunc * do what cursor-keypad down-arrow key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * Down arrow can go to the EOL if the _xCaretPosition (set by * horizontal motions) is past the end of the line, so * _fCaretNotAtBOL needs to be TRUE for this case. * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Down( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Down"); _TEST_INVARIANT_ LONG cch; LONG cchSave = _cch; // Save starting position for LONG cpSave = GetCp(); // change check BOOL fCollapse = _cch && !_fExtend; // Collapse nondegenerate sel CLinePtr rp(_pdp); LONG xCaretReally = _xCaretReally; // Save _xCaretReally IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (fCollapse) // Collapse at cpMost { Collapser(tomEnd); _fCaretNotAtBOL = TRUE; // Selections can't end at BOL } rp.RpSetCp(GetCp(), _fCaretNotAtBOL); if (fCtrl) // Move to next para { Advance(rp.FindParagraph(TRUE)); // Go to end of para _fCaretNotAtBOL = FALSE; // Next para is never at EOL } else if (_pdp->WaitForRecalcIli(rp + 1)) // Go to next line { Advance(rp.GetCchLeft()); // Advance selection to end rp++; // of current line if (!SetXPosition(xCaretReally, rp)) // Set *this to cp <--> x { return FALSE; // (unless can't create me) } } else if (!_fExtend) // No more lines to pass // && _pdp->GetYScroll() + _pdp->GetViewHeight() < _pdp->GetHeight()) { if (!GetPed()->IsRich() // Plain-text, && GetPed()->TxGetMultiLine() // multiline control && !_fCaretNotAtBOL) // with caret OK at BOL { cch = Advance(rp.GetCchLeft()); // Advance selection to end if (!_rpTX.IsAfterEOP()) // If control doesn't end { Advance(-cch); // with EOP, go back } } UpdateCaret(TRUE); // Be sure caret in view } if (GetCp() == cpSave && _cch == cchSave) { // Continue to select to the end of the lastline // This is what 1.0 is doing. if (_fExtend) { return End(fCtrl); } GetPed()->Sound(); // Nothing changed, so beep return FALSE; } Update(TRUE); // Update and then if (!_cch && !fCtrl) // restore _xCaretReally { _xCaretReally = xCaretReally; // Need to use _cch instead of } return TRUE; // cchSave in case of collapse } /* * CTxtSelection::SetXPosition(xCaret, rp) * * @mfunc * Put this text ptr at cp nearest to xCaret. If xCaret is in right * margin, we put caret either at EOL (for lines with no para mark), * or just before para mark * * @rdesc * TRUE iff could create measurer */ BOOL CTxtSelection::SetXPosition( LONG xCaret, //@parm Desired horizontal coordinate CLinePtr &rp) //@parm Line ptr identifying line to check { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SetXPosition"); _TEST_INVARIANT_ LONG cch; CMeasurer me(_pdp, *this); cch = rp->CchFromXpos(me, xCaret, NULL); if (!_fExtend && cch == (LONG)rp->_cch && // Not extending, at EOL, rp->_cchEOP) // and have EOP: { // backup before EOP cch += me._rpTX.BackupCpCRLF(); // Note: me._rpCF/_rpPF } // are now inconsistent SetCp(me.GetCp()); // but doesn't matter since _fCaretNotAtBOL = cch != 0; // me.GetCp() doesn't care return TRUE; } /* * CTxtSelection::GetXCaretReally() * * @mfunc * Get _xCaretReally - horizontal scrolling + left margin * * @rdesc * x caret really */ LONG CTxtSelection::GetXCaretReally() { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::GetXCaretReally"); _TEST_INVARIANT_ RECT rcView; _pdp->GetViewRect(rcView); return _xCaretReally - _pdp->GetXScroll() + rcView.left; } /* * CTxtSelection::Home(fCtrl) * * @mfunc * do what cursor-keypad Home key is supposed to do * * @rdesc * TRUE iff movement occurred * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Home( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Home"); _TEST_INVARIANT_ const LONG cchSave = _cch; const LONG cpSave = GetCp(); IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (fCtrl) // Move to start of document { SetCp(0); } else { CLinePtr rp(_pdp); if (_cch && !_fExtend) // Collapse at cpMin { Collapser(tomStart); _fCaretNotAtBOL = FALSE; // Selections can't start at } // EOL rp.RpSetCp(GetCp(), _fCaretNotAtBOL); // Define line ptr for Advance(-rp.RpGetIch()); // current state. Now BOL } _fCaretNotAtBOL = FALSE; // Caret always goes to BOL if (GetCp() == cpSave && _cch == cchSave) // Beep if no change { GetPed()->Sound(); return FALSE; } Update(TRUE); #if 0 // Scroll horizontally to 0 if caret not visible // TKTK? done by Update()? if (fCtrl && !_pdp->GetXScroll() && _xCaret - _pdp->GetViewLeft() + _pdp->GetXScroll() < _pdp->GetViewWidth()) { _pdp->ScrollView(0, _pdp->GetYScroll(), FALSE); } #endif return TRUE; } /* * CTxtSelection::End(fCtrl) * * @mfunc * do what cursor-keypad End key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * On lines without paragraph marks (EOP), End can go all the way * to the EOL. Since this character position (cp) is the same as * that for the start of the next line, we need _fCaretNotAtBOL to * distinguish between the two possible caret positions. * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::End( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::End"); _TEST_INVARIANT_ LONG cch; const LONG cchSave = _cch; const LONG cpSave = GetCp(); CLinePtr rp(_pdp); IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (fCtrl) // Move to end of document { SetCp(GetTextLength()); _fCaretNotAtBOL = FALSE; goto Exit; } else if (!_fExtend && _cch) // Collapse at cpMost { Collapser(tomEnd); _fCaretNotAtBOL = TRUE; // Selections can't end at BOL } rp.RpSetCp(GetCp(), _fCaretNotAtBOL); // Initialize line ptr cch = rp->_cch; // Default target pos in line Advance(cch - rp.RpGetIch()); // Move active end to EOL if (!_fExtend && rp->_cchEOP && _rpTX.IsAfterEOP()) // Not extending and { // have EOP: cch += BackupCRLF(); // backup before EOP } _fCaretNotAtBOL = cch != 0; // Decide ambiguous caret pos // by whether at BOL Exit: if (GetCp() == cpSave && _cch == cchSave) { GetPed()->Sound(); // No change, so Beep return FALSE; } Update(TRUE); return TRUE; } /* * CTxtSelection::PageUp(fCtrl) * * @mfunc * do what cursor-keypad PgUp key is supposed to do * * @rdesc * TRUE iff movement occurred * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::PageUp( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::PageUp"); _TEST_INVARIANT_ const LONG cchSave = _cch; const LONG cpSave = GetCp(); LONG xCaretReally = _xCaretReally; IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (_cch && !_fExtend) // Collapse selection { Collapser(tomStart); _fCaretNotAtBOL = FALSE; } if (fCtrl) // Ctrl-PgUp: move to top { // of visible view for SetCp(GetPed()->TxGetMultiLine() // multiline but top of ? _pdp->GetFirstVisibleCp() // text for SL : 0); _fCaretNotAtBOL = FALSE; } else if (_pdp->GetFirstVisibleCp() == 0) // PgUp in top Pg: move to { // start of document SetCp(0); _fCaretNotAtBOL = FALSE; } else // PgUp with scrolling to go { // Scroll up one windowful ScrollWindowful(SB_PAGEUP); // leaving caret at same // position in window } if (GetCp() == cpSave && _cch == cchSave) // Beep if no change { GetPed()->Sound(); return FALSE; } Update(TRUE); if (GetCp()) // Maintain x offset on page { _xCaretReally = xCaretReally; // up/down } return TRUE; } /* * CTxtSelection::PageDown(fCtrl) * * @mfunc * do what cursor-keypad PgDn key is supposed to do * * @rdesc * TRUE iff movement occurred * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::PageDown( BOOL fCtrl) //@parm TRUE iff Ctrl key is pressed (or being simulated) { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::PageDown"); _TEST_INVARIANT_ const LONG cchSave = _cch; LONG cpMostVisible; const LONG cpSave = GetCp(); POINT pt; CLinePtr rp(_pdp); LONG xCaretReally = _xCaretReally; IUndoMgr *pundo = GetPed()->GetUndoMgr(); CancelModes(); if (pundo) { pundo->StopGroupTyping(); } if (_cch && !_fExtend) // Collapse selection { Collapser(tomStart); _fCaretNotAtBOL = TRUE; } _pdp->GetCliVisible(&cpMostVisible, fCtrl); if (fCtrl) // Move to end of last { // entirely visible line RECT rcView; SetCp(cpMostVisible); if (_pdp->PointFromTp(*this, NULL, TRUE, pt, &rp, TA_TOP) < 0) { return FALSE; } _fCaretNotAtBOL = TRUE; _pdp->GetViewRect(rcView); if (rp > 0 && pt.y + rp->_yHeight > rcView.bottom) { Advance(-(LONG)rp->_cch); rp--; } if (!_fExtend && !rp.GetCchLeft() && rp->_cchEOP) { BackupCRLF(); // After backing up over EOP, _fCaretNotAtBOL = FALSE; // caret can't be at EOL } } else if (cpMostVisible == (LONG)GetTextLength()) { // Move to end of text SetCp(GetTextLength()); _fCaretNotAtBOL = !_rpTX.IsAfterEOP(); } else { if (!ScrollWindowful(SB_PAGEDOWN)) // Scroll down 1 windowful { return FALSE; } } if (GetCp() == cpSave && _cch == cchSave) // Beep if no change { GetPed()->Sound(); return FALSE; } Update(TRUE); _xCaretReally = xCaretReally; return TRUE; } /* * CTxtSelection::ScrollWindowful(wparam) * * @mfunc * Sroll up or down a windowful * * @rdesc * TRUE iff movement occurred */ BOOL CTxtSelection::ScrollWindowful( WPARAM wparam) //@parm SB_PAGEDOWN or SB_PAGEUP { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::ScrollWindowful"); // Scroll windowful _TEST_INVARIANT_ POINT pt; // leaving caret at same CLinePtr rp(_pdp); // point on screen LONG cpFirstVisible = _pdp->GetFirstVisibleCp(); LONG cpLastVisible; LONG cch; LONG cpNew; LONG cpMin; LONG cpMost; GetRange(cpMin, cpMost); // Get last character in the view _pdp->GetCliVisible(&cpLastVisible, TRUE); // Is the current selection contained entirely in the visible area of the // control? if ((cpMin < cpFirstVisible) || (cpMost > cpLastVisible)) { // Not in the view - we need to calculate a new range for the selection // Assume insertion point cch = 0; // Make first visible the active end cpNew = cpFirstVisible; // Set correct character count for new selection if (SB_PAGEDOWN == wparam) { // Get last visible at the beginning of the line if (_cch != 0) { cch = cpNew - cpMin; } } else { // SB_PAGEUP if (_cch != 0) { cch = cpFirstVisible - cpMost; } } // Update caret Set(cpNew, cch); // The real caret postion is now at the beginning of the line. _xCaretReally = 0; } if (_pdp->PointFromTp(*this, NULL, _fCaretNotAtBOL, pt, &rp, TA_TOP) < 0) { return FALSE; } // The point is visible so use that pt.x = _xCaretReally; pt.y += rp->_yHeight / 2; _pdp->VScroll(wparam, 0); if (_fExtend) { ExtendSelection(pt); } else { SetCaret(pt, FALSE); } return TRUE; } ///////////////////////// Keyboard support by jonmat ////////////////////////////// /* * CTxtSelection::CheckChangeKeyboardLayout ( BOOL fChangedFont ) * * @mfunc * Change keyboard for new font, or font at new character position. * @comm * Using only the currently loaded KBs, locate one that will support * the insertion points font. This is called anytime a character format * change occurs, or the insert font (caret position) changes. * @devnote * The current KB is preferred. If a previous association * was made, see if the KB is still loaded in the system and if so use * it. Otherwise, locate a suitable KB, preferring KB's that have * the same charset ID as their default, preferred charset. If no match * can be made then nothing changes. * * This routine is only useful on Windows 95. */ void CTxtSelection::CheckChangeKeyboardLayout( BOOL fChangedFont) // @parm TRUE if charformat has changed. { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::CheckChangeKeyboardLayout"); #ifndef MACPORT #define MAX_HKLS 256 // It will be awhile // before we have more KBs CTxtEdit *const ped = GetPed(); // Document context. INT i, totalLayouts, // For matching KBs. iBestLayout = -1; WORD preferredKB; // LCID of preferred KB. HKL hklList[MAX_HKLS]; // Currently loaded KBs. const CCharFormat *pcf; // Current font. CHARSETINFO csi; // Font's CodePage bits. AssertSz(ped, "no ped?"); // hey now! if (!fHaveNLSProcs || // EXIT if not running W95. !ped || !ped->IsRich() || !ped->_fFocus || // EXIT if no ped or focus or !ped->IsAutoKeyboard()) // auto keyboard is turn off { return; } pcf = ped->GetCharFormat(_iFormat); // Get insert font's data hklList[0] = pGetKeyboardLayout(0); // Current hkl preferred? preferredKB = fc().GetPreferredKB(pcf->bCharSet); if (preferredKB != LOWORD(hklList[0])) // Not correct KB? { // Get loaded HKLs. totalLayouts = 1 + pGetKeyboardLayoutList(MAX_HKLS, &hklList[1]); // Know which KB? if (preferredKB) // then locate it. { // Sequential match because for (i = 1; i < totalLayouts; i++) // HKL may be unloaded. { // Match LCIDs. if (preferredKB == LOWORD(hklList[i])) { iBestLayout = i; break; // Matched it. } } if (i >= totalLayouts) // Old KB is missing. { // Reset to locate new KB. fc().SetPreferredKB(pcf->bCharSet, 0); } } if (iBestLayout < 0) // Attempt to find new KB. { for (i = 0; i < totalLayouts; i++) { pTranslateCharsetInfo( // Get KB's charset. (DWORD *) ConvertLanguageIDtoCodePage(LOWORD(hklList[iBestLayout])), &csi, TCI_SRCCODEPAGE); if (csi.ciCharset == pcf->bCharSet) // If charset IDs match? { iBestLayout = i; break; // then this KB is best. } } if (iBestLayout >= 0) // Bind new KB. { fChangedFont = TRUE; fc().SetPreferredKB(pcf->bCharSet, LOWORD(hklList[iBestLayout])); } } if (fChangedFont && iBestLayout >= 0) // Bind font. { ICharFormatCache *pCF; if (SUCCEEDED(GetCharFormatCache(&pCF))) { pCF->AddRefFormat(_iFormat); fc().SetPreferredFont( LOWORD(hklList[iBestLayout]), _iFormat); } } if (iBestLayout > 0) // If == 0 then { // it's already active. // Activate KB. ActivateKeyboardLayout(hklList[iBestLayout], 0); } } #endif // MACPORT -- the mac needs its own code. } /* * CTxtSelection::CheckChangeFont ( CTxtEdit * const ped, const WORD lcID ) * * @mfunc * Change font for new keyboard layout. * @comm * If no previous preferred font has been associated with this KB, then * locate a font in the document suitable for this KB. * @devnote * This routine is called via WM_INPUTLANGCHANGEREQUEST message * (a keyboard layout switch). This routine can also be called * from WM_INPUTLANGCHANGE, but we are called more, and so this * is less efficient. * * Exact match is done via charset ID bitmask. If a match was previously * made, use it. A user can force the insertion font to be associated * to a keyboard if the control key is held through the KB changing * process. The association is broken when another KB associates to * the font. If no match can be made then nothing changes. * * This routine is only useful on Windows 95. * */ void CTxtSelection::CheckChangeFont( CTxtEdit *const ped, // @parm Document context. const WORD lcID) // @parm LCID from WM_ message. { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::CheckChangeFont"); #ifndef MACPORT #define MAX_RUNTOSEARCH (256L) LOCALESIGNATURE ls, curr_ls; // KB's code page bits. CCharFormat cf, // For creating new font. currCF; // For searching CHARSETINFO csi; // with code page bits. LONG iFormat, iBestFormat = -1; // Loop support. INT i; BOOL fLastTime; // Loop support. BOOL fSetPreferred = FALSE; HKL currHKL; // current KB; BOOL fLookUpFaceName = FALSE; // when picking a new font. ICharFormatCache *pCF; AssertSz(ped, "No ped?"); if (!fHaveNLSProcs || !ped->IsRich() || !ped->IsAutoFont()) // EXIT if not running W95. { return; // EXIT if auto font is turn off } if (FAILED(GetCharFormatCache(&pCF))) // Get CharFormat Cache. { return; } cf.InitDefault(0); // BUGBUG: We really want the key state of the current event. BOOL fReassign = GetAsyncKeyState(VK_CONTROL) < 0; // Is user holding CTRL? currHKL = pGetKeyboardLayout(0); ped->GetCharFormat(_iFormat)->Get(&currCF); GetLocaleInfoA(lcID, LOCALE_FONTSIGNATURE, (char *) &ls, sizeof(ls)); if (fReassign) // Force font/KB assoc. { // If font supports KB // in any way, // Note: test Unicode bits. GetLocaleInfoA(fc().GetPreferredKB(currCF.bCharSet), LOCALE_FONTSIGNATURE, (char *) &curr_ls, sizeof(ls)); if (CountMatchingBits(curr_ls.lsUsb, ls.lsUsb, 4)) { // Break old font/KB assoc. fc().SetPreferredFont(fc().GetPreferredKB(currCF.bCharSet), -1); // Bind KB and font. fc().SetPreferredKB(currCF.bCharSet, lcID); pCF->AddRefFormat(_iFormat); fc().SetPreferredFont(lcID, _iFormat); } } else // Lookup preferred font. { // Attempt to Find new { // preferred font. CFormatRunPtr rp(_rpCF); // Nondegenerate range fLastTime = TRUE; if (_rpCF.IsValid()) // If doc has cf runs. { fLastTime = FALSE; rp.AdjustBackward(); } pTranslateCharsetInfo( // charset. (DWORD *) ConvertLanguageIDtoCodePage(lcID), &csi, TCI_SRCCODEPAGE); iFormat = _iFormat; // Search _iFormat, // then backwards. i = MAX_RUNTOSEARCH; // Don't be searching for while (1) // years... { // Get code page bits. ped->GetCharFormat(iFormat)->Get(&cf); if (csi.ciCharset == cf.bCharSet) // Equal charset ids? { fSetPreferred = TRUE; break; } if (fLastTime) // Done searching? { break; } iFormat = rp.GetFormat(); // Keep searching backward. fLastTime = !rp.PrevRun() && i--; } if (!fSetPreferred && _rpCF.IsValid()) // Try searching forward. { rp = _rpCF; rp.AdjustBackward(); i = MAX_RUNTOSEARCH; // Don't be searching for while (i-- && rp.NextRun()) // years... { iFormat = rp.GetFormat(); // Get code page bits. ped->GetCharFormat(iFormat)->Get(&cf); // Equal charset ids? if (csi.ciCharset == cf.bCharSet) { fSetPreferred = TRUE; break; } } } if (fSetPreferred) { pCF->AddRefFormat(iFormat); } } if (!fSetPreferred) { iFormat = fc().GetPreferredFont(lcID); // Set preferred if usable. if (iFormat >= 0) { fSetPreferred = TRUE; } } if (fSetPreferred) // Found existing doc font. { // Bind KB and font. // This is redundent if ed.IsAutoKeyboard() == TRUE. pCF->AddRefFormat(_iFormat); fc().SetPreferredFont(LOWORD(currHKL), _iFormat); fc().SetPreferredKB(cf.bCharSet, lcID); fc().SetPreferredFont(lcID, iFormat); if (_iFormat != iFormat) { Set_iCF(iFormat); ped->GetCallMgr()->SetSelectionChanged(); } return; } // Still don't have a font? else // For FE, use hard coded defaults. { // else get charset right. // no assoication found, try FE default font WORD CurrentCodePage = ConvertLanguageIDtoCodePage(lcID); LPTSTR lpszFaceName = NULL; BYTE bCharSet; BYTE bPitchAndFamily; switch (CurrentCodePage) { // FE hard codes from Word. case _JAPAN_CP: bCharSet = SHIFTJIS_CHARSET; lpszFaceName = lpJapanFontName; bPitchAndFamily = 17; break; case _KOREAN_CP: bCharSet = HANGEUL_CHARSET; lpszFaceName = lpKoreanFontName; bPitchAndFamily = 49; break; case _CHINESE_TRAD_CP: bCharSet = CHINESEBIG5_CHARSET; lpszFaceName = lpTChineseFontName; bPitchAndFamily = 54; break; case _CHINESE_SIM_CP: bCharSet = GB2312_CHARSET; lpszFaceName = lpSChineseFontName; bPitchAndFamily = 54; break; default: // Use translate to get pTranslateCharsetInfo( // charset. (DWORD *) CurrentCodePage, &csi, TCI_SRCCODEPAGE); bCharSet = csi.ciCharset; bPitchAndFamily = currCF.bPitchAndFamily; lpszFaceName = currCF.szFaceName; fLookUpFaceName = TRUE; // Get Font's real name. break; } Assert(lpszFaceName); fSetPreferred = TRUE; cf.bPitchAndFamily = bPitchAndFamily; cf.bCharSet = (BYTE) bCharSet; _tcscpy(cf.szFaceName, lpszFaceName); } Assert(fSetPreferred); // one way or another... // Instantiate new format { // and update _iFormat. { cf.dwEffects = currCF.dwEffects; cf.yHeight = currCF.yHeight; cf.yOffset = currCF.yOffset; cf.crTextColor = currCF.crTextColor; cf.dwMask = currCF.dwMask; cf.wWeight = currCF.wWeight; cf.sSpacing = currCF.sSpacing; cf.crBackColor = currCF.crBackColor; cf.sStyle = currCF.sStyle; cf.wKerning = currCF.wKerning; cf.bUnderlineType = currCF.bUnderlineType; cf.bAnimation = currCF.bAnimation; cf.bRevAuthor = currCF.bRevAuthor; // If we relied on GDI to match a font, get the font's real name... if (fLookUpFaceName) { const CDevDesc *pdd = _pdp->GetDdRender(); HDC hdc; CCcs *pccs; HFONT hfontOld; OUTLINETEXTMETRICA *potm; CTempBuf mem; UINT otmSize; hdc = pdd->GetDC(); // Select logfont into DC, if (hdc) // for OutlineTextMetrics. { pccs = fc().GetCcs(hdc, &cf, _pdp->GetZoomNumerator(), _pdp->GetZoomDenominator(), GetDeviceCaps(hdc, LOGPIXELSY)); if (pccs) { hfontOld = SelectFont(hdc, pccs->_hfont); if (otmSize = ::GetOutlineTextMetricsA(hdc, 0, NULL)) { potm = (OUTLINETEXTMETRICA *) mem.GetBuf(otmSize); if (NULL != potm) { ::GetOutlineTextMetricsA(hdc, otmSize, potm); CStrInW strinw(&((CHAR *)(potm))[ BYTE(potm->otmpFaceName)]); cf.bPitchAndFamily = potm->otmTextMetrics.tmPitchAndFamily; cf.bCharSet = (BYTE) potm->otmTextMetrics.tmCharSet; _tcscpy(cf.szFaceName, (WCHAR *)strinw); } } SelectFont(hdc, hfontOld); pccs->Release(); } pdd->ReleaseDC(hdc); } } if (SUCCEEDED(pCF->Cache(&cf, &iFormat))) { // This is redundent if ed.IsAutoKeyboard() == TRUE. pCF->AddRefFormat(_iFormat); fc().SetPreferredFont(LOWORD(currHKL), _iFormat); fc().SetPreferredKB(cf.bCharSet, lcID); pCF->AddRefFormat(iFormat); fc().SetPreferredFont(lcID, iFormat); pCF->ReleaseFormat(_iFormat); _iFormat = iFormat; ped->GetCallMgr()->SetSelectionChanged(); } } } } #endif // MACPORT -- the mac needs its own code. } //////////////////////////// PutChar, Delete, Replace ////////////////////////////////// /* * CTxtSelection::PutChar(ch, fOver, publdr) * * @mfunc * Insert or overtype a character * * @rdesc * TRUE if successful */ BOOL CTxtSelection::PutChar( TCHAR ch, //@parm Char to put BOOL fOver, //@parm TRUE if overtype mode IUndoBuilder *publdr) //@parm If non-NULL, where to put anti-events { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::PutChar"); _TEST_INVARIANT_ // EOPs might be entered by ITextSelection::TypeText() if (IsEOP(ch)) { if (!GetPed()->TxGetMultiLine()) // EOP isn't allowed in { return FALSE; // single line controls } _fExtend = ch == VT ? TRUE : FALSE; // VT is for Shift-Enter return InsertEOP(publdr); // This code treats FF as } // ordinary CR if (publdr) { publdr->SetNameID(UID_TYPING); publdr->StartGroupTyping(); } if (!CheckTextLength(1)) // Return if we can't { return FALSE; // add even 1 more char } // The following if statement implements Word's "Smart Quote" feature. // To build this in, we still need an API to turn it on and off. This // could be EM_SETSMARTQUOTES with wparam turning the feature on or off. // murrays. NB: this needs localization for French, German, and many // other languages (unless system can provide open/close chars given // an LCID). /* if(ch == '\'' || ch == '"') // Smart quotes { LONG cp = GetCpMin(); // Open vs close depends CTxtPtr tp(GetPed(), cp - 1); // on char preceding // selection cpMin ch = (ch == '"') ? RDBLQUOTE : RQUOTE; // Default close quote // or apostrophe. If at if(!cp || IsWhiteSpace(tp.GetChar())) // BOStory or preceded ch--; // by whitespace, use } // open quote/apos */ SetExtend(TRUE); // Tell Advance() to if (fOver) // select chars { // If nothing selected and if (!_cch && !_rpTX.IsAtEOP()) // not at EOP char, try { // to select char at IP LONG iFormatSave = Get_iCF(); // Remember char's format Advance(1); ReplaceRange(0, NULL, publdr, SELRR_REMEMBERENDIP); // Delete this character. ReleaseFormats(_iFormat, -1); _iFormat = iFormatSave; // Restore char's format. } } else if (_SelMode == smWord && ch != TAB && _cch) // Replace word selection { // Leave word break chars CTxtPtr tp(_rpTX); // at end of selection Assert(_cch > 0); tp.AdvanceCp(-1); if (tp.GetCp() && tp.FindWordBreak(WB_ISDELIMITER)) // Delimeter at sel end { FindWordBreak(WB_LEFTBREAK); // Backspace over it, etc. } } _fIsChar = TRUE; // Give info to UpdateView _fIsWhiteChar = !!(GetPed()->_pfnWB(&ch, 0, // to avoid some flashies sizeof(ch), WB_CLASSIFY) & WBF_ISWHITE); _fIsTabChar = (ch == TAB); AdjustEndEOP(NEWCHARS); ReplaceRange(1, &ch, publdr, SELRR_REMEMBERRANGE); _fIsChar = FALSE; CheckUpdateWindow(); // Need to update display // for pending chars. return TRUE; } /* * CTxtSelection::SetIsChar(BOOL f) * * @mfunc * _fIsChar prevents replace range from resetting the * update window flag. This function allows clients, * like IME, to control the state of this flag. * */ VOID CTxtSelection::SetIsChar(BOOL f) { _fIsChar = f; } /* * CTxtSelection::CheckUpdateWindow() * * @mfunc * If it's time to update the window, * after pending-typed characters, * do so now. This is needed because * WM_PAINT has a lower priority than * WM_CHAR. * */ VOID CTxtSelection::CheckUpdateWindow() { DWORD ticks = GetTickCount(); DWORD delta = ticks - _ticksPending; if (0 == _ticksPending) { _ticksPending = ticks; } else if (delta >= ticksPendingUpdate) { GetPed()->TxUpdateWindow(); } } /* * CTxtSelection::InsertEOP(publdr) * * @mfunc * Insert EOP character(s) * * @rdesc * TRUE if successful */ BOOL CTxtSelection::InsertEOP( IUndoBuilder *publdr) //@parm If non-NULL, where to put anti-events { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::InsertEOP"); _TEST_INVARIANT_ LONG cchEOP = GetPed()->Get10Mode() ? 2 : 1; BOOL fResult = FALSE; LONG iFormatSave; const CParaFormat *pPF = GetPF(); // Get paragraph format if (publdr) { publdr->StartGroupTyping(); publdr->SetNameID(UID_TYPING); } if (CheckTextLength(cchEOP)) // If cchEOP chars can fit... { iFormatSave = Get_iCF(); // Save CharFormat before EOP // Get_iCF() does AddRefFormat() if (pPF->wNumbering == PFN_BULLET) // Bullet paragraph: EOP has { // desired bullet CharFormat CFormatRunPtr rpCF(_rpCF); // Get run pointers for locating CTxtPtr rpTX(_rpTX); // EOP CharFormat rpCF.AdvanceCp(rpTX.FindEOP(tomForward)); rpCF.AdjustBackward(); Set_iCF(rpCF.GetFormat()); // Set _iFormat to EOP CharFormat } // Put in approriate EOP mark fResult = ReplaceRange(cchEOP, // If Shift-Enter, insert VT _fExtend && IsRich() // Else CRLF or CR ? TEXT("\v") : szCRLF, publdr, SELRR_REMEMBERRANGE); Set_iCF(iFormatSave); // Restore _iFormat if changed ReleaseFormats(iFormatSave, -1); // Release iFormatSave } return fResult; } /* * CTxtSelection::Delete(fCtrl, publdr) * * @mfunc * Delete the selection. If fCtrl is true, this method deletes from * min of selection to end of word * * @rdesc * TRUE if successful */ BOOL CTxtSelection::Delete( DWORD fCtrl, //@parm If TRUE, Ctrl key depressed IUndoBuilder *publdr) //@parm if non-NULL, where to put anti-events { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Delete"); _TEST_INVARIANT_ SELRR mode = SELRR_REMEMBERRANGE; AssertSz(!GetPed()->TxGetReadOnly(), "CTxtSelection::Delete(): read only"); if (publdr) { publdr->StopGroupTyping(); publdr->SetNameID(UID_DELETE); } SetExtend(TRUE); // Setup to change selection if (fCtrl) { // Delete to word end from cpMin Collapser(tomStart); // (won't necessarily repaint, FindWordBreak(WB_MOVEWORDRIGHT); // since won't delete it) } if (!_cch) // No selection { mode = SELRR_REMEMBERCPMIN; if (!AdvanceCRLF()) // Try to select char at IP { GetPed()->Sound(); // End of text, nothing to delete return FALSE; } } AdjustEndEOP(NONEWCHARS); ReplaceRange(0, NULL, publdr, mode); // Delete selection return TRUE; } /* * CTxtSelection::BackSpace(fCtrl, publdr) * * @mfunc * do what keyboard BackSpace key is supposed to do * * @rdesc * TRUE iff movement occurred * * @comm * This routine should probably use the Move methods, i.e., it's * logical, not directional * * @devnote * _fExtend is TRUE iff Shift key is pressed or being simulated */ BOOL CTxtSelection::Backspace( BOOL fCtrl, //@parm TRUE iff Ctrl key is pressed (or being simulated) IUndoBuilder *publdr) //@parm If not-NULL, where to put the antievents { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::Backspace"); _TEST_INVARIANT_ SELRR mode = SELRR_REMEMBERRANGE; AssertSz(!GetPed()->TxGetReadOnly(), "CTxtSelection::Backspace(): read only"); _fCaretNotAtBOL = FALSE; if (publdr) { publdr->SetNameID(UID_TYPING); if (_cch || fCtrl) { publdr->StopGroupTyping(); } } SetExtend(TRUE); // Set up to extend range if (fCtrl) // Delete word left { if (!GetCpMin()) // Beginning of story: no word { // to delete GetPed()->Sound(); return FALSE; } Collapser(tomStart); // First collapse to cpMin FindWordBreak(WB_MOVEWORDLEFT); // Extend word left } else if (!_cch) // Empty selection { // Try to select previous char if (!BackupCRLF()) // to delete it { // Nothing to delete GetPed()->Sound(); return FALSE; } mode = SELRR_REMEMBERENDIP; if (publdr) { publdr->StartGroupTyping(); } } ReplaceRange(0, NULL, publdr, mode); // Delete selection return TRUE; } /* * CTxtSelection::ReplaceRange(cchNew, pch, publdr) * * @mfunc * Replace selected text by new given text and update screen according * to _fShowCaret and _fShowSelection * * @rdesc * length of text inserted */ LONG CTxtSelection::ReplaceRange( LONG cchNew, //@parm Length of replacing text or -1 to request // <p pch> sz length const TCHAR *pch, //@parm Replacing text IUndoBuilder *publdr, //@parm If non-NULL, where to put anti-events SELRR SELRRMode) //@parm what to do about selection anti-events. { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::ReplaceRange"); _TEST_INVARIANT_ LONG cchKeep; LONG cchNewSave; LONG cchOld; LONG cchText = GetTextLength(); LONG cpFirstRecalc; LONG cpMin, cpMost; LONG cpSave; const BOOL fShowCaret = _fShowCaret; const BOOL fUpdateView = _fShowSelection; CancelModes(); if (cchNew < 0) { cchNew = wcslen(pch); } if (!_cch && !cchNew) // Nothing to do { return 0; } GetPed()->GetCallMgr()->SetSelectionChanged(); cchOld = GetRange(cpMin, cpMost); if (cpMin > min(_cpSel, _cpSel + _cchSel) || // If new sel doesn't cpMost < max(_cpSel, _cpSel + _cchSel)) // contain all of old { // sel, remove old sel ShowSelection(FALSE); _fShowCaret = TRUE; } // FUTURE: Is the following if{} needed? What if cchNew > 0? Also if we // keep it, shouldn't it follow the WaitForRecalc() below? Note that // below there is: if(_rpTX.IsAfterEOP()) _fCaretNotAtBOL = FALSE; The // case for cchNew > 0 and !_rpTX.IsAfterEOP() doesn't set _fCaretNotAtBOL. // NOTE: I commented out all references to _fCaretNotAtBOL in this routine // and couldn't observe any strange behavior in reitp (murrays). Also it // seems to me that for insertion points, _fCaretNotAtBOL can always be // FALSE, so we can just set it FALSE here. (See CTxtSelection::Right for // a nondegenerate selection that needs to have it TRUE). if (!cchNew) { CLinePtr rp(_pdp); rp.RpSetCp(cpMin, FALSE); _fCaretNotAtBOL = rp.RpGetIch() != 0; } _fShowSelection = FALSE; // Suppress the flashies: cchKeep = cchText - cchOld; // Number of untouched chars // If we are streaming in text or RTF data, don't bother with incremental // recalcs. The data transfer engine will take care of a final recalc if (!GetPed()->IsStreaming()) { // Do this before calling ReplaceRange() so that UpdateView() works // AROO !!! Do this before replacing the text or the format ranges!!! if (!_pdp->WaitForRecalc(cpMin, -1)) { Tracef(TRCSEVERR, "WaitForRecalc(%ld) failed", cpMin); goto err; } } if (publdr) { Assert(SELRRMode != SELRR_IGNORE); // use the selection AntiEvent mode to determine what to do for undo LONG cp, cch = 0; if (SELRRMode == SELRR_REMEMBERRANGE) { cp = GetCp(); cch = _cch; } else if (SELRRMode == SELRR_REMEMBERENDIP) { cp = cpMost; } else { Assert(SELRRMode == SELRR_REMEMBERCPMIN); cp = cpMin; } HandleSelectionAEInfo(GetPed(), publdr, cp, cch, cpMin + cchNew, 0, SELAE_MERGE); } cpSave = cpMin; cpFirstRecalc = cpSave; cchNewSave = cchNew; cchNew = CTxtRange::ReplaceRange(cchNew, pch, publdr, SELRR_IGNORE); _cch = 0; _cchSel = 0; // No displayed selection _cpSel = GetCp(); // any ReplaceRange() cchText = GetTextLength(); // Update total text length if (cchNew != cchNewSave) { Tracef(TRCSEVERR, "CRchTxtPtr::ReplaceRange(%ld, %ld, %ld) failed", GetCp(), cchOld, cchNew); goto err; } // The cp should be at *end* (cpMost) of replaced range (it starts // at cpMin of the prior range). AssertSz(_cpSel == cpSave + cchNew && _cpSel <= cchText, "CTxtSelection::ReplaceRange() - Wrong cp after replacement"); // If no new and no old, return value better be 0 Assert(cchNew > 0 || cchOld > 0 || cchKeep == cchText); cchNew = cchText - cchKeep; // Actual cchNew inserted _fShowSelection = fUpdateView; if (_rpTX.IsAfterEOP()) // Ambiguous cp has caret at { _fCaretNotAtBOL = FALSE; // BOL } // We can only update the caret if we are inplace active. if (GetPed()->fInplaceActive()) { UpdateCaret(fUpdateView); // May need to scroll } else { // Update caret when we get focus again GetPed()->_fScrollCaretOnFocus = TRUE; } return cchNew; err: TRACEERRSZSC("CTxtSelection::ReplaceRange()", E_FAIL); Tracef(TRCSEVERR, "CTxtSelection::ReplaceRange(%ld, %ld)", cchOld, cchNew); Tracef(TRCSEVERR, "cchText %ld", cchText); return cchText - cchKeep; } /* * CTxtSelection::SetCharFormat(pCF, fApplyToWord, publdr) * * @mfunc * apply CCharFormat *pCF to this selection. If range is an IP * and fApplyToWord is TRUE, then apply CCharFormat to word surrounding * this insertion point * * @rdesc * HRESULT = NOERROR if no error */ HRESULT CTxtSelection::SetCharFormat( const CCharFormat *pcf, //@parm Ptr to CCharFormat to fill with results IUndoBuilder *publdr, //@parm the undo context DWORD flags) //@parm If TRUE and this selection is an IP, // use enclosing word { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SetCharFormat"); HRESULT hr; LONG iFormat = _iFormat; BOOL fApplyToWord = (flags & SCF_WORD) ? CTxtRange::APPLYTOWORD : 0; if (publdr) { publdr->StopGroupTyping(); } /* * The code below applies character formatting to a double-clicked * selection the way Word does it, that is, not applying the formatting to * the last character in the selection if that character is a blank. * * See also the corresponding code in CTxtRange::GetCharFormat(). */ LONG cch; LONG cpMin, cpMost; if (_SelMode == smWord && (flags & SCF_USEUIRULES)) // In word select mode, { // don't include final blank in cch = GetRange(cpMin, cpMost); // SetCharFormat AssertSz(cch, "CTxtSelection::SetCharFormat: IP in word select mode"); cpMost--; // Setup new range to end at last cch--; // char in selection CTxtRange rg(GetPed(), cpMost, cch); if (rg._rpTX.GetChar() == ' ') // Selection ends with a blank: { // don't format it hr = rg.SetCharFormat(pcf, FALSE, publdr); goto finish; } } hr = CTxtRange::SetCharFormat(pcf, fApplyToWord, publdr); if (_iFormat != iFormat) // _iFormat changed { CheckChangeKeyboardLayout(TRUE); } finish: UpdateCaret(TRUE); return hr; } /* * CTxtSelection::SetParaFormat(pPF, publdr) * * @mfunc * apply CParaFormat *pPF to this selection. * * #rdesc * HRESULT = NOERROR if no error */ HRESULT CTxtSelection::SetParaFormat( const CParaFormat *pPF, //@parm ptr to CParaFormat to apply IUndoBuilder *publdr) //@parm the Undo context for this operation { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::SetParaFormat"); if (publdr) { publdr->StopGroupTyping(); } // Apply the format HRESULT hr = CTxtRange::SetParaFormat(pPF, publdr); UpdateCaret(TRUE); return hr; } /* * CTxtSelection::SetSelectionInfo (pselchg) * * @mfunc Fills out data members in a SELCHANGE structure * * @rdesc void */ void CTxtSelection::SetSelectionInfo( SELCHANGE *pselchg) //@parm the SELCHANGE structure to use { LONG cpMin, cpMost; LONG cch; LONG cObjects; CObjectMgr *pobjmgr; cch = GetRange(cpMin, cpMost); pselchg->chrg.cpMin = cpMin; pselchg->chrg.cpMax = cpMost; // now fill out the selection type flags. // the flags mean the following things: // // SEL_EMPTY: insertion point // SEL_TEXT: at least one character selected // SEL_MULTICHAR: more than one character selected // SEL_OBJECT: at least one object selected // SEL_MULTIOJBECT: more than one object selected // // note that the flags are OR'ed together. //This is the default pselchg->seltyp = SEL_EMPTY; if (cch) { cObjects = GetObjectCount(); // Total object count if (cObjects) // There are objects: { // get count in range pobjmgr = GetPed()->GetObjectMgr(); Assert(pobjmgr); cObjects = pobjmgr->CountObjectsInRange(cpMin, cpMost); if (cObjects > 0) { pselchg->seltyp |= SEL_OBJECT; if (cObjects > 1) { pselchg->seltyp |= SEL_MULTIOBJECT; } } } cch -= cObjects; AssertSz(cch >= 0, "objects are overruning the selection"); if (cch > 0) { pselchg->seltyp |= SEL_TEXT; if (cch > 1) { pselchg->seltyp |= SEL_MULTICHAR; } } } } /* * CTxtSelection::UpdateForAutoWord (cpAnchor) * * @mfunc Update state to prepare for auto word selection * * @rdesc void */ void CTxtSelection::UpdateForAutoWord( LONG cpAnchor) //@parm cp to user for the anchor { // If enabled, prepare Auto Word Sel if (GetPed()->TxGetAutoWordSel()) { CTxtPtr tp(GetPed(), cpAnchor); // Move anchor to new location _cpAnchor = cpAnchor; // Remember that FindWordBreak moves tp's cp // (aren't side effects wonderful? tp.FindWordBreak(WB_MOVEWORDRIGHT); _cpAnchorMost = _cpWordMost = tp.GetCp(); tp.FindWordBreak(WB_MOVEWORDLEFT); _cpAnchorMin = _cpWordMin = tp.GetCp(); _fAutoSelectAborted = FALSE; } } /* * CTxtSelection::AutoSelGoBackWord(pcpToUpdate, iDirToPrevWord, iDirToNextWord) * * @mfunc Backup a word in auto word selection * * @rdesc void */ void CTxtSelection::AutoSelGoBackWord( LONG *pcpToUpdate, //@parm end of word selection to update int iDirToPrevWord, //@parm direction to next word int iDirToNextWord) //@parm direction to previous word { if (GetCp() >= _cpAnchorMin && GetCp() <= _cpAnchorMost) { // We are back in the first word. Here we want to pop // back to a selection anchored by the original selection Set(GetCp(), GetCp() - _cpAnchor); _fAutoSelectAborted = FALSE; _cpWordMin = _cpAnchorMin; _cpWordMost = _cpAnchorMost; } else { // pop back a word *pcpToUpdate = _cpWordPrev; CTxtPtr tp(_rpTX); _cpWordPrev = GetCp() + tp.FindWordBreak(iDirToPrevWord); FindWordBreak(iDirToNextWord); } } /* * CTxtSelection::InitClickForAutWordSel (pt) * * @mfunc Init auto selection for click with shift key down * * @rdesc void */ void CTxtSelection::InitClickForAutWordSel( const POINT pt) //@parm Point of click { // If enabled, prepare Auto Word Sel if (GetPed()->TxGetAutoWordSel()) { // If auto word selection is occuring we want to pretend // that the click is really part of extending the selection. // Therefore, we want the auto word select data to look as // if the user had been extending the selection via the // mouse all along. So we set the word borders to the // word that would have been previously selected. // Need this for finding word breaks CRchTxtPtr rtp(GetPed()); LONG cpClick = _pdp->CpFromPoint(pt, NULL, &rtp, NULL, TRUE); int iDir = -1; if (cpClick < 0) { // If this fails what can we do? Prentend it didn't happen! // We can do this because it will only make the UI act a // little funny and chances are the user won't even notice // this. return; } // Assume click is within anchor word _cpWordMost = _cpAnchorMost; _cpWordMin = _cpAnchorMin; if (cpClick > _cpAnchorMost) { // Click after the anchor word so set most and // prev appropriately. iDir = WB_MOVEWORDLEFT; rtp.FindWordBreak(WB_MOVEWORDLEFT); _cpWordMost = rtp.GetCp(); } // Click is before the anchor word else if (cpClick < _cpAnchorMost) { // Click before the anchor word so set most and // prev appropriately. iDir = WB_MOVEWORDRIGHT; rtp.FindWordBreak(WB_MOVEWORDRIGHT); _cpWordMin = rtp.GetCp(); } if (iDir != -1) { rtp.FindWordBreak(iDir); _cpWordPrev = rtp.GetCp(); } } } /* * CTxtSelection::CreateCaret () * * @mfunc Create a caret * * @rdesc void */ void CTxtSelection::CreateCaret() { CTxtEdit *ped = GetPed(); ped->TxCreateCaret(0, dxCaret, (INT)_yHeightCaret); ped->TxSetCaretPos((INT)_xCaret, (INT)_yCaret); _fCaretCreated = TRUE; } /* * CTxtSelection::SetDelayedSelectionRange * * @mfunc sets the selection range such that it won't take effect until * the control is "stable" */ void CTxtSelection::SetDelayedSelectionRange( LONG cp, //@parm the active end LONG cch) //@parm the signed extension { CSelPhaseAdjuster *pspa; pspa = (CSelPhaseAdjuster *)GetPed()->GetCallMgr()->GetComponent( COMP_SELPHASEADJUSTER); Assert(pspa); pspa->CacheRange(cp, cch); } /* * CTxtSelection::CheckPlainTextFinalEOP () * * @mfunc * returns TRUE if this is a plain-text, multiline control with caret * allowed at BOL and the selection at the end of the story following * and EOP */ BOOL CTxtSelection::CheckPlainTextFinalEOP() { CTxtEdit *ped = GetPed(); return !ped->IsRich() // Plain-text, && ped->TxGetMultiLine() // multiline control, && !_fCaretNotAtBOL // with caret OK at BOL, && GetCp() == (LONG)ped->GetTextLength() // & cp at end of story && _rpTX.IsAfterEOP(); } /* * CTxtSelection::PrepareIMEOverstrike(fOver, publdr) * * @mfunc * Prepare for IME overtype by deleting the next character * * @rdesc * TRUE if successful */ void CTxtSelection::PrepareIMEOverstrike( IUndoBuilder *publdr) //@parm If non-NULL, where to put anti-events { TRACEBEGIN(TRCSUBSYSSEL, TRCSCOPEINTERN, "CTxtSelection::PrepareIMEOverstrike"); _TEST_INVARIANT_ // If nothing selected and not at EOP char, try // to select char at IP if (!_cch && !_rpTX.IsAtEOP()) { LONG iFormatSave = Get_iCF(); // Remember char's format if (publdr) { publdr->StopGroupTyping(); } SetExtend(TRUE); // Tell Advance() to select chars Advance(1); ReplaceRange(0, NULL, publdr, SELRR_REMEMBERENDIP); // Delete this character. ReleaseFormats(_iFormat, -1); _iFormat = iFormatSave; // Restore char's format. } } // // CSelPhaseAdjuster methods // /* * CSelPhaseAdjuster::CSelPhaseAdjuster * * @mfunc constructor */ CSelPhaseAdjuster::CSelPhaseAdjuster( CTxtEdit *ped) //@parm the edit context { _cp = _cch = -1; _ped = ped; _ped->GetCallMgr()->RegisterComponent((IReEntrantComponent *)this, COMP_SELPHASEADJUSTER); } /* * CSelPhaseAdjuster::~CSelPhaseAdjuster * * @mfunc destructor */ CSelPhaseAdjuster::~CSelPhaseAdjuster() { // Save some indirections CTxtEdit *ped = _ped; if (_cp != -1) { ped->GetSel()->SetSelection(_cp - _cch, _cp); // If the selection is updated, then we invalidate the // entire display because the old selection can still // appear othewise because the part of the screen that // it was on is not updated. if (ped->fInplaceActive()) { // Tell entire client rectangle to update. // FUTURE: The smaller we make this the better. ped->TxInvalidateRect(NULL, FALSE); } } ped->GetCallMgr()->RevokeComponent((IReEntrantComponent *)this); } /* * CSelPhaseAdjuster::CacheRange * * @mfunc tells this class the selection range to remember */ void CSelPhaseAdjuster::CacheRange( LONG cp, //@parm the active end to remember LONG cch) //@parm the signed extension to remember { _cp = cp; _cch = cch; }
25.227534
115
0.630086
[ "render", "object" ]
b9a90d00ae1d7b3741ce707303fbc55eddc33d02
4,867
cpp
C++
handout/Game/Source/Scene.cpp
mrmile/Audio_And_Music_Manager
330454d47cad50711c95235657962536ba679679
[ "MIT" ]
null
null
null
handout/Game/Source/Scene.cpp
mrmile/Audio_And_Music_Manager
330454d47cad50711c95235657962536ba679679
[ "MIT" ]
null
null
null
handout/Game/Source/Scene.cpp
mrmile/Audio_And_Music_Manager
330454d47cad50711c95235657962536ba679679
[ "MIT" ]
null
null
null
#include "App.h" #include "Input.h" #include "Textures.h" #include "Audio.h" #include "Render.h" #include "Window.h" #include "Scene.h" #include "ModulePlayer.h" #include "Defs.h" #include "Log.h" #include <SDL_mixer/include/SDL_mixer.h> Scene::Scene() : Module() { name.Create("scene"); } // Destructor Scene::~Scene() {} // Called before render is available bool Scene::Awake() { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool Scene::Start() { img = app->tex->Load("Assets/Textures/speakers.png"); img2 = app->tex->Load("Assets/Textures/speakers_ground.png"); glassBreak = app->audio->LoadFx("Assets/Audio/Fx/breaking_glass.wav"); activationSound = app->audio->LoadFx("Assets/Audio/Fx/generator_activation.wav"); steamValve = app->audio->LoadFx("Assets/Audio/Fx/steam_valve.wav"); ventWalk[0] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_01.wav"); ventWalk[1] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_02.wav"); ventWalk[2] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_03.wav"); ventWalk[3] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_04.wav"); ventWalk[4] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_05.wav"); ventWalk[5] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_06.wav"); ventWalk[6] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_07.wav"); ventWalk[7] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_08.wav"); ventWalk[8] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_09.wav"); ventWalk[9] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_10.wav"); ventWalk[10] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_11.wav"); ventWalk[11] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_12.wav"); ventWalk[12] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_13.wav"); ventWalk[13] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_14.wav"); ventWalk[14] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_15.wav"); ventWalk[15] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_16.wav"); ventWalk[16] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_17.wav"); ventWalk[17] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_18.wav"); ventWalk[18] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_19.wav"); ventWalk[19] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_20.wav"); ventWalk[20] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_21.wav"); ventWalk[21] = app->audio->LoadFx("Assets/Audio/Fx/MOV_HunterVentWalk_22.wav"); sceneTimer = 0; ventWalkSoundID = 0; return true; } // Called each loop iteration bool Scene::PreUpdate() { return true; } // Called each loop iteration bool Scene::Update(float dt) { sceneTimer++; if (app->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { //Todo 4.1: Use the new playFX function to play glassBreak sound effect spatially //(the speakers center coordinates are { 640, 360 }) } if (app->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { //Todo 4.2: Use the new playFX function to play steamValve sound effect spatially //(the speakers center coordinates are { 640, 360 }) } if (app->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN) { //Todo 4.3: Use the new playFX function to play activationSound sound effect spatially //(the speakers center coordinates are { 640, 360 }) } if (app->input->GetKey(SDL_SCANCODE_F4) == KEY_REPEAT) { //Todo 4.4: Use the new playFX function to play the modular "ventWalk" sound effect //(the speakers center coordinates are { 640, 360 }) //Note that modular sounds require extra logic in addition to the playFx function } if (app->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) { // Todo 5.1: Use the ChangeMusic function to switch the music to OFF (feel free to experiment with fades) } if (app->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) { // Todo 5.2: Use the ChangeMusic function to switch the music to EL_BOOM (feel free to experiment with fades) } if (app->input->GetKey(SDL_SCANCODE_F7) == KEY_DOWN) { // Todo 5.3: Use the ChangeMusic function to switch the music to PRENDE_UN_PORRO (feel free to experiment with fades) } if (app->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN) { app->audio->playMusicSpatially = !app->audio->playMusicSpatially; } if (app->audio->playMusicSpatially == true) { // Todo 6: Use the PlayMusicSpatially function to play music spatially when switched on //(the speakers center coordinates are { 640, 360 }) } return true; } // Called each loop iteration bool Scene::PostUpdate() { bool ret = true; if(app->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool Scene::CleanUp() { LOG("Freeing scene"); return true; }
29.49697
119
0.718101
[ "render" ]
b9ae8a7f6fcfb6ec4dbbd7e5c77016f25f5bb3c4
1,055
cpp
C++
C++/remove-boxes.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
remove-boxes.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
remove-boxes.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time: O(n^3) ~ O(n^4) // Space: O(n^3) class Solution { public: int removeBoxes(vector<int>& boxes) { int lookup[100][100][100] = {0}; return removeBoxesHelper(boxes, 0, boxes.size() - 1, 0, lookup); } private: int removeBoxesHelper(const vector<int>& boxes, int l, int r, int k, int lookup[100][100][100]) { if (l > r) { return 0; } if (lookup[l][r][k]) { return lookup[l][r][k]; } auto& result = lookup[l][r][k]; while (l < r && boxes[l + 1] == boxes[l]) { ++l, ++k; } result = removeBoxesHelper(boxes, l + 1, r, 0, lookup) + (k + 1) * (k + 1); for (int i = l + 1; i <= r; ++i) { if (boxes[i] == boxes[l]) { result = max(result, removeBoxesHelper(boxes, l + 1, i - 1, 0, lookup) + removeBoxesHelper(boxes, i, r, k + 1, lookup)); } } return result; } };
30.142857
102
0.420853
[ "vector" ]
b9c17a65f25ee7d3e2d8b3241fc490f2f93f8708
4,192
cpp
C++
Drill4dotNet/Drill4dotNet-Tests/CProfilerCallbackTest.cpp
Drill4J/agent-dotnet
75b8b95c86173afee4b7072c8d02ea8cb341fad7
[ "Apache-2.0" ]
7
2019-12-26T05:38:25.000Z
2021-06-23T07:04:59.000Z
Drill4dotNet/Drill4dotNet-Tests/CProfilerCallbackTest.cpp
Drill4J/agent-dotnet
75b8b95c86173afee4b7072c8d02ea8cb341fad7
[ "Apache-2.0" ]
11
2020-01-13T22:31:34.000Z
2020-04-10T17:59:33.000Z
Drill4dotNet/Drill4dotNet-Tests/CProfilerCallbackTest.cpp
Drill4J/agent-dotnet
75b8b95c86173afee4b7072c8d02ea8cb341fad7
[ "Apache-2.0" ]
4
2020-02-10T18:19:24.000Z
2021-06-23T06:58:41.000Z
#include "pch.h" #include "ComWrapperBase.h" #include "CoreInteractMock.h" #include "MetaDataAssemblyImportMock.h" #include "MetaDataDispenserMock.h" #include "ConnectorMock.h" #include "ProClient.h" #include <CProfilerCallback.h> using namespace Drill4dotNet; using namespace testing; class CProfilerCallbackTest : public Test { public: void SetUp() { proClient.emplace(); profilerCallback.emplace(*proClient); WCHAR injectionFileName[_MAX_PATH]; ::GetModuleFileName(NULL, injectionFileName, _MAX_PATH); Drill4dotNet::s_Drill4dotNetLibFilePath = injectionFileName; } void TearDown() { profilerCallback.reset(); proClient.reset(); } std::optional<ProClient<ConnectorMock>> proClient; std::optional<CProfilerCallback< ConnectorMock, CoreInteractMock, MetaDataDispenserMock, MetaDataAssemblyImportMock, MetadataImportMock, TrivialLogger>> profilerCallback; }; TEST_F(CProfilerCallbackTest, GetClient) { EXPECT_EQ(&*proClient, &profilerCallback->GetClient()); } TEST_F(CProfilerCallbackTest, Initialize_Shutdown) { // We have to pair each Initialize() by Shutdown() to properly clean up resources // ...until we change the design of ownership on CorProfilerInterface. const auto rti_expected = std::optional<RuntimeInformation>({ 0, COR_PRF_DESKTOP_CLR, 9, 9, 999, 8 }); const auto coreInteractCreation { CoreInteractMock::SetCreationCallBack([rti_expected]( CoreInteractMock& corInteractMock, IUnknown* query, TrivialLogger logger) { EXPECT_CALL(corInteractMock, TryGetRuntimeInformation()).WillOnce(Return(rti_expected)); EXPECT_CALL(corInteractMock, SetEventMask(_)).WillOnce(Return()); EXPECT_CALL(corInteractMock, SetEnterLeaveFunctionHooks(_,_,_)).WillOnce(Return()); EXPECT_CALL(corInteractMock, SetFunctionIDMapper(_)).WillOnce(Return()); }) }; const InjectionMetaData expectedInjection { 0x69'6D'71'EF, 0x9A'F0'D6'D8, 0xE9'C2'80'22 }; const std::wstring injectionAssemblyName { L"Injection" }; const auto metaDataAssemblyImportCreation { MetaDataAssemblyImportMock::SetOnCreate([expectedInjection, injectionAssemblyName](MetaDataAssemblyImportMock& metaDataAssemblyImportMock) { EXPECT_CALL(metaDataAssemblyImportMock, GetAssemblyFromScope()).WillOnce(Return(expectedInjection.Assembly)); EXPECT_CALL(metaDataAssemblyImportMock, GetAssemblyProps(expectedInjection.Assembly)).WillOnce(Return(AssemblyProps { injectionAssemblyName, 0 })); }) }; const std::wstring injectionClassName { L"Drill4dotNet.CInjection" }; const std::wstring injectionMethodName { L"FInjection" }; const auto metaDataImportCreation { MetadataImportMock::SetOnCreate([expectedInjection, injectionClassName, injectionMethodName](MetadataImportMock& metaDataImportMock) { EXPECT_CALL(metaDataImportMock, FindTypeDefByName(injectionClassName, 0)).WillOnce(Return(expectedInjection.Class)); EXPECT_CALL(metaDataImportMock, GetTypeDefProps(expectedInjection.Class)).WillOnce(Return(TypeDefProps { injectionClassName, 0, 0 })); EXPECT_CALL(metaDataImportMock, EnumMethodsWithName(expectedInjection.Class, injectionMethodName)).WillOnce(Return(std::vector { expectedInjection.Function })); }) }; std::function<std::vector<AstEntity>()> treeProvider{}; EXPECT_CALL(proClient->GetConnector(), TreeProvider()).WillOnce(ReturnRef(treeProvider)); IUnknown* p = reinterpret_cast<IUnknown*>(this); EXPECT_HRESULT_SUCCEEDED(profilerCallback->Initialize(p)); EXPECT_EQ(typeid(std::optional<CoreInteractMock>), typeid(profilerCallback->GetCorProfilerInfo()) ); const InjectionMetaData actualInjection = profilerCallback->GetInfoHandler().GetInjectionMetaData(); EXPECT_EQ(expectedInjection.Assembly, actualInjection.Assembly); EXPECT_EQ(expectedInjection.Class, actualInjection.Class); EXPECT_EQ(expectedInjection.Function, actualInjection.Function); EXPECT_HRESULT_SUCCEEDED(profilerCallback->Shutdown()); EXPECT_FALSE(profilerCallback->GetCorProfilerInfo().has_value()); }
44.595745
186
0.753817
[ "vector" ]
b9c5627cf8f73cfdb83f1b40fffbe55cef8bbde2
5,354
cpp
C++
app/sources/Config.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
null
null
null
app/sources/Config.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
null
null
null
app/sources/Config.cpp
ptensschi/CppUMockGen
d11f12297688f99863238b263f241b6e3ac66dfd
[ "BSD-3-Clause" ]
1
2019-01-10T20:36:24.000Z
2019-01-10T20:36:24.000Z
#include "Config.hpp" #include <stdexcept> #include <set> #include <vector> Config::Config( bool useUnderlyingTypedefType, const std::vector<std::string> &paramOverrideOptions, const std::vector<std::string> &typeOverrideOptions ) : m_useUnderlyingTypedefType( useUnderlyingTypedefType ), m_paramOverrideMap( paramOverrideOptions, false ), m_typeOverrideMap( typeOverrideOptions, true ) {} bool Config::UseUnderlyingTypedefType() const { return m_useUnderlyingTypedefType; } const Config::OverrideSpec* Config::GetParameterOverride( const std::string& key ) const { return m_paramOverrideMap.GetOverride(key); } const Config::OverrideSpec* Config::GetTypeOverride( const std::string& key ) const { return m_typeOverrideMap.GetOverride(key); } static const std::vector<std::pair<std::string, MockedType>> validOverrideTypes = { { "Bool", MockedType::Bool }, { "Int", MockedType::Int }, { "UnsignedInt", MockedType::UnsignedInt }, { "LongInt", MockedType::Long }, { "UnsignedLongInt", MockedType::UnsignedLong }, { "Double", MockedType::Double }, { "String", MockedType::String }, { "Pointer", MockedType::Pointer }, { "ConstPointer", MockedType::ConstPointer }, { "Output", MockedType::Output }, { "Skip", MockedType::Skip }, }; static const std::map<std::string, MockedType> validReturnOverrideTypes( validOverrideTypes.begin(), validOverrideTypes.end() - 2 ); static const std::map<std::string, MockedType> validParameterOverrideTypes( validOverrideTypes.begin(), validOverrideTypes.end() ); Config::OverrideSpec::OverrideSpec( const std::string &value, const std::string &option, bool isReturn ) { if( value.empty() ) { std::string errorMsg = "Override option specification cannot be empty <" + option + ">"; throw std::runtime_error( errorMsg ); } std::string type; size_t sepPos = value.find( EXPR_MOD_SEPARATOR ); if( sepPos != std::string::npos ) { type = value.substr(0, sepPos); if( type.empty() ) { std::string errorMsg = "Override option type cannot be empty <" + option + ">"; throw std::runtime_error( errorMsg ); } std::string argExprMod = value.substr(sepPos+1); if( argExprMod.empty() ) { std::string errorMsg = "Override option argument expression cannot be empty if specified <" + option + ">"; throw std::runtime_error( errorMsg ); } size_t placeholderPos = argExprMod.find( EXPR_MOD_PLACEHOLDER ); if( placeholderPos == std::string::npos ) { std::string errorMsg = "Override option argument expression does not contain parameter name placeholder ($) <" + option + ">"; throw std::runtime_error( errorMsg ); } m_exprModFront = argExprMod.substr( 0, placeholderPos ); m_exprModBack = argExprMod.substr( placeholderPos + 1 ); } else { type = value; } if( isReturn ) { auto it = validReturnOverrideTypes.find( type ); if( it != validReturnOverrideTypes.end() ) { m_type = it->second; } else { std::string errorMsg = "Invalid return override option type <" + option + ">."; throw std::runtime_error( errorMsg ); } } else { auto it = validParameterOverrideTypes.find( type ); if( it != validParameterOverrideTypes.end() ) { m_type = it->second; } else { std::string errorMsg = "Invalid parameter override option type <" + option + ">."; throw std::runtime_error( errorMsg ); } } } Config::OverrideMap::OverrideMap( const std::vector<std::string> &options, bool typeOverride ) { for( const std::string &option : options ) { size_t sepPos = option.find('='); if( sepPos != std::string::npos ) { std::string key = option.substr(0, sepPos); if( key.empty() ) { std::string errorMsg = "Override option key cannot be empty <" + option + ">."; throw std::runtime_error( errorMsg ); } bool isReturn = ( typeOverride ? ( key.front() == '@' ) : ( key.back() == '@' ) ); Config::OverrideSpec spec = Config::OverrideSpec( option.substr(sepPos+1), option, isReturn ); if( !m_map.emplace( key, spec ).second ) { std::string errorMsg = "Override option key <" + key + "> can only be passed once."; throw std::runtime_error( errorMsg ); } } else { std::string errorMsg = "Invalid override option <" + option + ">."; throw std::runtime_error( errorMsg ); } } } const Config::OverrideSpec* Config::OverrideMap::GetOverride( const std::string& key ) const { OverrideMapType::const_iterator it = m_map.find( key ); return ( it != m_map.end() ) ? &(it->second) : NULL; } MockedType Config::OverrideSpec::GetType() const { return m_type; } const std::string& Config::OverrideSpec::GetExprModFront() const { return m_exprModFront; } const std::string& Config::OverrideSpec::GetExprModBack() const { return m_exprModBack; }
32.05988
138
0.607583
[ "vector" ]
b9c850945f6fe28fcd217316e24c8fabd48357a1
5,276
cpp
C++
homework/Muravyev/05/prog.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
10
2017-09-21T15:17:33.000Z
2021-01-11T13:11:55.000Z
homework/Muravyev/05/prog.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
null
null
null
homework/Muravyev/05/prog.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
22
2017-09-21T15:45:08.000Z
2019-02-21T19:15:25.000Z
#include <iostream> #include <vector> #include <cassert> using namespace std; template <class T> class Row{ // Вспомогательный класс "строка" public: Row(int l = 0, T *v = nullptr){ len = l; vector = v; } ~Row(){} const T& operator[](int i) const{ if (i >= len) assert(!"index out of range"); return vector[i]; } T& operator[](int i){ if (i >= len) assert(!"index out of range"); return vector[i]; } private: int len; T *vector; }; template <class T> class Matrix{ // Основной класс "матрица" public: Matrix(int r = 0, int c = 0){ rows = r; cols = c; matrix = new T[r*c]; } Matrix(const Matrix<T>& m){ // Конструктор копирования delete[] matrix; cols = m.GetCols(); rows = m.GetRows(); matrix = new T[rows*cols]; for(int i = 0;i < rows;++i){ for(int j = 0;j < cols;++j){ matrix[i*cols+j] = m[i][j]; } } } Matrix(Matrix<T>&& m){ // Конструктор перемещения if (this == &m) { return; } rows = move(m.rows); cols = move(m.cols); delete[] matrix; matrix = move(m.matrix); m.matrix = nullptr; m.rows = 0; m.cols = 0; } ~Matrix(){ delete[] matrix; } const int GetRows() const{ return rows; } const int GetCols() const{ return cols; } const Row<T>& operator[](int i) const{ if (i >= rows) assert(!"index out of range"); col = Row<T>(cols, &matrix[i*cols]); return col; } Row<T>& operator[](int i){ if (i >= rows) assert(!"index out of range"); col = Row<T>(cols, &matrix[i*cols]); return col; } Matrix<T>& operator*=(T a){ for (int i = 0; i < rows*cols; ++i){ matrix[i]*=a; } return *this; } Matrix<T>& operator*=(vector<T>& v){ if (cols != v.size()) assert(!"incorrect operation"); T s; T *m = new T[rows]; for(int i = 0;i < rows;++i){ s = 0; for(int j = 0;j < cols;++j){ s += matrix[i*cols +j]*v[j]; } m[i] = s; } delete[] matrix; matrix = m; cols = 1; return *this; } Matrix& operator=(Matrix<T>&& m){ // Оператор перемещения if (this == &m) { return *this; } rows = move(m.rows); cols = move(m.cols); delete[] matrix; matrix = move(m.matrix); m.matrix = nullptr; m.rows = 0; m.cols = 0; return *this; } Matrix<T>& operator=(const Matrix<T>& m){ // Оператор копирования delete[] matrix; cols = m.GetCols(); rows = m.GetRows(); matrix = new T[rows*cols]; for(int i = 0;i < rows;++i){ for(int j = 0;j < cols;++j){ matrix[i*cols+j] = m[i][j]; } } return *this; } bool operator==(const Matrix<T>& m) const{ if (rows != m.GetRows() || cols != m.GetCols()) return false; for (int i = 0;i < cols*rows;++i){ if (matrix[i] != m[i/cols][i%cols]) return false; } return true; } bool operator!=(const Matrix<T>& m) const{ return !(*this == m); } private: int rows; int cols; T *matrix; mutable Row<T> col; }; void check(bool value){ if (!value) cout << "error" << endl; } void checkGetSet(){ // Тест Matrix<double> mat; Matrix<double> m(2, 3); m[0][0] = 1; m[0][1] = 2; m[0][2] = 3; m[1][0] = 4; m[1][1] = 5; m[1][2] = 6; check(m[0][0] == 1); // Проверяем присваивание и сравнение check(m[0][1] == 2); // на равенство check(m[0][2] == 3); check(m[1][0] == 4); check(m[1][1] == 5); check(m[1][2] == 6); check(m[0][0] != 2); // Проверяем на неравенство m *= 2; check(m[1][2] == 12); // Проверяем умножение на число check(m[0][1] == 4); m *= 0.5; check(m[1][2] == 6); vector<double> v(3); v[0] = 1; v[1] = 0; v[2] = 1; m *= v; check(m[0][0] == 4); // Проверка умножения на вектор check(m[1][0] == 10); mat = m; // Проверка копирования mat[0][0] = 2; check(mat[0][0] == 2); check(m[0][0] == 4); // Проверяем, что объекты не связаны check(m.GetRows() == 2); // Проверка получения количества строк check(m.GetCols() == 1); // и столбцов mat = move(m); // Проверка оператора перемещения check(mat[0][0] == 4); // Проверяем, что работают шаблоны // Делаем то же самое, но с int вместо double Matrix<int> imat; Matrix<int> im(2, 3); im[0][0] = 1; im[0][1] = 2; im[0][2] = 3; im[1][0] = 4; im[1][1] = 5; im[1][2] = 6; check(im[0][0] == 1); // Проверяем присваивание и сравнение check(im[0][1] == 2); // на равенство check(im[0][2] == 3); check(im[1][0] == 4); check(im[1][1] == 5); check(im[1][2] == 6); check(im[0][0] != 2); // Проверяем на неравенство im *= 2; check(im[1][2] == 12); // Проверяем умножение на число check(im[0][1] == 4); vector<int> iv(3); iv[0] = 1; iv[1] = 0; iv[2] = 1; im *= iv; check(im[0][0] == 8); // Проверка умножения на вектор check(im[1][0] == 20); imat = im; // Проверка копирования imat[0][0] = 2; check(imat[0][0] == 2); check(im[0][0] == 8); // Проверяем, что объекты не связаны check(im.GetRows() == 2); // Проверка получения количества строк check(im.GetCols() == 1); // и столбцов imat = move(im); // Проверка оператора перемещения check(imat[0][0] == 8); } int main(){ checkGetSet(); return 0; }
20.936508
68
0.521418
[ "vector" ]
8454e4a16391840eb70accb199474e0e2a188343
10,976
inl
C++
ork.lev2/src/gfx/meshutil/assimp_util.inl
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
25
2015-02-21T04:21:21.000Z
2022-01-20T05:19:27.000Z
ork.lev2/src/gfx/meshutil/assimp_util.inl
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
113
2019-08-23T04:52:14.000Z
2021-09-13T04:04:11.000Z
ork.lev2/src/gfx/meshutil/assimp_util.inl
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
4
2017-02-20T18:17:55.000Z
2020-06-28T03:47:55.000Z
/////////////////////////////////////////////////////////////////////////////// // Orkid // Copyright 1996-2020, Michael T. Mayers /////////////////////////////////////////////////////////////////////////////// #include <ork/pch.h> #include <ork/file/cas.inl> #include <ork/application/application.h> #include <ork/math/plane.h> #include <ork/kernel/spawner.h> #include <ork/kernel/string/deco.inl> /////////////////////////////////////////////////////////////////////////////// #include <ork/lev2/gfx/meshutil/meshutil.h> #include <ork/lev2/gfx/meshutil/clusterizer.h> #include <ork/lev2/gfx/material_pbr.inl> /////////////////////////////////////////////////////////////////////////////// #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/pbrmaterial.h> #include <assimp/material.h> /////////////////////////////////////////////////////////////////////////////// namespace ork::meshutil { /////////////////////////////////////////////////////////////////////////////// inline uint32_t assimpImportFlags() { uint32_t flags = aiProcessPreset_TargetRealtime_MaxQuality | // aiProcess_LimitBoneWeights | // // aiProcess_GenNormals | // aiProcess_CalcTangentSpace | // aiProcess_RemoveRedundantMaterials; // aiProcess_MakeLeftHanded return flags; } /////////////////////////////////////////////////////////////////////////////// inline fmtx4 convertMatrix44(const aiMatrix4x4& inp) { fmtx4 rval; for (int i = 0; i < 16; i++) { int x = i % 4; int y = i / 4; rval.SetElemXY(x, y, inp[y][x]); } return rval; } /////////////////////////////////////////////////////////////////////////////// inline void get_bounding_box_for_node(const aiScene* scene, const aiNode* nd, aiVector3D& min, aiVector3D& max, aiMatrix4x4& trafo) { aiMatrix4x4 prev; unsigned int n = 0, t; prev = trafo; aiMultiplyMatrix4(&trafo, &nd->mTransformation); for (; n < nd->mNumMeshes; ++n) { const aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]]; for (t = 0; t < mesh->mNumVertices; ++t) { aiVector3D tmp = mesh->mVertices[t]; aiTransformVecByMatrix4(&tmp, &trafo); min.x = std::min(min.x, tmp.x); min.y = std::min(min.y, tmp.y); min.z = std::min(min.z, tmp.z); max.x = std::max(max.x, tmp.x); max.y = std::max(max.y, tmp.y); max.z = std::max(max.z, tmp.z); } } for (n = 0; n < nd->mNumChildren; ++n) { get_bounding_box_for_node(scene, nd->mChildren[n], min, max, trafo); } trafo = prev; } /////////////////////////////////////////////////////////////////////////////// struct GltfMaterial { std::string _name; std::string _metallicAndRoughnessMap; std::string _colormap; std::string _normalmap; std::string _amboccmap; std::string _emissivemap; float _metallicFactor = 0.0f; float _roughnessFactor = 1.0f; fvec4 _baseColor = fvec4(1, 1, 1, 1); }; typedef std::map<int, GltfMaterial*> gltfmaterialmap_t; typedef std::map<std::string, ork::lev2::XgmSkelNode*> skelnodemap_t; /////////////////////////////////////////////////////////////////////////////// inline std::string remapSkelName(std::string inp) { // fixup blender naming auto remapped_name = ork::string::replaced(inp, "Armature_", ""); remapped_name = ork::string::replaced(remapped_name, "_", "."); return remapped_name; } /////////////////////////////////////////////////////////////////////////////// struct ParsedSkeleton { std::string _rootname; skelnodemap_t _xgmskelmap; bool _isSkinned = false; ////////////////////////////////////////////////////////////// inline lev2::XgmSkelNode* rootXgmSkelNode() { return _xgmskelmap.find(remapSkelName(_rootname))->second; } }; typedef std::shared_ptr<ParsedSkeleton> parsedskeletonptr_t; /////////////////////////////////////////////////////////////////////////////// inline parsedskeletonptr_t parseSkeleton(const aiScene* scene) { auto rval = std::make_shared<ParsedSkeleton>(); std::queue<aiNode*> nodestack; std::set<std::string> uniqskelnodeset; skelnodemap_t& xgmskelnodes = rval->_xgmskelmap; ///////////////////////////////////////////////// // get nodes ///////////////////////////////////////////////// nodestack = std::queue<aiNode*>(); nodestack.push(scene->mRootNode); rval->_rootname = scene->mRootNode->mName.data; deco::printf(fvec3::Green(), "//////////////////////////////////////////////////\n"); deco::printf(fvec3::Green(), "// Parsing Assimp Skeleton\n"); deco::printf(fvec3::Green(), "//////////////////////////////////////////////////\n"); deco::printf(fvec3::Green(), "// traversing nodes\n"); while (not nodestack.empty()) { auto n = nodestack.front(); nodestack.pop(); auto name = remapSkelName(n->mName.data); auto itb = uniqskelnodeset.find(name); if (itb == uniqskelnodeset.end()) { int index = uniqskelnodeset.size(); uniqskelnodeset.insert(name); auto xgmnode = new ork::lev2::XgmSkelNode(name); xgmnode->miSkelIndex = index; xgmskelnodes[name] = xgmnode; deco::printf(fvec3::White(), "aiNode<%d:%s> xgmnode<%p> remapped<%s>\n", index, n->mName.data, xgmnode, name.c_str()); xgmnode->_nodeMatrix = convertMatrix44(n->mTransformation); deco::printe(fvec3::Yellow(), xgmnode->_nodeMatrix.dump4x3(), true); } for (int i = 0; i < n->mNumChildren; ++i) { nodestack.push(n->mChildren[i]); } } ///////////////////////////////////////////////// // get bones ///////////////////////////////////////////////// deco::printf(fvec3::Green(), "// traversing bones\n"); nodestack = std::queue<aiNode*>(); nodestack.push(scene->mRootNode); while (not nodestack.empty()) { auto n = nodestack.front(); nodestack.pop(); for (int m = 0; m < n->mNumMeshes; ++m) { const aiMesh* mesh = scene->mMeshes[n->mMeshes[m]]; for (int b = 0; b < mesh->mNumBones; b++) { auto bone = mesh->mBones[b]; auto bonename = remapSkelName(bone->mName.data); auto itb = xgmskelnodes.find(bonename); OrkAssert(itb != xgmskelnodes.end()); if (itb != xgmskelnodes.end()) { auto xgmnode = itb->second; if (false == xgmnode->_varmap["visited_bone"].isA<bool>()) { xgmnode->_varmap["visited_bone"].set<bool>(true); xgmnode->_assimpOffsetMatrix = convertMatrix44(bone->mOffsetMatrix); rval->_isSkinned = true; } } } } for (int i = 0; i < n->mNumChildren; ++i) { nodestack.push(n->mChildren[i]); } } ///////////////////////////////////////////////// // set parents ///////////////////////////////////////////////// deco::printf(fvec3::Green(), "// creating xgm topology\n"); nodestack = std::queue<aiNode*>(); nodestack.push(scene->mRootNode); while (not nodestack.empty()) { auto p = nodestack.front(); nodestack.pop(); ////////////////////////////// auto itp = xgmskelnodes.find(remapSkelName(p->mName.data)); OrkAssert(itp != xgmskelnodes.end()); auto pskelnode = itp->second; // fmtx4 pmtx = pskelnode->bindMatrix(); // deco::printf(fvec3::White(), "pskelnode<%s> %s\n", pskelnode->_name.c_str(), pskelnode->_jointMatrix.dump().c_str()); // deco::printf(fvec3::White(), "pskelnode<%s> %s\n", pskelnode->_name.c_str(), pmtx.dump().c_str()); ////////////////////////////// for (int i = 0; i < p->mNumChildren; ++i) { auto c = p->mChildren[i]; auto itc = xgmskelnodes.find(remapSkelName(c->mName.data)); OrkAssert(itc != xgmskelnodes.end()); auto cskelnode = itc->second; if (false == cskelnode->_varmap["visited_2nd"].isA<bool>()) { cskelnode->_varmap["visited_2nd"].set<bool>(true); nodestack.push(c); cskelnode->_parent = pskelnode; pskelnode->mChildren.push_back(cskelnode); } } ///////////////////////////////////////////////// } // while (not nodestack.empty()) ///////////////////////////////////////////////// auto root = rval->rootXgmSkelNode(); root->_jointMatrix = root->_assimpOffsetMatrix.inverse(); ///////////////////////////////////////////////// // set joints matrices from nodes ///////////////////////////////////////////////// root->visitHierarchy([root](lev2::XgmSkelNode* node) { fmtx4 Bc = node->concatenatednode2(); auto par = node->_parent; fmtx4 Bp = par ? par->concatenatednode2() : fmtx4::Identity(); fmtx4 J; J.CorrectionMatrix(Bp, Bc); J = Bp.inverse() * Bc; node->_jointMatrix = J; }); ///////////////////////////////////////////////// // set inversebind pose (from nodes) ///////////////////////////////////////////////// root->visitHierarchy([root](lev2::XgmSkelNode* node) { node->_bindMatrixInverse = node->concatenated().inverse(); }); ///////////////////////////////////////////////// // debug dump ///////////////////////////////////////////////// deco::printf(fvec3::Green(), "// result debug dump\n"); root->visitHierarchy([root](lev2::XgmSkelNode* node) { fmtx4 ASSO = node->_assimpOffsetMatrix; fmtx4 N = node->_nodeMatrix; fmtx4 K = node->concatenatednode(); // object space fmtx4 K2 = node->concatenatednode2(); // object space fmtx4 Bi = node->_bindMatrixInverse; fmtx4 Bc = node->bindMatrix(); auto par = node->_parent; fmtx4 Bp = par ? par->bindMatrix() : fmtx4::Identity(); fmtx4 J = node->_jointMatrix; fmtx4 Jk = node->concatenated(); // object space fmtx4 Ji = J.inverse(); fmtx4 D = Bp * J; auto n = node->_name; deco::printe(fvec3::White(), n + ".ASSO: " + ASSO.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".N: " + N.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".J: " + J.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".K: " + K.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".K2: " + K2.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Bi: " + Bi.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Bc: " + Bc.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Bp: " + Bp.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Ji: " + Ji.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Jk: " + Jk.dump4x3cn(), true); deco::printe(fvec3::White(), n + ".Bp*J: " + D.dump4x3cn(), true); printf("\n"); }); ///////////////////////////////////////////////// // bool fixup_applied = root->applyCentimeterToMeterScale(); // OrkAssert(false); return rval; } // bone len<1.998> // bone.1 len<1.42> // bone.2 len<1.45> // bone.3 len<1.18> /////////////////////////////////////////////////////////////////////////////// } // namespace ork::meshutil
35.292605
124
0.503553
[ "mesh", "object" ]
8458ea32ca4e21e75de808ed12e6cb6b4e7998f6
13,396
cc
C++
model/addons/PhysiBoSS/MaBoSS-env-2.0/engine/src/FinalStateSimulationEngine.cc
bsc-life/spheroid-tnf-v2-emews
04a6ae2d6620df7700271f113a45379f39f88c41
[ "BSD-3-Clause" ]
6
2020-11-11T08:45:12.000Z
2021-09-15T14:31:07.000Z
data/PhysiBoSSv2/addons/PhysiBoSS/MaBoSS-env-2.0/engine/src/FinalStateSimulationEngine.cc
VasilisStavr/spheroid-tnf-v2-emews
74a28becd075f9596104345b4775f9b1ddfe9ec0
[ "BSD-3-Clause" ]
null
null
null
data/PhysiBoSSv2/addons/PhysiBoSS/MaBoSS-env-2.0/engine/src/FinalStateSimulationEngine.cc
VasilisStavr/spheroid-tnf-v2-emews
74a28becd075f9596104345b4775f9b1ddfe9ec0
[ "BSD-3-Clause" ]
2
2021-05-30T14:33:46.000Z
2021-07-16T09:30:19.000Z
/* MaBoSS (Markov Boolean Stochastic Simulator) Copyright (C) 2011-2018 Institut Curie, 26 rue d'Ulm, Paris, France MaBoSS 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. MaBoSS 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 */ /* Module: FinalStateSimulationEngine.cc Authors: Eric Viara <viara@sysra.com> Gautier Stoll <gautier.stoll@curie.fr> Date: January-March 2011 */ #include "FinalStateSimulationEngine.h" #include "Probe.h" #include "Utils.h" #include <stdlib.h> #include <math.h> #include <iomanip> #include <iostream> const std::string FinalStateSimulationEngine::VERSION = "1.0.0"; FinalStateSimulationEngine::FinalStateSimulationEngine(Network* network, RunConfig* runconfig) : network(network), runconfig(runconfig), time_tick(runconfig->getTimeTick()), max_time(runconfig->getMaxTime()), sample_count(runconfig->getSampleCount()), discrete_time(runconfig->isDiscreteTime()), thread_count(runconfig->getThreadCount()) { if (thread_count > sample_count) { thread_count = sample_count; } if (thread_count > 1 && !runconfig->getRandomGeneratorFactory()->isThreadSafe()) { std::cerr << "Warning: non reentrant random, may not work properly in multi-threaded mode\n"; } const std::vector<Node*>& nodes = network->getNodes(); std::vector<Node*>::const_iterator begin = nodes.begin(); std::vector<Node*>::const_iterator end = nodes.end(); refnode_count = 0; while (begin != end) { Node* node = *begin; if (node->isInternal()) { has_internal = true; internal_state.setNodeState(node, true); // std::cout << "Node " << node->getLabel() << " is internal, internal state is "; // internal_state.displayOneLine(std::cout, network); // std::cout << std::endl; } if (node->isReference()) { reference_state.setNodeState(node, node->getReferenceState()); refnode_count++; } ++begin; } sample_count_per_thread.resize(thread_count); unsigned int count = sample_count / thread_count; unsigned int firstcount = count + sample_count - count * thread_count; for (unsigned int nn = 0; nn < thread_count; ++nn) { sample_count_per_thread[nn] = (nn == 0 ? firstcount : count); } } NodeIndex FinalStateSimulationEngine::getTargetNode(RandomGenerator* random_generator, const MAP<NodeIndex, double>& nodeTransitionRates, double total_rate) const { double U_rand2 = random_generator->generate(); double random_rate = U_rand2 * total_rate; MAP<NodeIndex, double>::const_iterator begin = nodeTransitionRates.begin(); MAP<NodeIndex, double>::const_iterator end = nodeTransitionRates.end(); NodeIndex node_idx = INVALID_NODE_INDEX; while (begin != end && random_rate > 0.) { node_idx = (*begin).first; double rate = (*begin).second; random_rate -= rate; ++begin; } assert(node_idx != INVALID_NODE_INDEX); assert(network->getNode(node_idx)->getIndex() == node_idx); return node_idx; } struct FinalStateArgWrapper { FinalStateSimulationEngine* mabest; unsigned int start_count_thread; unsigned int sample_count_thread; RandomGeneratorFactory* randgen_factory; int seed; STATE_MAP<NetworkState_Impl, unsigned int>* final_state_map; std::ostream* output_traj; FinalStateArgWrapper(FinalStateSimulationEngine* mabest, unsigned int start_count_thread, unsigned int sample_count_thread, RandomGeneratorFactory* randgen_factory, int seed, STATE_MAP<NetworkState_Impl, unsigned int>* final_state_map, std::ostream* output_traj) : mabest(mabest), start_count_thread(start_count_thread), sample_count_thread(sample_count_thread), randgen_factory(randgen_factory), seed(seed), final_state_map(final_state_map), output_traj(output_traj) { } }; void* FinalStateSimulationEngine::threadWrapper(void *arg) { FinalStateArgWrapper* warg = (FinalStateArgWrapper*)arg; try { warg->mabest->runThread(warg->start_count_thread, warg->sample_count_thread, warg->randgen_factory, warg->seed, warg->final_state_map, warg->output_traj); } catch(const BNException& e) { std::cerr << e; } return NULL; } void FinalStateSimulationEngine::runThread(unsigned int start_count_thread, unsigned int sample_count_thread, RandomGeneratorFactory* randgen_factory, int seed, STATE_MAP<NetworkState_Impl, unsigned int>* final_state_map, std::ostream* output_traj) { const std::vector<Node*>& nodes = network->getNodes(); std::vector<Node*>::const_iterator begin = nodes.begin(); std::vector<Node*>::const_iterator end = nodes.end(); NetworkState network_state; RandomGenerator* random_generator = randgen_factory->generateRandomGenerator(seed); for (unsigned int nn = 0; nn < sample_count_thread; ++nn) { random_generator->setSeed(seed+start_count_thread+nn); network->initStates(network_state, random_generator); double tm = 0.; unsigned int step = 0; if (NULL != output_traj) { (*output_traj) << "\nTrajectory #" << (nn+1) << '\n'; (*output_traj) << " istate\t"; network_state.displayOneLine(*output_traj, network); (*output_traj) << '\n'; } while (tm < max_time) { double total_rate = 0.; MAP<NodeIndex, double> nodeTransitionRates; begin = nodes.begin(); while (begin != end) { Node* node = *begin; NodeIndex node_idx = node->getIndex(); if (node->getNodeState(network_state)) { double r_down = node->getRateDown(network_state); if (r_down != 0.0) { total_rate += r_down; nodeTransitionRates[node_idx] = r_down; } } else { double r_up = node->getRateUp(network_state); if (r_up != 0.0) { total_rate += r_up; nodeTransitionRates[node_idx] = r_up; } } ++begin; } if (total_rate == 0) { tm = max_time; } else { double transition_time ; if (discrete_time) { transition_time = time_tick; } else { double U_rand1 = random_generator->generate(); transition_time = -log(U_rand1) / total_rate; } tm += transition_time; } if (NULL != output_traj) { (*output_traj) << std::setprecision(10) << tm << '\t'; network_state.displayOneLine(*output_traj, network); } if (tm >= max_time) { break; } NodeIndex node_idx = getTargetNode(random_generator, nodeTransitionRates, total_rate); network_state.flipState(network->getNode(node_idx)); step++; } NetworkState_Impl final_state = network_state.getState(); if (has_internal) { final_state &= ~internal_state.getState(); } if (final_state_map->find(final_state) == final_state_map->end()) { (*final_state_map)[final_state] = 1; } else { (*final_state_map)[final_state]++; } } delete random_generator; } void FinalStateSimulationEngine::run(std::ostream* output_traj) { pthread_t* tid = new pthread_t[thread_count]; RandomGeneratorFactory* randgen_factory = runconfig->getRandomGeneratorFactory(); int seed = runconfig->getSeedPseudoRandom(); unsigned int start_sample_count = 0; Probe probe; for (unsigned int nn = 0; nn < thread_count; ++nn) { STATE_MAP<NetworkState_Impl, unsigned int>* final_states_map = new STATE_MAP<NetworkState_Impl, unsigned int>(); final_states_map_v.push_back(final_states_map); FinalStateArgWrapper* warg = new FinalStateArgWrapper(this, start_sample_count, sample_count_per_thread[nn], randgen_factory, seed, final_states_map, output_traj); pthread_create(&tid[nn], NULL, FinalStateSimulationEngine::threadWrapper, warg); arg_wrapper_v.push_back(warg); start_sample_count += sample_count_per_thread[nn]; } for (unsigned int nn = 0; nn < thread_count; ++nn) { pthread_join(tid[nn], NULL); } epilogue(); delete [] tid; } STATE_MAP<NetworkState_Impl, unsigned int>* FinalStateSimulationEngine::mergeFinalStateMaps() { if (1 == final_states_map_v.size()) { return new STATE_MAP<NetworkState_Impl, unsigned int>(*final_states_map_v[0]); } STATE_MAP<NetworkState_Impl, unsigned int>* final_states_map = new STATE_MAP<NetworkState_Impl, unsigned int>(); std::vector<STATE_MAP<NetworkState_Impl, unsigned int>*>::iterator begin = final_states_map_v.begin(); std::vector<STATE_MAP<NetworkState_Impl, unsigned int>*>::iterator end = final_states_map_v.end(); while (begin != end) { STATE_MAP<NetworkState_Impl, unsigned int>* fp_map = *begin; STATE_MAP<NetworkState_Impl, unsigned int>::const_iterator b = fp_map->begin(); STATE_MAP<NetworkState_Impl, unsigned int>::const_iterator e = fp_map->end(); while (b != e) { NetworkState_Impl state = (*b).first; if (final_states_map->find(state) == final_states_map->end()) { (*final_states_map)[state] = (*b).second; } else { (*final_states_map)[state] += (*b).second; } ++b; } ++begin; } return final_states_map; } void FinalStateSimulationEngine::epilogue() { STATE_MAP<NetworkState_Impl, unsigned int>* merged_final_states_map = mergeFinalStateMaps(); STATE_MAP<NetworkState_Impl, unsigned int>::const_iterator b = merged_final_states_map->begin(); STATE_MAP<NetworkState_Impl, unsigned int>::const_iterator e = merged_final_states_map->end(); while (b != e) { final_states[NetworkState((*b).first).getState()] = ((double) (*b).second)/sample_count; ++b; } delete merged_final_states_map; } FinalStateSimulationEngine::~FinalStateSimulationEngine() { for (auto t_arg_wrapper: arg_wrapper_v) delete t_arg_wrapper; } void FinalStateSimulationEngine::displayFinal(std::ostream& output_final, bool hexfloat) const { for (auto final_state: final_states) { if (hexfloat) output_final << std::setprecision(6) << fmthexdouble(final_state.second); else output_final << std::setprecision(6) << final_state.second << "\t"; NetworkState(final_state.first).displayOneLine(output_final, network); output_final << "\n"; } } const STATE_MAP<Node*, double> FinalStateSimulationEngine::getFinalNodes() const { STATE_MAP<Node *, double> node_dist; for (auto& node: network->getNodes()) { if (!(node->isInternal())) { double dist = 0; for (auto final_state: final_states) { NetworkState state = final_state.first; dist += final_state.second * ((double) state.getNodeState(node)); } node_dist[node] = dist; } } return node_dist; } #ifdef PYTHON_API PyObject* FinalStateSimulationEngine::getNumpyLastStatesDists() const { npy_intp dims[2] = {(npy_intp) 1, (npy_intp) final_states.size()}; PyArrayObject* result = (PyArrayObject *) PyArray_ZEROS(2,dims,NPY_DOUBLE, 0); PyObject* list_states = PyList_New(final_states.size()); int i=0; for(auto& final_state: final_states) { void* ptr = PyArray_GETPTR2(result, 0, i); PyArray_SETITEM( result, (char*) ptr, PyFloat_FromDouble(final_state.second) ); PyList_SetItem( list_states, i, PyUnicode_FromString(NetworkState(final_state.first).getName(network).c_str()) ); i++; } PyObject* timepoints = PyList_New(1); PyList_SetItem( timepoints, 0, PyFloat_FromDouble(max_time) ); return PyTuple_Pack(3, PyArray_Return(result), list_states, timepoints); } std::vector<Node*> FinalStateSimulationEngine::getNodes() const { std::vector<Node*> result_nodes; for (auto node: network->getNodes()) { if (!node->isInternal()) result_nodes.push_back(node); } return result_nodes; } PyObject* FinalStateSimulationEngine::getNumpyLastNodesDists() const { std::vector<Node*> output_nodes = getNodes(); npy_intp dims[2] = {(npy_intp) 1, (npy_intp) output_nodes.size()}; PyArrayObject* result = (PyArrayObject *) PyArray_ZEROS(2,dims,NPY_DOUBLE, 0); PyObject* list_nodes = PyList_New(output_nodes.size()); int i=0; for (auto node: output_nodes) { for(auto& final_state: final_states) { if (NetworkState(final_state.first).getNodeState(node)){ void* ptr_val = PyArray_GETPTR2(result, 0, i); PyArray_SETITEM( result, (char*) ptr_val, PyFloat_FromDouble( PyFloat_AsDouble(PyArray_GETITEM(result, (char*) ptr_val)) + final_state.second ) ); } } PyList_SetItem(list_nodes, i, PyUnicode_FromString(node->getLabel().c_str())); i++; } PyObject* timepoints = PyList_New(1); PyList_SetItem( timepoints, 0, PyFloat_FromDouble(max_time) ); return PyTuple_Pack(3, PyArray_Return(result), list_nodes, timepoints); } #endif
32.279518
266
0.688414
[ "vector" ]
845c958b7360e97229fd28321db719abfc1f138d
2,631
cpp
C++
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/cfmodels/MSCFModel_KraussPS.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/cfmodels/MSCFModel_KraussPS.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/cfmodels/MSCFModel_KraussPS.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file MSCFModel_KraussPS.cpp /// @author Tobias Mayer /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @author Laura Bieker /// @date Mon, 04 Aug 2009 /// // Krauss car-following model, changing accel and speed by slope /****************************************************************************/ #include <config.h> #include <utils/geom/GeomHelper.h> #include <microsim/MSVehicle.h> #include <microsim/MSLane.h> #include "MSCFModel_KraussPS.h" // =========================================================================== // method definitions // =========================================================================== MSCFModel_KraussPS::MSCFModel_KraussPS(const MSVehicleType* vtype) : MSCFModel_Krauss(vtype) { } MSCFModel_KraussPS::~MSCFModel_KraussPS() {} double MSCFModel_KraussPS::maxNextSpeed(double speed, const MSVehicle* const veh) const { const double gravity = 9.80665; const double aMax = MAX2(0., getMaxAccel() - gravity * sin(DEG2RAD(veh->getSlope()))); // assuming drag force is proportional to the square of speed const double vMax = MAX2( sqrt(aMax / getMaxAccel()) * myType->getMaxSpeed(), // prevent emergency braking when inclination changes suddenly (momentum) speed - ACCEL2SPEED(getMaxDecel())); return MAX2( // prevent stalling at low speed getMaxAccel() / 2, MIN2(speed + ACCEL2SPEED(aMax), vMax)); } MSCFModel* MSCFModel_KraussPS::duplicate(const MSVehicleType* vtype) const { return new MSCFModel_KraussPS(vtype); } /****************************************************************************/
39.863636
101
0.571646
[ "model" ]
8463f92068ed4a19b2df023b177b0cc1f8d951ad
929
cpp
C++
solution107.cpp
white-shark/leetcode-cpp
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
31
2016-08-18T16:30:59.000Z
2022-02-15T11:21:39.000Z
solution107.cpp
runguanner/Leetcode
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
null
null
null
solution107.cpp
runguanner/Leetcode
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
22
2017-07-17T07:30:00.000Z
2022-01-24T08:37:15.000Z
/** * Binary Tree Level Order Traversal II * * cpselvis(cpselvis@gmail.com) * September 4th, 2016 */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> ret; vector<TreeNode*> nodes; if (root != NULL) { nodes.push_back(root); dfs(nodes, ret); } reverse(ret.begin(), ret.end()); return ret; } void dfs(vector<TreeNode*> &nodes, vector<vector<int>> &ret) { vector<int> vals; vector<TreeNode*> childNodes; if (nodes.size() == 0) { return; } for (int i = 0; i < nodes.size(); i ++) { if (nodes[i] != NULL) { vals.push_back(nodes[i] -> val); if (nodes[i] -> left != NULL) { childNodes.push_back(nodes[i] -> left); } if (nodes[i] -> right != NULL) { childNodes.push_back(nodes[i] -> right); } } } ret.push_back(vals); dfs(childNodes, ret); } };
18.959184
62
0.55436
[ "vector" ]
84648ee1aa9839784bc6202fd4a399eda36953fe
56,216
cpp
C++
Source/source/load.cpp
Neocraftz1553/Pikifen
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
[ "MIT" ]
null
null
null
Source/source/load.cpp
Neocraftz1553/Pikifen
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
[ "MIT" ]
null
null
null
Source/source/load.cpp
Neocraftz1553/Pikifen
e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2
[ "MIT" ]
null
null
null
/* * Copyright (c) Andre 'Espyo' Silva 2013. * The following source file belongs to the open-source project Pikifen. * Please read the included README and LICENSE files for more information. * Pikmin is copyright (c) Nintendo. * * === FILE DESCRIPTION === * Data loading and unloading functions. */ #include <algorithm> #include "load.h" #include "const.h" #include "drawing.h" #include "functions.h" #include "game.h" #include "init.h" #include "utils/string_utils.h" using std::set; /* ---------------------------------------------------------------------------- * Loads an area into memory. * name: * Name of the area's folder. * load_for_editor: * If true, skips loading some things that the area editor won't need. * from_backup: * If true, load from a backup, if any. */ void load_area( const string &name, const bool load_for_editor, const bool from_backup ) { if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Data"); } game.cur_area_data.clear(); string geometry_file_name; string data_file_name; string sanitized_area_name = sanitize_file_name(name); if(from_backup) { geometry_file_name = USER_AREA_DATA_FOLDER_PATH + "/" + sanitized_area_name + "/Geometry_backup.txt"; data_file_name = USER_AREA_DATA_FOLDER_PATH + "/" + sanitized_area_name + "/Data_backup.txt"; } else { geometry_file_name = AREAS_FOLDER_PATH + "/" + sanitized_area_name + "/Geometry.txt"; data_file_name = AREAS_FOLDER_PATH + "/" + sanitized_area_name + "/Data.txt"; } //First, load the area's configuration data. data_node data_file(data_file_name); reader_setter rs(&data_file); data_node* weather_node = NULL; rs.set("name", game.cur_area_data.name); rs.set("subtitle", game.cur_area_data.subtitle); rs.set("maker", game.cur_area_data.maker); rs.set("version", game.cur_area_data.version); rs.set("notes", game.cur_area_data.notes); rs.set("spray_amounts", game.cur_area_data.spray_amounts); rs.set("weather", game.cur_area_data.weather_name, &weather_node); rs.set("bg_bmp", game.cur_area_data.bg_bmp_file_name); rs.set("bg_color", game.cur_area_data.bg_color); rs.set("bg_dist", game.cur_area_data.bg_dist); rs.set("bg_zoom", game.cur_area_data.bg_bmp_zoom); if(game.loading_text_bmp) al_destroy_bitmap(game.loading_text_bmp); if(game.loading_subtext_bmp) al_destroy_bitmap(game.loading_subtext_bmp); game.loading_text_bmp = NULL; game.loading_subtext_bmp = NULL; if(game.perf_mon) { game.perf_mon->finish_measurement(); } draw_loading_screen( game.cur_area_data.name, game.cur_area_data.subtitle, 1.0 ); al_flip_display(); if(!load_for_editor) { if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Initial assets"); } if(game.cur_area_data.weather_name.empty()) { game.cur_area_data.weather_condition = weather(); } else if( game.weather_conditions.find(game.cur_area_data.weather_name) == game.weather_conditions.end() ) { log_error( "Area " + name + " refers to an unknown weather condition, \"" + game.cur_area_data.weather_name + "\"!", weather_node ); game.cur_area_data.weather_condition = weather(); } else { game.cur_area_data.weather_condition = game.weather_conditions[game.cur_area_data.weather_name]; } } if(!load_for_editor && !game.cur_area_data.bg_bmp_file_name.empty()) { game.cur_area_data.bg_bmp = game.textures.get(game.cur_area_data.bg_bmp_file_name, &data_file); } if(!load_for_editor && game.perf_mon) { game.perf_mon->finish_measurement(); } //Time to load the geometry. data_node geometry_file = load_data_file(geometry_file_name); //Vertexes. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Vertexes"); } size_t n_vertexes = geometry_file.get_child_by_name( "vertexes" )->get_nr_of_children_by_name("v"); for(size_t v = 0; v < n_vertexes; ++v) { data_node* vertex_data = geometry_file.get_child_by_name( "vertexes" )->get_child_by_name("v", v); vector<string> words = split(vertex_data->value); if(words.size() == 2) { game.cur_area_data.vertexes.push_back( new vertex(s2f(words[0]), s2f(words[1])) ); } } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Edges. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Edges"); } size_t n_edges = geometry_file.get_child_by_name( "edges" )->get_nr_of_children_by_name("e"); for(size_t e = 0; e < n_edges; ++e) { data_node* edge_data = geometry_file.get_child_by_name( "edges" )->get_child_by_name("e", e); edge* new_edge = new edge(); vector<string> s_nrs = split(edge_data->get_child_by_name("s")->value); if(s_nrs.size() < 2) s_nrs.insert(s_nrs.end(), 2, "-1"); for(size_t s = 0; s < 2; ++s) { if(s_nrs[s] == "-1") new_edge->sector_nrs[s] = INVALID; else new_edge->sector_nrs[s] = s2i(s_nrs[s]); } vector<string> v_nrs = split(edge_data->get_child_by_name("v")->value); if(v_nrs.size() < 2) v_nrs.insert(v_nrs.end(), 2, "0"); new_edge->vertex_nrs[0] = s2i(v_nrs[0]); new_edge->vertex_nrs[1] = s2i(v_nrs[1]); game.cur_area_data.edges.push_back(new_edge); } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Sectors. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Sectors"); } size_t n_sectors = geometry_file.get_child_by_name( "sectors" )->get_nr_of_children_by_name("s"); for(size_t s = 0; s < n_sectors; ++s) { data_node* sector_data = geometry_file.get_child_by_name( "sectors" )->get_child_by_name("s", s); sector* new_sector = new sector(); new_sector->type = game.sector_types.get_nr( sector_data->get_child_by_name("type")->value ); if(new_sector->type == 255) new_sector->type = SECTOR_TYPE_NORMAL; new_sector->is_bottomless_pit = s2b( sector_data->get_child_by_name( "is_bottomless_pit" )->get_value_or_default("false") ); new_sector->brightness = s2f( sector_data->get_child_by_name( "brightness" )->get_value_or_default(i2s(DEF_SECTOR_BRIGHTNESS)) ); new_sector->tag = sector_data->get_child_by_name("tag")->value; new_sector->z = s2f(sector_data->get_child_by_name("z")->value); new_sector->fade = s2b(sector_data->get_child_by_name("fade")->value); new_sector->always_cast_shadow = s2b( sector_data->get_child_by_name("always_cast_shadow")->value ); new_sector->texture_info.file_name = sector_data->get_child_by_name("texture")->value; new_sector->texture_info.rot = s2f(sector_data->get_child_by_name("texture_rotate")->value); vector<string> scales = split(sector_data->get_child_by_name("texture_scale")->value); if(scales.size() >= 2) { new_sector->texture_info.scale.x = s2f(scales[0]); new_sector->texture_info.scale.y = s2f(scales[1]); } vector<string> translations = split(sector_data->get_child_by_name("texture_trans")->value); if(translations.size() >= 2) { new_sector->texture_info.translation.x = s2f(translations[0]); new_sector->texture_info.translation.y = s2f(translations[1]); } new_sector->texture_info.tint = s2c( sector_data->get_child_by_name("texture_tint")-> get_value_or_default("255 255 255") ); if(!new_sector->fade && !new_sector->is_bottomless_pit) { new_sector->texture_info.bitmap = game.textures.get(new_sector->texture_info.file_name, NULL); } data_node* hazards_node = sector_data->get_child_by_name("hazards"); vector<string> hazards_strs = semicolon_list_to_vector(hazards_node->value); for(size_t h = 0; h < hazards_strs.size(); ++h) { string hazard_name = hazards_strs[h]; if(game.hazards.find(hazard_name) == game.hazards.end()) { log_error( "Unknown hazard \"" + hazard_name + "\"!", hazards_node ); } else { new_sector->hazards.push_back(&(game.hazards[hazard_name])); } } new_sector->hazards_str = hazards_node->value; new_sector->hazard_floor = s2b( sector_data->get_child_by_name( "hazards_floor" )->get_value_or_default("true") ); game.cur_area_data.sectors.push_back(new_sector); } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Mobs. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Object generators"); } vector<std::pair<size_t, size_t> > mob_links_buffer; size_t n_mobs = geometry_file.get_child_by_name("mobs")->get_nr_of_children(); for(size_t m = 0; m < n_mobs; ++m) { data_node* mob_node = geometry_file.get_child_by_name("mobs")->get_child(m); mob_gen* mob_ptr = new mob_gen(); mob_ptr->pos = s2p(mob_node->get_child_by_name("p")->value); mob_ptr->angle = s2f( mob_node->get_child_by_name("angle")->get_value_or_default("0") ); mob_ptr->vars = mob_node->get_child_by_name("vars")->value; mob_ptr->category = game.mob_categories.get_from_name(mob_node->name); if(!mob_ptr->category) continue; string mt = mob_node->get_child_by_name("type")->value; mob_ptr->type = mob_ptr->category->get_type(mt); vector<string> link_strs = split(mob_node->get_child_by_name("links")->value); for(size_t l = 0; l < link_strs.size(); ++l) { mob_links_buffer.push_back(std::make_pair(m, s2i(link_strs[l]))); } bool problem = false; if(!mob_ptr->type && !load_for_editor) { //Error. log_error( "Unknown \"" + mob_ptr->category->name + "\" mob type \"" + mt + "\"!", mob_node ); problem = true; } if( ( mob_ptr->category->id == MOB_CATEGORY_NONE || mob_ptr->category->id == INVALID ) && !load_for_editor ) { log_error( "Unknown mob category \"" + mob_node->name + "\"!", mob_node ); mob_ptr->category = game.mob_categories.get(MOB_CATEGORY_NONE); problem = true; } if(!problem) { game.cur_area_data.mob_generators.push_back(mob_ptr); } else { delete mob_ptr; } } for(size_t l = 0; l < mob_links_buffer.size(); ++l) { size_t f = mob_links_buffer[l].first; size_t s = mob_links_buffer[l].second; game.cur_area_data.mob_generators[f]->links.push_back( game.cur_area_data.mob_generators[s] ); game.cur_area_data.mob_generators[f]->link_nrs.push_back(s); } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Path stops. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Paths"); } size_t n_stops = geometry_file.get_child_by_name("path_stops")->get_nr_of_children(); for(size_t s = 0; s < n_stops; ++s) { data_node* path_stop_node = geometry_file.get_child_by_name("path_stops")->get_child(s); path_stop* s_ptr = new path_stop(); vector<string> words = split(path_stop_node->get_child_by_name("pos")->value); s_ptr->pos.x = (words.size() >= 1 ? s2f(words[0]) : 0); s_ptr->pos.y = (words.size() >= 2 ? s2f(words[1]) : 0); data_node* links_node = path_stop_node->get_child_by_name("links"); size_t n_links = links_node->get_nr_of_children(); for(size_t l = 0; l < n_links; ++l) { data_node* link_node = links_node->get_child(l); path_link l_struct(NULL, INVALID); l_struct.end_nr = s2i(link_node->value); s_ptr->links.push_back(l_struct); } game.cur_area_data.path_stops.push_back(s_ptr); } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Tree shadows. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Tree shadows"); } size_t n_shadows = geometry_file.get_child_by_name("tree_shadows")->get_nr_of_children(); for(size_t s = 0; s < n_shadows; ++s) { data_node* shadow_node = geometry_file.get_child_by_name("tree_shadows")->get_child(s); tree_shadow* s_ptr = new tree_shadow(); vector<string> words = split(shadow_node->get_child_by_name("pos")->value); s_ptr->center.x = (words.size() >= 1 ? s2f(words[0]) : 0); s_ptr->center.y = (words.size() >= 2 ? s2f(words[1]) : 0); words = split(shadow_node->get_child_by_name("size")->value); s_ptr->size.x = (words.size() >= 1 ? s2f(words[0]) : 0); s_ptr->size.y = (words.size() >= 2 ? s2f(words[1]) : 0); s_ptr->angle = s2f( shadow_node->get_child_by_name( "angle" )->get_value_or_default("0") ); s_ptr->alpha = s2i( shadow_node->get_child_by_name( "alpha" )->get_value_or_default("255") ); s_ptr->file_name = shadow_node->get_child_by_name("file")->value; s_ptr->bitmap = game.textures.get(s_ptr->file_name, NULL); words = split(shadow_node->get_child_by_name("sway")->value); s_ptr->sway.x = (words.size() >= 1 ? s2f(words[0]) : 0); s_ptr->sway.y = (words.size() >= 2 ? s2f(words[1]) : 0); if(s_ptr->bitmap == game.bmp_error && !load_for_editor) { log_error( "Unknown tree shadow texture \"" + s_ptr->file_name + "\"!", shadow_node ); } game.cur_area_data.tree_shadows.push_back(s_ptr); } if(game.perf_mon) { game.perf_mon->finish_measurement(); } //Set up stuff. if(game.perf_mon) { game.perf_mon->start_measurement("Area -- Geometry calculations"); } for(size_t e = 0; e < game.cur_area_data.edges.size(); ++e) { game.cur_area_data.fix_edge_pointers( game.cur_area_data.edges[e] ); } for(size_t s = 0; s < game.cur_area_data.sectors.size(); ++s) { game.cur_area_data.connect_sector_edges( game.cur_area_data.sectors[s] ); } for(size_t v = 0; v < game.cur_area_data.vertexes.size(); ++v) { game.cur_area_data.connect_vertex_edges( game.cur_area_data.vertexes[v] ); } for(size_t s = 0; s < game.cur_area_data.path_stops.size(); ++s) { game.cur_area_data.fix_path_stop_pointers( game.cur_area_data.path_stops[s] ); } for(size_t s = 0; s < game.cur_area_data.path_stops.size(); ++s) { game.cur_area_data.path_stops[s]->calculate_dists(); } if(!load_for_editor) { //Fade sectors that also fade brightness should be //at midway between the two neighbors. for(size_t s = 0; s < game.cur_area_data.sectors.size(); ++s) { sector* s_ptr = game.cur_area_data.sectors[s]; if(s_ptr->fade) { sector* n1 = NULL; sector* n2 = NULL; s_ptr->get_texture_merge_sectors(&n1, &n2); if(n1 && n2) { s_ptr->brightness = (n1->brightness + n2->brightness) / 2; } } } } //Triangulate everything and save bounding boxes. set<edge*> lone_edges; for(size_t s = 0; s < game.cur_area_data.sectors.size(); ++s) { sector* s_ptr = game.cur_area_data.sectors[s]; s_ptr->triangles.clear(); TRIANGULATION_ERRORS res = triangulate(s_ptr, &lone_edges, load_for_editor, false); if(res != TRIANGULATION_NO_ERROR && load_for_editor) { game.cur_area_data.problems.non_simples[s_ptr] = res; game.cur_area_data.problems.lone_edges.insert( lone_edges.begin(), lone_edges.end() ); } s_ptr->calculate_bounding_box(); } if(!load_for_editor) game.cur_area_data.generate_blockmap(); if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads asset file names. */ void load_asset_file_names() { data_node file(SYSTEM_ASSET_FILE_NAMES_FILE_PATH); game.asset_file_names.load(&file); } /* ---------------------------------------------------------------------------- * Loads a bitmap from the game's content. * file_name: * File name of the bitmap. * node: * If present, it will be used to report errors, if any. * report_error: * If false, omits error reporting. * error_bmp_on_error: * If true, returns the error bitmap in the case of an * error. Otherwise, returns NULL. * error_bmp_on_empty: * If true, returns the error bitmap in the case of an * empty file name. Otherwise, returns NULL. * path_from_root: * Normally, files are fetched from the images folder. * If this parameter is true, the path starts from the game's root. */ ALLEGRO_BITMAP* load_bmp( const string &file_name, data_node* node, const bool report_error, const bool error_bmp_on_error, const bool error_bmp_on_empty, const bool path_from_root ) { if(file_name.empty()) { if(error_bmp_on_empty) { return game.bmp_error; } else { return NULL; } } string base_dir = (path_from_root ? "" : (GRAPHICS_FOLDER_PATH + "/")); ALLEGRO_BITMAP* b = al_load_bitmap((base_dir + file_name).c_str()); if(!b) { if(report_error) { log_error("Could not open image " + file_name + "!", node); } if(error_bmp_on_error) { b = game.bmp_error; } } return b; } /* ---------------------------------------------------------------------------- * Loads the user-made particle generators. * load_resources: * If true, things like bitmaps and the like will be loaded as well. * If you don't need those, set this to false to make it load faster. */ void load_custom_particle_generators(const bool load_resources) { if(game.perf_mon) { game.perf_mon->start_measurement("Custom particle generators"); } vector<string> generator_files = folder_to_vector(PARTICLE_GENERATORS_FOLDER_PATH, false); for(size_t g = 0; g < generator_files.size(); ++g) { data_node file = load_data_file( PARTICLE_GENERATORS_FOLDER_PATH + "/" + generator_files[g] ); if(!file.file_was_opened) continue; data_node* p_node = file.get_child_by_name("base"); reader_setter grs(&file); reader_setter prs(p_node); string name_str; float emission_interval_float = 0.0f; size_t number_int = 1; string bitmap_str; data_node* bitmap_node = NULL; particle base_p; grs.set("name", name_str); grs.set("emission_interval", emission_interval_float); grs.set("number", number_int); prs.set("bitmap", bitmap_str, &bitmap_node); prs.set("duration", base_p.duration); prs.set("friction", base_p.friction); prs.set("gravity", base_p.gravity); prs.set("size_grow_speed", base_p.size_grow_speed); prs.set("size", base_p.size); prs.set("speed", base_p.speed); prs.set("color", base_p.color); if(bitmap_node) { if(load_resources) { base_p.bitmap = game.bitmaps.get( bitmap_str, bitmap_node ); } base_p.type = PARTICLE_TYPE_BITMAP; } else { base_p.type = PARTICLE_TYPE_CIRCLE; } base_p.time = base_p.duration; base_p.priority = PARTICLE_PRIORITY_MEDIUM; particle_generator new_pg(emission_interval_float, base_p, number_int); grs.set("number_deviation", new_pg.number_deviation); grs.set("duration_deviation", new_pg.duration_deviation); grs.set("friction_deviation", new_pg.friction_deviation); grs.set("gravity_deviation", new_pg.gravity_deviation); grs.set("size_deviation", new_pg.size_deviation); grs.set("pos_deviation", new_pg.pos_deviation); grs.set("speed_deviation", new_pg.speed_deviation); grs.set("angle", new_pg.angle); grs.set("angle_deviation", new_pg.angle_deviation); grs.set("total_speed", new_pg.total_speed); grs.set("total_speed_deviation", new_pg.total_speed_deviation); new_pg.angle = deg_to_rad(new_pg.angle); new_pg.angle_deviation = deg_to_rad(new_pg.angle_deviation); new_pg.id = MOB_PARTICLE_GENERATOR_STATUS + game.custom_particle_generators.size(); game.custom_particle_generators[name_str] = new_pg; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads a data file from the game's content. * file_name: * Name of the file. */ data_node load_data_file(const string &file_name) { data_node n = data_node(file_name); if(!n.file_was_opened) { log_error("Could not open data file " + file_name + "!"); } return n; } /* ---------------------------------------------------------------------------- * Loads the game's fonts. */ void load_fonts() { const int STANDARD_FONT_RANGES_SIZE = 2; int standard_font_ranges[STANDARD_FONT_RANGES_SIZE] = { 0x0020, 0x007E, //ASCII /*0x00A0, 0x00A1, //Non-breaking space and inverted ! 0x00BF, 0x00FF, //Inverted ? and European vowels and such*/ }; const int COUNTER_FONT_RANGES_SIZE = 6; int counter_font_ranges[COUNTER_FONT_RANGES_SIZE] = { 0x002D, 0x002D, //Dash 0x002F, 0x0039, //Slash and numbers 0x0078, 0x0078, //x }; const int VALUE_FONT_RANGES_SIZE = 6; int value_font_ranges[VALUE_FONT_RANGES_SIZE] = { 0x0024, 0x0024, //Dollar sign 0x002D, 0x002D, //Dash 0x0030, 0x0039, //Numbers }; //We can't load the fonts directly because we want to set the ranges. //So we load them into bitmaps first. //Main font. ALLEGRO_BITMAP* temp_font_bmp = load_bmp(game.asset_file_names.main_font); if(temp_font_bmp) { game.fonts.main = al_grab_font_from_bitmap( temp_font_bmp, STANDARD_FONT_RANGES_SIZE / 2, standard_font_ranges ); } al_destroy_bitmap(temp_font_bmp); //Area name font. temp_font_bmp = load_bmp(game.asset_file_names.area_name_font); if(temp_font_bmp) { game.fonts.area_name = al_grab_font_from_bitmap( temp_font_bmp, STANDARD_FONT_RANGES_SIZE / 2, standard_font_ranges ); } al_destroy_bitmap(temp_font_bmp); //Counter font. temp_font_bmp = load_bmp(game.asset_file_names.counter_font); if(temp_font_bmp) { game.fonts.counter = al_grab_font_from_bitmap( temp_font_bmp, COUNTER_FONT_RANGES_SIZE / 2, counter_font_ranges ); } al_destroy_bitmap(temp_font_bmp); //Value font. temp_font_bmp = load_bmp(game.asset_file_names.value_font); if(temp_font_bmp) { game.fonts.value = al_grab_font_from_bitmap( temp_font_bmp, VALUE_FONT_RANGES_SIZE / 2, value_font_ranges ); } al_destroy_bitmap(temp_font_bmp); game.fonts.builtin = al_create_builtin_font(); } /* ---------------------------------------------------------------------------- * Loads the game's configuration file. */ void load_game_config() { data_node file = load_data_file(CONFIG_FILE); game.config.load(&file); al_set_window_title(game.display, game.config.name.c_str()); } /* ---------------------------------------------------------------------------- * Loads the hazards from the game data. */ void load_hazards() { if(game.perf_mon) { game.perf_mon->start_measurement("Hazards"); } vector<string> hazard_files = folder_to_vector(HAZARDS_FOLDER_PATH, false); for(size_t h = 0; h < hazard_files.size(); ++h) { data_node file = load_data_file(HAZARDS_FOLDER_PATH + "/" + hazard_files[h]); if(!file.file_was_opened) continue; hazard new_h; reader_setter rs(&file); string effects_str; string liquid_str; data_node* effects_node = NULL; data_node* liquid_node = NULL; rs.set("name", new_h.name); rs.set("color", new_h.main_color); rs.set("effects", effects_str, &effects_node); rs.set("liquid", liquid_str, &liquid_node); if(effects_node) { vector<string> effects_strs = semicolon_list_to_vector(effects_str); for(size_t e = 0; e < effects_strs.size(); ++e) { string effect_name = effects_strs[e]; if( game.status_types.find(effect_name) == game.status_types.end() ) { log_error( "Unknown status effect \"" + effect_name + "\"!", effects_node ); } else { new_h.effects.push_back( game.status_types[effect_name] ); } } } if(liquid_node) { if(game.liquids.find(liquid_str) == game.liquids.end()) { log_error( "Unknown liquid \"" + liquid_str + "\"!", liquid_node ); } else { new_h.associated_liquid = game.liquids[liquid_str]; } } game.hazards[new_h.name] = new_h; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads the liquids from the game data. * load_resources: * If true, things like bitmaps and the like will be loaded as well. * If you don't need those, set this to false to make it load faster. */ void load_liquids(const bool load_resources) { if(game.perf_mon) { game.perf_mon->start_measurement("Liquid types"); } vector<string> liquid_files = folder_to_vector(LIQUIDS_FOLDER_PATH, false); for(size_t l = 0; l < liquid_files.size(); ++l) { data_node file = load_data_file(LIQUIDS_FOLDER_PATH + "/" + liquid_files[l]); if(!file.file_was_opened) continue; liquid* new_l = new liquid(); reader_setter rs(&file); string animation_str; rs.set("name", new_l->name); rs.set("animation", animation_str); rs.set("color", new_l->main_color); rs.set("surface_1_speed", new_l->surface_speed[0]); rs.set("surface_2_speed", new_l->surface_speed[0]); rs.set("surface_alpha", new_l->surface_alpha); if(load_resources) { data_node anim_file = load_data_file(ANIMATIONS_FOLDER_PATH + "/" + animation_str); new_l->anim_db = load_animation_database_from_file(&anim_file); if(!new_l->anim_db.animations.empty()) { new_l->anim_instance = animation_instance(&new_l->anim_db); new_l->anim_instance.cur_anim = new_l->anim_db.animations[0]; new_l->anim_instance.start(); } } game.liquids[new_l->name] = new_l; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads the maker tools from the tool config file. */ void load_maker_tools() { data_node file(MAKER_TOOLS_FILE_PATH); if(!file.file_was_opened) return; game.maker_tools.enabled = s2b(file.get_child_by_name("enabled")->value); for(unsigned char k = 0; k < 20; k++) { string tool_name; if(k < 10) { //The first ten indexes are the F2 - F11 keys. tool_name = file.get_child_by_name("f" + i2s(k + 2))->value; } else { //The second ten indexes are the 0 - 9 keys. tool_name = file.get_child_by_name(i2s(k - 10))->value; } for(size_t t = 0; t < N_MAKER_TOOLS; ++t) { if(tool_name == MAKER_TOOL_NAMES[t]) { game.maker_tools.keys[k] = t; } } } reader_setter rs(&file); data_node* mob_hurting_percentage_node = NULL; rs.set("area_image_mobs", game.maker_tools.area_image_mobs); rs.set("area_image_shadows", game.maker_tools.area_image_shadows); rs.set("area_image_size", game.maker_tools.area_image_size); rs.set("change_speed_multiplier", game.maker_tools.change_speed_mult); rs.set( "mob_hurting_percentage", game.maker_tools.mob_hurting_ratio, &mob_hurting_percentage_node ); rs.set("auto_start_option", game.maker_tools.auto_start_option); rs.set("auto_start_mode", game.maker_tools.auto_start_mode); rs.set("performance_monitor", game.maker_tools.use_perf_mon); if(mob_hurting_percentage_node) { game.maker_tools.mob_hurting_ratio /= 100.0; } } /* ---------------------------------------------------------------------------- * Loads miscellaneous fixed graphics. */ void load_misc_graphics() { //Icon. game.sys_assets.bmp_icon = game.bitmaps.get(game.asset_file_names.icon); al_set_display_icon(game.display, game.sys_assets.bmp_icon); //Graphics. game.sys_assets.bmp_checkbox_check = game.bitmaps.get(game.asset_file_names.checkbox_check); game.sys_assets.bmp_cursor = game.bitmaps.get(game.asset_file_names.cursor); game.sys_assets.bmp_cursor_invalid = game.bitmaps.get(game.asset_file_names.cursor_invalid); game.sys_assets.bmp_enemy_spirit = game.bitmaps.get(game.asset_file_names.enemy_spirit); game.sys_assets.bmp_idle_glow = game.bitmaps.get(game.asset_file_names.idle_glow); game.sys_assets.bmp_mouse_cursor = game.bitmaps.get(game.asset_file_names.mouse_cursor); game.sys_assets.bmp_mouse_wd_icon = game.bitmaps.get(game.asset_file_names.mouse_wd_icon); game.sys_assets.bmp_mouse_wu_icon = game.bitmaps.get(game.asset_file_names.mouse_wu_icon); game.sys_assets.bmp_notification = game.bitmaps.get(game.asset_file_names.notification); game.sys_assets.bmp_pikmin_silhouette = game.bitmaps.get(game.asset_file_names.pikmin_silhouette); game.sys_assets.bmp_pikmin_spirit = game.bitmaps.get(game.asset_file_names.pikmin_spirit); game.sys_assets.bmp_rock = game.bitmaps.get(game.asset_file_names.rock); game.sys_assets.bmp_shadow = game.bitmaps.get(game.asset_file_names.shadow); game.sys_assets.bmp_smack = game.bitmaps.get(game.asset_file_names.smack); game.sys_assets.bmp_smoke = game.bitmaps.get(game.asset_file_names.smoke); game.sys_assets.bmp_sparkle = game.bitmaps.get(game.asset_file_names.sparkle); game.sys_assets.bmp_spotlight = game.bitmaps.get(game.asset_file_names.spotlight); game.sys_assets.bmp_swarm_arrow = game.bitmaps.get(game.asset_file_names.swarm_arrow); game.sys_assets.bmp_wave_ring = game.bitmaps.get(game.asset_file_names.wave_ring); for(unsigned char i = 0; i < 3; ++i) { game.sys_assets.bmp_mouse_button_icon[i] = game.bitmaps.get(game.asset_file_names.mouse_button_icon[i]); } } /* ---------------------------------------------------------------------------- * Loads miscellaneous fixed sound effects. */ void load_misc_sounds() { //Sound effects. game.voice = al_create_voice( 44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2 ); game.mixer = al_create_mixer( 44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2 ); al_attach_mixer_to_voice(game.mixer, game.voice); game.sys_assets.sfx_attack = load_sample("Attack.ogg"); game.sys_assets.sfx_pikmin_attack = load_sample("Pikmin_attack.ogg"); game.sys_assets.sfx_pikmin_carrying = load_sample("Pikmin_carrying.ogg"); game.sys_assets.sfx_pikmin_carrying_grab = load_sample("Pikmin_carrying_grab.ogg"); game.sys_assets.sfx_pikmin_caught = load_sample("Pikmin_caught.ogg"); game.sys_assets.sfx_pikmin_dying = load_sample("Pikmin_dying.ogg"); game.sys_assets.sfx_pikmin_held = load_sample("Pikmin_held.ogg"); game.sys_assets.sfx_pikmin_idle = load_sample("Pikmin_idle.ogg"); game.sys_assets.sfx_pikmin_thrown = load_sample("Pikmin_thrown.ogg"); game.sys_assets.sfx_pikmin_plucked = load_sample("Pikmin_plucked.ogg"); game.sys_assets.sfx_pikmin_called = load_sample("Pikmin_called.ogg"); game.sys_assets.sfx_pluck = load_sample("Pluck.ogg"); game.sys_assets.sfx_throw = load_sample("Throw.ogg"); game.sys_assets.sfx_switch_pikmin = load_sample("Switch_Pikmin.ogg"); game.sys_assets.sfx_camera = load_sample("Camera.ogg"); } /* ---------------------------------------------------------------------------- * Loads the player's options. */ void load_options() { data_node file = data_node(OPTIONS_FILE_PATH); if(!file.file_was_opened) return; //Init joysticks. game.joystick_numbers.clear(); int n_joysticks = al_get_num_joysticks(); for(int j = 0; j < n_joysticks; ++j) { game.joystick_numbers[al_get_joystick(j)] = j; } //Read the main options. game.options.load(&file); game.win_fullscreen = game.options.intended_win_fullscreen; game.win_w = game.options.intended_win_w; game.win_h = game.options.intended_win_h; //Set up the animation editor history. reader_setter rs(&file); game.states.animation_editor_st->history.clear(); for(size_t h = 0; h < animation_editor::HISTORY_SIZE; ++h) { game.states.animation_editor_st->history.push_back(""); rs.set( "animation_editor_history_" + i2s(h + 1), game.states.animation_editor_st->history[h] ); } } /* ---------------------------------------------------------------------------- * Loads an audio sample from the game's content. * file_name: * Name of the file to load. */ sample_struct load_sample(const string &file_name) { ALLEGRO_SAMPLE* sample = al_load_sample((AUDIO_FOLDER_PATH + "/" + file_name).c_str()); if(!sample) { log_error("Could not open audio sample " + file_name + "!"); } return sample_struct(sample, game.mixer); } /* ---------------------------------------------------------------------------- * Loads the spike damage types available. */ void load_spike_damage_types() { if(game.perf_mon) { game.perf_mon->start_measurement("Spike damage types"); } vector<string> type_files = folder_to_vector(SPIKE_DAMAGES_FOLDER_PATH, false); for(size_t t = 0; t < type_files.size(); ++t) { data_node file = load_data_file(SPIKE_DAMAGES_FOLDER_PATH + "/" + type_files[t]); if(!file.file_was_opened) continue; spike_damage_type new_t; reader_setter rs(&file); string particle_generator_name; data_node* damage_node = NULL; data_node* particle_generator_node = NULL; rs.set("name", new_t.name); rs.set("damage", new_t.damage, &damage_node); rs.set("ingestion_only", new_t.ingestion_only); rs.set("is_damage_ratio", new_t.is_damage_ratio); rs.set( "particle_generator", particle_generator_name, &particle_generator_node ); if(particle_generator_node) { if( game.custom_particle_generators.find(particle_generator_name) == game.custom_particle_generators.end() ) { log_error( "Unknown particle generator \"" + particle_generator_name + "\"!", particle_generator_node ); } else { new_t.particle_gen = &game.custom_particle_generators[particle_generator_name]; new_t.particle_offset_pos = s2p( file.get_child_by_name("particle_offset")->value, &new_t.particle_offset_z ); } } if(new_t.damage == 0) { log_error( "Spike damage type \"" + new_t.name + "\" needs a damage number!", (damage_node ? damage_node : &file) ); } game.spike_damage_types[new_t.name] = new_t; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads spray types from the game data. * load_resources: * If true, things like bitmaps and the like will be loaded as well. * If you don't need those, set this to false to make it load faster. */ void load_spray_types(const bool load_resources) { if(game.perf_mon) { game.perf_mon->start_measurement("Spray types"); } vector<string> type_files = folder_to_vector(SPRAYS_FOLDER_PATH, false); vector<spray_type> temp_types; for(size_t t = 0; t < type_files.size(); ++t) { data_node file = load_data_file(SPRAYS_FOLDER_PATH + "/" + type_files[t]); if(!file.file_was_opened) continue; spray_type new_t; reader_setter rs(&file); string effects_str; string icon_str; data_node* effects_node = NULL; data_node* icon_node = NULL; rs.set("name", new_t.name); rs.set("effects", effects_str, &effects_node); rs.set("icon", icon_str, &icon_node); rs.set("group", new_t.group); rs.set("angle", new_t.angle); rs.set("distance_range", new_t.distance_range); rs.set("angle_range", new_t.angle_range); rs.set("color", new_t.main_color); rs.set("ingredients_needed", new_t.ingredients_needed); rs.set("buries_pikmin", new_t.buries_pikmin); if(effects_node) { vector<string> effects_strs = semicolon_list_to_vector(effects_node->value); for(size_t e = 0; e < effects_strs.size(); ++e) { string effect_name = effects_strs[e]; if( game.status_types.find(effect_name) == game.status_types.end() ) { log_error( "Unknown status effect \"" + effect_name + "\"!", effects_node ); } else { new_t.effects.push_back(game.status_types[effect_name]); } } } new_t.angle = deg_to_rad(new_t.angle); new_t.angle_range = deg_to_rad(new_t.angle_range); if(load_resources) { new_t.bmp_spray = game.bitmaps.get(icon_str, icon_node); } temp_types.push_back(new_t); } //Check the registered order and sort. for(size_t t = 0; t < temp_types.size(); ++t) { if( find( game.config.spray_order_strings.begin(), game.config.spray_order_strings.end(), temp_types[t].name ) == game.config.spray_order_strings.end() ) { log_error( "Spray type \"" + temp_types[t].name + "\" was not found " "in the spray order list in the config file!" ); game.config.spray_order_strings.push_back(temp_types[t].name); } } for(size_t o = 0; o < game.config.spray_order_strings.size(); ++o) { string s = game.config.spray_order_strings[o]; bool found = false; for(size_t t = 0; t < temp_types.size(); ++t) { if(temp_types[t].name == s) { game.spray_types.push_back(temp_types[t]); found = true; } } if(!found) { log_error( "Unknown spray type \"" + s + "\" found " "in the spray order list in the config file!" ); } } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads status effect types from the game data. * load_resources: * If true, things like bitmaps and the like will be loaded as well. * If you don't need those, set this to false to make it load faster. */ void load_status_types(const bool load_resources) { if(game.perf_mon) { game.perf_mon->start_measurement("Status types"); } vector<string> type_files = folder_to_vector(STATUSES_FOLDER_PATH, false); for(size_t t = 0; t < type_files.size(); ++t) { data_node file = load_data_file(STATUSES_FOLDER_PATH + "/" + type_files[t]); if(!file.file_was_opened) continue; status_type* new_t = new status_type(); reader_setter rs(&file); bool affects_pikmin_bool = false; bool affects_leaders_bool = false; bool affects_enemies_bool = false; bool affects_others_bool = false; string particle_offset_str; string particle_gen_str; data_node* particle_gen_node = NULL; rs.set("name", new_t->name); rs.set("color", new_t->color); rs.set("tint", new_t->tint); rs.set("glow", new_t->glow); rs.set("affects_pikmin", affects_pikmin_bool); rs.set("affects_leaders", affects_leaders_bool); rs.set("affects_enemies", affects_enemies_bool); rs.set("affects_others", affects_others_bool); rs.set("removable_with_whistle", new_t->removable_with_whistle); rs.set("auto_remove_time", new_t->auto_remove_time); rs.set("health_change_ratio", new_t->health_change_ratio); rs.set("causes_disable", new_t->causes_disable); rs.set("causes_flailing", new_t->causes_flailing); rs.set("causes_panic", new_t->causes_panic); rs.set("disabled_state_inedible", new_t->disabled_state_inedible); rs.set("speed_multiplier", new_t->speed_multiplier); rs.set("attack_multiplier", new_t->attack_multiplier); rs.set("defense_multiplier", new_t->defense_multiplier); rs.set("maturity_change_amount", new_t->maturity_change_amount); rs.set("disables_attack", new_t->disables_attack); rs.set("turns_invisible", new_t->turns_invisible); rs.set("anim_speed_multiplier", new_t->anim_speed_multiplier); rs.set("animation", new_t->animation_name); rs.set("animation_mob_scale", new_t->animation_mob_scale); rs.set("particle_generator", particle_gen_str, &particle_gen_node); rs.set("particle_offset", particle_offset_str); new_t->affects = 0; if(affects_pikmin_bool) { new_t->affects |= STATUS_AFFECTS_PIKMIN; } if(affects_leaders_bool) { new_t->affects |= STATUS_AFFECTS_LEADERS; } if(affects_enemies_bool) { new_t->affects |= STATUS_AFFECTS_ENEMIES; } if(affects_others_bool) { new_t->affects |= STATUS_AFFECTS_OTHERS; } if(particle_gen_node) { if( game.custom_particle_generators.find(particle_gen_str) == game.custom_particle_generators.end() ) { log_error( "Unknown particle generator \"" + particle_gen_str + "\"!", particle_gen_node ); } else { new_t->generates_particles = true; new_t->particle_gen = &game.custom_particle_generators[particle_gen_str]; new_t->particle_offset_pos = s2p(particle_offset_str, &new_t->particle_offset_z); } } if(load_resources) { if(!new_t->animation_name.empty()) { data_node anim_file = load_data_file( ANIMATIONS_FOLDER_PATH + "/" + new_t->animation_name ); new_t->anim_db = load_animation_database_from_file(&anim_file); if(!new_t->anim_db.animations.empty()) { new_t->anim_instance = animation_instance(&new_t->anim_db); new_t->anim_instance.cur_anim = new_t->anim_db.animations[0]; new_t->anim_instance.start(); } } } game.status_types[new_t->name] = new_t; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Loads the animations that are used system-wide. */ void load_system_animations() { data_node system_animations_file = load_data_file(SYSTEM_ANIMATIONS_FILE_PATH); init_single_animation( &system_animations_file, "leader_damage_sparks", game.sys_assets.spark_animation ); } /* ---------------------------------------------------------------------------- * Loads the weather conditions available. */ void load_weather() { if(game.perf_mon) { game.perf_mon->start_measurement("Weather"); } vector<string> weather_files = folder_to_vector(WEATHER_FOLDER_PATH, false); for(size_t w = 0; w < weather_files.size(); ++w) { data_node file = load_data_file(WEATHER_FOLDER_PATH + "/" + weather_files[w]); if(!file.file_was_opened) continue; weather new_w; reader_setter rs(&file); //General. rs.set("name", new_w.name); rs.set("fog_near", new_w.fog_near); rs.set("fog_far", new_w.fog_far); new_w.fog_near = std::max(new_w.fog_near, 0.0f); new_w.fog_far = std::max(new_w.fog_far, new_w.fog_near); //Lighting. vector<std::pair<size_t, string> > lighting_table = get_weather_table(file.get_child_by_name("lighting")); for(size_t p = 0; p < lighting_table.size(); ++p) { new_w.daylight.push_back( std::make_pair( lighting_table[p].first, s2c(lighting_table[p].second) ) ); } //Sun's strength. vector<std::pair<size_t, string> > sun_strength_table = get_weather_table(file.get_child_by_name("sun_strength")); for(size_t p = 0; p < sun_strength_table.size(); ++p) { new_w.sun_strength.push_back( std::make_pair( sun_strength_table[p].first, s2i(sun_strength_table[p].second) ) ); } //Blackout effect's strength. vector<std::pair<size_t, string> > blackout_strength_table = get_weather_table( file.get_child_by_name("blackout_strength") ); for(size_t p = 0; p < blackout_strength_table.size(); ++p) { new_w.blackout_strength.push_back( std::make_pair( blackout_strength_table[p].first, s2i(blackout_strength_table[p].second) ) ); } //Fog. vector<std::pair<size_t, string> > fog_color_table = get_weather_table( file.get_child_by_name("fog_color") ); for(size_t p = 0; p < fog_color_table.size(); ++p) { new_w.fog_color.push_back( std::make_pair( fog_color_table[p].first, s2c(fog_color_table[p].second) ) ); } //Save it in the map. game.weather_conditions[new_w.name] = new_w; } if(game.perf_mon) { game.perf_mon->finish_measurement(); } } /* ---------------------------------------------------------------------------- * Unloads the loaded area from memory. */ void unload_area() { game.cur_area_data.clear(); } /* ---------------------------------------------------------------------------- * Unloads custom particle generators loaded from memory. */ void unload_custom_particle_generators() { for( auto g = game.custom_particle_generators.begin(); g != game.custom_particle_generators.end(); ++g ) { game.bitmaps.detach(g->second.base_particle.bitmap); } game.custom_particle_generators.clear(); } /* ---------------------------------------------------------------------------- * Unloads hazards loaded in memory. */ void unload_hazards() { game.hazards.clear(); } /* ---------------------------------------------------------------------------- * Unloads loaded liquids from memory. */ void unload_liquids() { for(auto &l : game.liquids) { l.second->anim_db.destroy(); delete l.second; } game.liquids.clear(); } /* ---------------------------------------------------------------------------- * Unloads miscellaneous graphics, sounds, and other resources. */ void unload_misc_resources() { game.bitmaps.detach(game.sys_assets.bmp_checkbox_check); game.bitmaps.detach(game.sys_assets.bmp_cursor); game.bitmaps.detach(game.sys_assets.bmp_cursor_invalid); game.bitmaps.detach(game.sys_assets.bmp_enemy_spirit); game.bitmaps.detach(game.sys_assets.bmp_icon); game.bitmaps.detach(game.sys_assets.bmp_idle_glow); game.bitmaps.detach(game.sys_assets.bmp_mouse_cursor); game.bitmaps.detach(game.sys_assets.bmp_mouse_wd_icon); game.bitmaps.detach(game.sys_assets.bmp_mouse_wu_icon); game.bitmaps.detach(game.sys_assets.bmp_notification); game.bitmaps.detach(game.sys_assets.bmp_pikmin_silhouette); game.bitmaps.detach(game.sys_assets.bmp_pikmin_spirit); game.bitmaps.detach(game.sys_assets.bmp_rock); game.bitmaps.detach(game.sys_assets.bmp_shadow); game.bitmaps.detach(game.sys_assets.bmp_smack); game.bitmaps.detach(game.sys_assets.bmp_smoke); game.bitmaps.detach(game.sys_assets.bmp_sparkle); game.bitmaps.detach(game.sys_assets.bmp_spotlight); game.bitmaps.detach(game.sys_assets.bmp_swarm_arrow); game.bitmaps.detach(game.sys_assets.bmp_wave_ring); for(unsigned char i = 0; i < 3; ++i) { game.bitmaps.detach(game.sys_assets.bmp_mouse_button_icon[i]); } game.sys_assets.sfx_attack.destroy(); game.sys_assets.sfx_pikmin_attack.destroy(); game.sys_assets.sfx_pikmin_carrying.destroy(); game.sys_assets.sfx_pikmin_carrying_grab.destroy(); game.sys_assets.sfx_pikmin_caught.destroy(); game.sys_assets.sfx_pikmin_dying.destroy(); game.sys_assets.sfx_pikmin_held.destroy(); game.sys_assets.sfx_pikmin_idle.destroy(); game.sys_assets.sfx_pikmin_thrown.destroy(); game.sys_assets.sfx_pikmin_plucked.destroy(); game.sys_assets.sfx_pikmin_called.destroy(); game.sys_assets.sfx_throw.destroy(); game.sys_assets.sfx_switch_pikmin.destroy(); game.sys_assets.sfx_camera.destroy(); } /* ---------------------------------------------------------------------------- * Unloads spike damage types loaded in memory. */ void unload_spike_damage_types() { game.spike_damage_types.clear(); } /* ---------------------------------------------------------------------------- * Unloads loaded spray types from memory. */ void unload_spray_types() { for(size_t s = 0; s < game.spray_types.size(); ++s) { game.bitmaps.detach(game.spray_types[s].bmp_spray); } game.spray_types.clear(); } /* ---------------------------------------------------------------------------- * Unloads loaded status effect types from memory. * unload_resources: * If resources got loaded, set this to true to unload them. */ void unload_status_types(const bool unload_resources) { for(auto &s : game.status_types) { if(unload_resources) { s.second->anim_db.destroy(); } delete s.second; } game.status_types.clear(); } /* ---------------------------------------------------------------------------- * Unloads loaded weather conditions. */ void unload_weather() { game.weather_conditions.clear(); }
34.049667
80
0.561317
[ "geometry", "object", "vector" ]
8464c6d6ee1a7cf797f8ebc3f26eab18801ed58a
14,964
cpp
C++
hmmwv_turning/FWD_hmmwv_turning.cpp
Luke-M15/ME751_FinalProject
0516b0a206d77c5ea309791871cb1cbc5618df82
[ "MIT" ]
null
null
null
hmmwv_turning/FWD_hmmwv_turning.cpp
Luke-M15/ME751_FinalProject
0516b0a206d77c5ea309791871cb1cbc5618df82
[ "MIT" ]
null
null
null
hmmwv_turning/FWD_hmmwv_turning.cpp
Luke-M15/ME751_FinalProject
0516b0a206d77c5ea309791871cb1cbc5618df82
[ "MIT" ]
null
null
null
//=================================================================== //Author: Luke Mottley //ME 751 Final Project // Full Vehicle model on deformable terrain, significantly based on the HMMWV // deformable soil demo //==================================================================== #include <cstdio> #include <cmath> #include <vector> #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/ChDriver.h" #include "chrono_vehicle/terrain/SCMDeformableTerrain.h" #include "chrono_vehicle/terrain/RigidTerrain.h" #include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h" #include "chrono_models/vehicle/hmmwv/HMMWV.h" #include "chrono_postprocess/ChGnuPlot.h" #include "chrono_thirdparty/filesystem/path.h" using namespace chrono; using namespace chrono::collision; using namespace chrono::irrlicht; using namespace chrono::vehicle; using namespace chrono::vehicle::hmmwv; using std::cout; using std::endl; // ============================================================================= // USER SETTINGS // ============================================================================= // ----------------------------------------------------------------------------- // Terrain parameters // ----------------------------------------------------------------------------- // Dimensions double terrainHeight = 0; double terrainLength = 16.0; // size in X direction double terrainWidth = 8.0; // size in Y direction // Divisions (X and Y) int divLength = 128;//1024; int divWidth = 64;//512; // ----------------------------------------------------------------------------- // Vehicle parameters // ----------------------------------------------------------------------------- // Type of wheel/tire (controls both contact and visualization) enum WheelType { CYLINDRICAL, LUGGED }; WheelType wheel_type = LUGGED; // Type of terrain enum TerrainType { DEFORMABLE_SOIL, RIGID_SOIL }; TerrainType terrain_type = DEFORMABLE_SOIL; // Type of powertrain model (SHAFTS, SIMPLE) PowertrainModelType powertrain_model = PowertrainModelType::SIMPLE; // Drive type (FWD, RWD, or AWD) DrivelineType drive_type = DrivelineType::FWD; // Chassis visualization (MESH, PRIMITIVES, NONE) VisualizationType chassis_vis = VisualizationType::NONE; // Initial vehicle position and orientation ChVector<> initLoc(-5, -2, 0.6); ChQuaternion<> initRot(1, 0, 0, 0); // Contact material properties float Y_t = 1.0e6f; float cr_t = 0.1f; float mu_t = 0.8f; // ----------------------------------------------------------------------------- // Simulation parameters // ----------------------------------------------------------------------------- // Simulation Length double t_end = 5; // Simulation step size double step_size = 3e-3; // Time interval between two render frames (1/FPS) double render_step_size = 1.0 / 100; // Point on chassis tracked by the camera ChVector<> trackPoint(0.0, 0.0, 1.75); // Output directories const std::string out_dir = "HMMWV_FWD_turning"; const std::string img_dir = out_dir + "/IMG"; // Visualization output bool img_output = false; // ============================================================================= class MyDriver : public ChDriver { public: MyDriver(ChVehicle& vehicle, double delay) : ChDriver(vehicle), m_delay(delay) {} ~MyDriver() {} virtual void Synchronize(double time) override { m_throttle = 0; m_steering = 0; m_braking = 0; double eff_time = time - m_delay; // Do not generate any driver inputs for a duration equal to m_delay. if (eff_time < 0) return; if (eff_time > 0.2) m_throttle = 0.9; else m_throttle = 1.5 * eff_time; if (eff_time < 1) m_steering = 0; else m_steering = 0.6 * std::sin(CH_C_2PI * (eff_time - 2) / 6); } private: double m_delay; }; // ============================================================================= void CreateLuggedGeometry(std::shared_ptr<ChBody> wheelBody) { std::string lugged_file("vehicle/hmmwv/lugged_wheel_section.obj"); geometry::ChTriangleMeshConnected lugged_mesh; ChConvexDecompositionHACDv2 lugged_convex; utils::LoadConvexMesh(GetChronoDataFile(lugged_file), lugged_mesh, lugged_convex); int num_hulls = lugged_convex.GetHullCount(); auto coll_model = wheelBody->GetCollisionModel(); coll_model->ClearModel(); // Assemble the tire contact from 15 segments, properly offset. // Each segment is further decomposed in convex hulls. for (int iseg = 0; iseg < 15; iseg++) { ChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y); for (int ihull = 0; ihull < num_hulls; ihull++) { std::vector<ChVector<> > convexhull; lugged_convex.GetConvexHullResult(ihull, convexhull); coll_model->AddConvexHull(convexhull, VNULL, rot); } } // Add a cylinder to represent the wheel hub. coll_model->AddCylinder(0.223, 0.223, 0.126); coll_model->BuildModel(); // Visualization auto trimesh = std::make_shared<geometry::ChTriangleMeshConnected>(); trimesh->LoadWavefrontMesh(GetChronoDataFile("vehicle/hmmwv/lugged_wheel.obj"), false, false); auto trimesh_shape = std::make_shared<ChTriangleMeshShape>(); trimesh_shape->SetMesh(trimesh); trimesh_shape->SetName("lugged_wheel"); wheelBody->AddAsset(trimesh_shape); auto mcolor = std::make_shared<ChColorAsset>(0.3f, 0.3f, 0.3f); wheelBody->AddAsset(mcolor); } // ============================================================================= int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Set path to Chrono data directory SetChronoDataPath(CHRONO_DATA_DIR); // -------------------- // Create HMMWV vehicle // -------------------- HMMWV_Full my_hmmwv; my_hmmwv.SetContactMethod(ChMaterialSurface::SMC); my_hmmwv.SetChassisFixed(false); my_hmmwv.SetInitPosition(ChCoordsys<>(initLoc, initRot)); my_hmmwv.SetPowertrainType(powertrain_model); my_hmmwv.SetDriveType(drive_type); my_hmmwv.SetTireType(TireModelType::RIGID); my_hmmwv.SetVehicleStepSize(step_size); my_hmmwv.Initialize(); VisualizationType wheel_vis = (wheel_type == CYLINDRICAL) ? VisualizationType::MESH : VisualizationType::NONE; my_hmmwv.SetChassisVisualizationType(chassis_vis); my_hmmwv.SetWheelVisualizationType(wheel_vis); ChSystem* system = my_hmmwv.GetSystem(); // -------------------------------------------------------- // Set wheel contact material. // If needed, modify wheel contact and visualization models // -------------------------------------------------------- for (int i = 0; i < 4; i++) { auto wheelBody = my_hmmwv.GetVehicle().GetWheelBody(i); wheelBody->GetMaterialSurfaceSMC()->SetFriction(mu_t); wheelBody->GetMaterialSurfaceSMC()->SetYoungModulus(Y_t); wheelBody->GetMaterialSurfaceSMC()->SetRestitution(cr_t); CreateLuggedGeometry(wheelBody); } // -------------------- // Create driver system // -------------------- MyDriver driver(my_hmmwv.GetVehicle(), 0.25); driver.Initialize(); // ------------------ // Create the terrain // ------------------ ChTerrain* terrain; SCMDeformableTerrain* terrainD = new SCMDeformableTerrain(system); terrainD->SetPlane(ChCoordsys<>(VNULL, Q_from_AngX(CH_C_PI_2))); terrainD->SetSoilParametersSCM(2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01, // Janosi shear coefficient (m) 2e8, // Elastic stiffness (Pa/m), before plastic yield 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ); /* terrainD->SetBulldozingFlow(true); // inflate soil at the border of the rut terrainD->SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut 0.8, // displaced material vs downward pressed material. 5, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion */ // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: terrainD->SetAutomaticRefinement(true); terrainD->SetAutomaticRefinementResolution(0.04); ////terrainD->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 80, 16); ////terrainD->SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); terrainD->SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE, 0, 0.1); terrainD->Initialize(terrainHeight, terrainLength, terrainWidth, divLength, divWidth); terrain = terrainD; // Complete system construction system->SetupInitial(); // --------------------------------------- // Create the vehicle Irrlicht application // --------------------------------------- ChWheeledVehicleIrrApp app(&my_hmmwv.GetVehicle(), &my_hmmwv.GetPowertrain(), L"HMMWV FWD Deformable Soil Turning"); app.SetSkyBox(); app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); app.SetChaseCamera(trackPoint, 6.0, 0.5); app.SetTimestep(step_size); app.AssetBindAll(); app.AssetUpdateAll(); // ----------------- // Initialize output // ----------------- if (!filesystem::create_directory(filesystem::path(out_dir))) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if (img_output) { if (!filesystem::create_directory(filesystem::path(img_dir))) { std::cout << "Error creating directory " << img_dir << std::endl; return 1; } } utils::CSV_writer outFile(" "); // --------------- // Simulation loop // --------------- std::cout << "Total vehicle mass: " << my_hmmwv.GetTotalMass() << std::endl; // Solver settings. ////system->SetSolverType(ChSolver::Type::MINRES); system->SetMaxItersSolverSpeed(50); system->SetMaxItersSolverStab(50); ////system->SetTol(0); ////system->SetMaxPenetrationRecoverySpeed(1.5); ////system->SetMinBounceSpeed(2.0); ////system->SetSolverOverrelaxationParam(0.8); ////system->SetSolverSharpnessParam(1.0); // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Initialize simulation frame counter int step_number = 0; int render_frame = 0; ChRealtimeStepTimer realtime_timer; while (app.GetDevice()->run()) { double time = system->GetChTime(); if (time >= t_end) break; auto frcL = static_cast<ChRigidTire*>(my_hmmwv.GetTire(0))->ReportTireForce(terrain); double longSL = my_hmmwv.GetTire(0)->GetLongitudinalSlip(); double slipL = my_hmmwv.GetTire(0)->GetSlipAngle(); auto frcR = static_cast<ChRigidTire*>(my_hmmwv.GetTire(1))->ReportTireForce(terrain); double longSR = my_hmmwv.GetTire(1)->GetLongitudinalSlip(); double slipR = my_hmmwv.GetTire(1)->GetSlipAngle(); auto drawL = my_hmmwv.GetVehicle().GetSuspension(0)->GetRevolute(LEFT)->Get_react_force(); auto drawR = my_hmmwv.GetVehicle().GetSuspension(0)->GetRevolute(RIGHT)->Get_react_force(); if (time > .75) { outFile << time << frcL.force.x() << frcL.force.y() << frcL.force.z() << longSL << slipL << drawL; outFile << frcR.force.x() << frcR.force.y() << frcR.force.z() << longSR << slipR << drawR << std::endl; } // Render scene app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192)); app.DrawAll(); ChIrrTools::drawColorbar(0, 0.1, "Sinkage", app.GetDevice(), 30); if (img_output && step_number % render_steps == 0) { char filename[100]; sprintf(filename, "%s/img_%03d.jpg", img_dir.c_str(), render_frame + 1); app.WriteImageToFile(filename); render_frame++; } double throttle_input = driver.GetThrottle(); double steering_input = driver.GetSteering(); double braking_input = driver.GetBraking(); // Update modules driver.Synchronize(time); terrain->Synchronize(time); my_hmmwv.Synchronize(time, steering_input, braking_input, throttle_input, *terrain); app.Synchronize("", steering_input, throttle_input, braking_input); // Advance dynamics double step = realtime_timer.SuggestSimulationStep(step_size); system->DoStepDynamics(step); app.Advance(step); // Increment frame number step_number++; app.EndScene(); } outFile.write_to_file(out_dir + "/output.dat"); // creating plots std::string plot1 = out_dir + "/left_tire_y_force.gpl"; postprocess::ChGnuPlot mplot1(plot1.c_str()); mplot1.SetGrid(); mplot1.SetLabelX("Time (sec)"); mplot1.SetLabelY("Force (N)"); mplot1.Plot("output.dat", 1, 3, "Left Tire Y Force"); std::string plot2 = out_dir + "/left_tire_z_force.gpl"; postprocess::ChGnuPlot mplot2(plot2.c_str()); mplot2.SetGrid(); mplot2.SetLabelX("Time (sec)"); mplot2.SetLabelY("Force (N)"); mplot2.Plot("output.dat", 1, 4, "Left Tire Z Force"); std::string plot3 = out_dir + "/right_tire_y_force.gpl"; postprocess::ChGnuPlot mplot3(plot3.c_str()); mplot3.SetGrid(); mplot3.SetLabelX("Time (sec)"); mplot3.SetLabelY("Force (N)"); mplot3.Plot("output.dat", 1, 11, "Right Tire Y Force"); std::string plot4 = out_dir + "/right_tire_z_force.gpl"; postprocess::ChGnuPlot mplot4(plot4.c_str()); mplot4.SetGrid(); mplot4.SetLabelX("Time (sec)"); mplot4.SetLabelY("Force (N)"); mplot4.Plot("output.dat", 1, 12, "Right Tire Z Force"); std::string plot5 = out_dir + "/left_tire_long_slip.gpl"; postprocess::ChGnuPlot mplot5(plot5.c_str()); mplot5.SetGrid(); mplot5.SetLabelX("Time (sec)"); mplot5.SetLabelY("Longitudinal Slip"); mplot5.Plot("output.dat", 1, 5, "Left Tire Longitudinal Slip"); std::string plot6 = out_dir + "/right_tire_long_slip.gpl"; postprocess::ChGnuPlot mplot6(plot6.c_str()); mplot6.SetGrid(); mplot6.SetLabelX("Time (sec)"); mplot6.SetLabelY("Longitudinal Slip"); mplot6.Plot("output.dat", 1, 13, "Right Tire Longitudinal Slip"); std::string plot7 = out_dir + "/left_tire_slip_angle.gpl"; postprocess::ChGnuPlot mplot7(plot7.c_str()); mplot7.SetGrid(); mplot7.SetLabelX("Time (sec)"); mplot7.SetLabelY("Slip Angle (deg)"); mplot7.Plot("output.dat", 1, 6, "Left Tire Slip Angle"); std::string plot8 = out_dir + "/right_tire_slip_angle.gpl"; postprocess::ChGnuPlot mplot8(plot8.c_str()); mplot8.SetGrid(); mplot8.SetLabelX("Time (sec)"); mplot8.SetLabelY("Slip Angle (deg)"); mplot8.Plot("output.dat", 1, 114, "Right Tire Slip Angle"); std::string plot9 = out_dir + "/front_left_drawbar.gpl"; postprocess::ChGnuPlot mplot9(plot9.c_str()); mplot9.SetGrid(); mplot9.SetLabelX("Longitudinal Slip"); mplot9.SetLabelY("Force (N)"); mplot9.Plot("output.dat", 5, 7, "Front Left Draw Pull"); std::string plot10 = out_dir + "/front_right_drawbar.gpl"; postprocess::ChGnuPlot mplot10(plot10.c_str()); mplot10.SetGrid(); mplot10.SetLabelX("Longitudinal Slip"); mplot10.SetLabelY("Force (N)"); mplot10.Plot("output.dat", 13, 15, "Front Right Drawbar Pull"); // Cleanup delete terrain; return 0; }
34.009091
118
0.655774
[ "mesh", "geometry", "render", "vector", "model", "3d" ]
84676a5645d1fa679cf8d5556bc2be064db58163
20,166
cpp
C++
com/netfx/src/clr/tools/strike/eeheap.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/tools/strike/eeheap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/tools/strike/eeheap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #include "strike.h" #include "util.h" void* operator new(size_t, void* p) { return p; } /**********************************************************************\ * Routine Description: * * * * This function is called to update GC heap statistics. * * * \**********************************************************************/ void HeapStat::Add(DWORD_PTR aMT, DWORD aSize) { if (head == 0) { head = (Node*)malloc(sizeof(Node)); if (head == NULL) { dprintf ("Not enough memory\n"); ControlC = TRUE; return; } head = new (head) Node; head->MT = aMT; } Node *walk = head; while (walk->MT != aMT) { if (IsInterrupt()) return; if (aMT < walk->MT) { if (walk->left == NULL) break; walk = walk->left; } else { if (walk->right == NULL) break; walk = walk->right; } } if (aMT == walk->MT) { walk->count ++; walk->totalSize += aSize; } else { Node *node = (Node*)malloc(sizeof(Node)); if (node == NULL) { dprintf ("Not enough memory\n"); ControlC = TRUE; return; } node = new (node) Node; node->MT = aMT; node->totalSize = aSize; node->count ++; if (aMT < walk->MT) { walk->left = node; } else { walk->right = node; } } } /**********************************************************************\ * Routine Description: * * * * This function is called to sort all entries in the heap stat. * * * \**********************************************************************/ void HeapStat::Sort () { Node *root = head; head = NULL; ReverseLeftMost (root); Node *sortRoot = NULL; while (head) { Node *tmp = head; head = head->left; if (tmp->right) ReverseLeftMost (tmp->right); // add tmp tmp->right = NULL; tmp->left = NULL; SortAdd (sortRoot, tmp); } head = sortRoot; // Change binary tree to a linear tree root = head; head = NULL; ReverseLeftMost (root); sortRoot = NULL; while (head) { Node *tmp = head; head = head->left; if (tmp->right) ReverseLeftMost (tmp->right); // add tmp tmp->right = NULL; tmp->left = NULL; LinearAdd (sortRoot, tmp); } head = sortRoot; //reverse the order root = head; head = NULL; sortRoot = NULL; while (root) { Node *tmp = root->right; root->left = NULL; root->right = NULL; LinearAdd (sortRoot, root); root = tmp; } head = sortRoot; } void HeapStat::ReverseLeftMost (Node *root) { while (root) { Node *tmp = root->left; root->left = head; head = root; root = tmp; } } /**********************************************************************\ * Routine Description: * * * * This function is called to help to sort heap stat. * * * \**********************************************************************/ void HeapStat::SortAdd (Node *&root, Node *entry) { if (root == NULL) { root = entry; } else { Node *parent = root; Node *ptr = root; while (ptr) { parent = ptr; if (ptr->totalSize < entry->totalSize) ptr = ptr->right; else ptr = ptr->left; } if (parent->totalSize < entry->totalSize) parent->right = entry; else parent->left = entry; } } void HeapStat::LinearAdd(Node *&root, Node *entry) { if (root == NULL) { root = entry; } else { entry->right = root; root = entry; } } /**********************************************************************\ * Routine Description: * * * * This function is called to print GC heap statistics. * * * \**********************************************************************/ void HeapStat::Print() { Node *root = head; int ncount = 0; while (root) { if (IsInterrupt()) return; dprintf ("%8x %8d %9d ", root->MT, root->count, root->totalSize); ncount += root->count; if (root->MT == MTForFreeObj()) { dprintf ("%9s\n","Free"); } else { NameForMT (root->MT, g_mdName); dprintf ("%S\n", g_mdName); } root = root->right; } dprintf ("Total %d objects\n", ncount); } void HeapStat::Delete() { Node *root = head; head = NULL; ReverseLeftMost (root); while (head) { Node *tmp = head; head = head->left; if (tmp->right) ReverseLeftMost (tmp->right); // free tmp free (tmp); } } /**********************************************************************\ * Routine Description: * * * * Print the gc heap info. * * * \**********************************************************************/ void GCHeapInfo(gc_heap &heap, DWORD_PTR &total_size) { DWORD_PTR dwAddrSeg; heap_segment segment; int n; for (n = 0; n <= heap.g_max_generation; n ++) { if (IsInterrupt()) return; dprintf ("generation %d starts at 0x%p\n", n, (ULONG64)heap.generation_table[n].allocation_start); } dwAddrSeg = (DWORD_PTR)heap.generation_table[heap.g_max_generation].start_segment; dprintf (" segment begin allocated size\n"); total_size = 0; n = 0; DWORD_PTR dwAddr; while (dwAddrSeg != (DWORD_PTR)heap.generation_table[0].start_segment) { if (IsInterrupt()) return; dwAddr = dwAddrSeg; segment.Fill (dwAddr); dprintf ("%p %p %p 0x%p(%d)\n", (ULONG64)dwAddrSeg, (ULONG64)segment.mem, (ULONG64)segment.allocated, (ULONG64)(segment.allocated - segment.mem), segment.allocated - segment.mem); total_size += segment.allocated - segment.mem; dwAddrSeg = (DWORD_PTR)segment.next; n ++; if (n > 20) break; } dwAddr = (DWORD_PTR)heap.generation_table[0].start_segment; segment.Fill (dwAddr); //DWORD_PTR end = (DWORD_PTR)heap.generation_table[0].allocation_context.alloc_ptr; DWORD_PTR end = (DWORD_PTR)heap.alloc_allocated; dprintf ("%p %p %p %p(%d)\n", (ULONG64)dwAddrSeg, (ULONG64)segment.mem, (ULONG64)end, (ULONG64)(end - (DWORD_PTR)segment.mem), end - (DWORD_PTR)segment.mem); total_size += end - (DWORD_PTR)segment.mem; dprintf ("Total Size %#8x(%d)\n", total_size, total_size); } //Alignment constant for allocation #ifdef _X86_ #define ALIGNCONST 3 #else #define ALIGNCONST 7 #endif static BOOL MemOverlap (DWORD_PTR beg1, DWORD_PTR end1, DWORD_PTR beg2, DWORD_PTR end2) { if (beg2 >= beg1 && beg2 <= end1) return TRUE; else if (end2 >= beg1 && end2 <= end1) return TRUE; else if (beg1 >= beg2 && beg1 <= end2) return TRUE; else if (end1 >= beg2 && end1 <= end2) return TRUE; else return FALSE; } #define plug_skew sizeof(DWORD) #define min_obj_size (sizeof(BYTE*)+plug_skew+sizeof(size_t)) size_t Align (size_t nbytes) { return (nbytes + ALIGNCONST) & ~ALIGNCONST; } /**********************************************************************\ * Routine Description: * * * * Dump objects on the gc heap. * * * \**********************************************************************/ void GCHeapDump(gc_heap &heap, DWORD_PTR &nObj, DumpHeapFlags &flags, AllocInfo* pallocInfo) { DWORD_PTR begin_youngest; DWORD_PTR end_youngest; begin_youngest = (DWORD_PTR)heap.generation_table[0].allocation_start; DWORD_PTR dwAddr = (DWORD_PTR)heap.ephemeral_heap_segment; heap_segment segment; segment.Fill (dwAddr); end_youngest = (DWORD_PTR)heap.alloc_allocated; DWORD_PTR dwAddrSeg = (DWORD_PTR)heap.generation_table[2].start_segment; dwAddr = dwAddrSeg; segment.Fill (dwAddr); DWORD_PTR dwAddrCurrObj = (DWORD_PTR)heap.generation_table[2].allocation_start; if (flags.bFixRange) { dwAddrCurrObj = flags.startObject; DWORD_PTR end_of_segment = (DWORD_PTR)segment.allocated; if (dwAddrSeg == (DWORD_PTR)heap.ephemeral_heap_segment) { end_of_segment = end_youngest; } // Find the correct segment for this address. while (dwAddrCurrObj > end_of_segment || dwAddrCurrObj < dwAddrSeg) { dwAddrSeg = (DWORD_PTR)segment.next; if (dwAddrSeg) { dwAddr = dwAddrSeg; segment.Fill (dwAddr); if (dwAddrSeg == (DWORD_PTR)heap.ephemeral_heap_segment) { end_of_segment = end_youngest; } } else return; } } size_t s; MethodTable vMethTable; DWORD_PTR dwAddrMethTable; nObj = 0; DWORD_PTR dwAddrPrevObj=0; while(1) { if (IsInterrupt()) break; if (dwAddrCurrObj > flags.endObject) break; DWORD_PTR end_of_segment = (DWORD_PTR)segment.allocated; if (dwAddrSeg == (DWORD_PTR)heap.ephemeral_heap_segment) { end_of_segment = end_youngest; if (dwAddrCurrObj == end_youngest - Align(min_obj_size)) break; } if (dwAddrCurrObj >= (DWORD_PTR)end_of_segment || !MemOverlap (flags.startObject, flags.endObject, (DWORD_PTR)segment.mem, (DWORD_PTR)end_of_segment)) { if (dwAddrCurrObj > (DWORD_PTR)end_of_segment) { dprintf ("curr_object: %p > heap_segment_allocated (seg: %p)\n", (ULONG64)dwAddrCurrObj, (ULONG64)dwAddrSeg); if (dwAddrPrevObj) { dprintf ("Last good object: %p\n", (ULONG64)dwAddrPrevObj); } break; } dwAddrSeg = (DWORD_PTR)segment.next; if (dwAddrSeg) { dwAddr = dwAddrSeg; segment.Fill (dwAddr); dwAddrCurrObj = (DWORD_PTR)segment.mem; continue; } else break; // Done Verifying Heap } if (dwAddrSeg == (DWORD_PTR)heap.ephemeral_heap_segment && dwAddrCurrObj >= end_youngest) { if (dwAddrCurrObj > end_youngest) { // prev_object length is too long dprintf ("curr_object: %p > end_youngest: %p\n", (ULONG64)dwAddrCurrObj, (ULONG64)end_youngest); if (dwAddrPrevObj) { dprintf ("Last good object: %p\n", (ULONG64)dwAddrPrevObj); } break; } break; } move (dwAddrMethTable, dwAddrCurrObj); dwAddrMethTable = dwAddrMethTable & ~3; if (dwAddrMethTable == 0) { // Is this the beginning of an allocation context? int i; for (i = 0; i < pallocInfo->num; i ++) { if (dwAddrCurrObj == (DWORD_PTR)pallocInfo->array[i].alloc_ptr) { dwAddrCurrObj = (DWORD_PTR)pallocInfo->array[i].alloc_limit + Align(min_obj_size); break; } } if (i < pallocInfo->num) continue; } if (dwAddrMethTable != MTForFreeObj() && !IsMethodTable (dwAddrMethTable)) { dprintf ("Bad MethodTable for Obj at %p\n", (ULONG64)dwAddrCurrObj); if (dwAddrPrevObj) { dprintf ("Last good object: %p\n", (ULONG64)dwAddrPrevObj); } break; } DWORD_PTR dwAddrTmp = dwAddrMethTable; DWORD_PTR mtAddr = dwAddrTmp; vMethTable.Fill (dwAddrTmp); if (!CallStatus) { dprintf ("Fail to read MethodTable for Obj at %p\n", (ULONG64)dwAddrCurrObj); if (dwAddrPrevObj) { dprintf ("Last good object: %p\n", (ULONG64)dwAddrPrevObj); } break; } s = ObjectSize (dwAddrCurrObj); if (s == 0) { dprintf ("curr_object : %p size=0\n", (ULONG64)dwAddrCurrObj); if (dwAddrPrevObj) { dprintf ("Last good object: %p\n", (ULONG64)dwAddrPrevObj); } break; } if (dwAddrCurrObj >= flags.startObject && dwAddrCurrObj <= flags.endObject && s > flags.min_size && s < flags.max_size && (flags.MT == 0 || flags.MT == mtAddr)) { nObj ++; if (!flags.bStatOnly) dprintf ("%p %p %8d%s\n", (ULONG64)dwAddrCurrObj, (ULONG64)dwAddrMethTable, s, (dwAddrMethTable==MTForFreeObj())?" Free":""); stat->Add (dwAddrMethTable, (DWORD)s); } s = (s + ALIGNCONST) & ~ALIGNCONST; dwAddrPrevObj = dwAddrCurrObj; dwAddrCurrObj += s; } } DWORD_PTR LoaderHeapInfo (LoaderHeap *pLoaderHeap) { LoaderHeapBlock heapBlock; DWORD_PTR totalSize = 0; DWORD_PTR wastedSize = 0; DWORD_PTR heapAddr = (DWORD_PTR)pLoaderHeap->m_pFirstBlock; DWORD_PTR dwCurBlock = (DWORD_PTR)pLoaderHeap->m_pCurBlock; while (1) { if (IsInterrupt()) break; DWORD_PTR dwAddr = heapAddr; heapBlock.Fill (dwAddr); if (!CallStatus) { break; } DWORD_PTR curSize = 0; if (heapAddr != dwCurBlock) { DWORD_PTR dwAddr; char ch; for (dwAddr = (DWORD_PTR)heapBlock.pVirtualAddress; dwAddr < (DWORD_PTR)heapBlock.pVirtualAddress + heapBlock.dwVirtualSize; dwAddr += OSPageSize()) { if (IsInterrupt()) break; if (SafeReadMemory(dwAddr, &ch, sizeof(ch), NULL)) { curSize += OSPageSize(); } else break; } wastedSize += heapBlock.dwVirtualSize - curSize; } else { curSize = (DWORD_PTR)pLoaderHeap->m_pPtrToEndOfCommittedRegion - (DWORD_PTR)heapAddr; } totalSize += curSize; dprintf ("%p(%x", (ULONG64)heapBlock.pVirtualAddress, heapBlock.dwVirtualSize); if (curSize != heapBlock.dwVirtualSize) dprintf (":%p", (ULONG64)curSize); dprintf (") "); heapAddr = (DWORD_PTR)heapBlock.pNext; if (heapAddr == 0) { dprintf ("\n"); break; } } dprintf ("Size: 0x%p(%d) bytes.\n", (ULONG64)totalSize, totalSize); if (wastedSize) dprintf ("Wasted: 0x%p(%d) bytes.\n", (ULONG64)wastedSize, wastedSize); return totalSize; } DWORD_PTR JitHeapInfo () { // walk ExecutionManager__m_pJitList static DWORD_PTR dwJitListAddr = 0; if (dwJitListAddr == 0) { dwJitListAddr = GetValueFromExpression("MSCOREE!ExecutionManager__m_pJitList"); } DWORD_PTR dwJitList; if (!SafeReadMemory(dwJitListAddr, &dwJitList, sizeof(DWORD_PTR), NULL)) { return 0; } if (dwJitList == 0) return 0; EEJitManager vEEJitManager; IJitManager vIJitManager; DWORD_PTR totalSize = 0; while (dwJitList) { if (IsInterrupt()) break; DWORD_PTR vtbl; if (!SafeReadMemory(dwJitList, &vtbl, sizeof(DWORD_PTR), NULL)) { break; } JitType jitType = GetJitType (vtbl); DWORD_PTR dwAddr = dwJitList; if (jitType == JIT) { vEEJitManager.Fill (dwAddr); dwJitList = (DWORD_PTR)vEEJitManager.m_next; dprintf ("Normal Jit:"); HeapList vHeapList; LoaderHeap v_LoaderHeap; dwAddr = (DWORD_PTR)vEEJitManager.m_pCodeHeap; while (dwAddr) { if (IsInterrupt()) break; vHeapList.Fill (dwAddr); v_LoaderHeap.Fill (vHeapList.pHeap); totalSize += LoaderHeapInfo (&v_LoaderHeap); dwAddr = vHeapList.hpNext; } } else if (jitType == EJIT) { vIJitManager.Fill (dwAddr); dwJitList = (DWORD_PTR)vIJitManager.m_next; dprintf ("FJIT: "); dwAddr = GetValueFromExpression ("mscoree!EconoJitManager__m_CodeHeap"); unsigned value; SafeReadMemory(dwAddr, &value, sizeof(unsigned), NULL); dprintf ("%x", value); dwAddr = GetValueFromExpression ("mscoree!EconoJitManager__m_CodeHeapCommittedSize"); SafeReadMemory(dwAddr, &value, sizeof(unsigned), NULL); dprintf ("(%x)", value); dprintf ("\n"); dprintf ("Size 0x%x(%d)bytes\n", value); totalSize += value; } else if (jitType == PJIT) { vIJitManager.Fill (dwAddr); dwJitList = (DWORD_PTR)vIJitManager.m_next; } else { dprintf ("Unknown Jit\n"); break; } } dprintf ("Total size 0x%p(%d)bytes.\n", (ULONG64)totalSize, totalSize); return totalSize; }
31.072419
98
0.444362
[ "object" ]
8467ac43a00f33e91593540576f68b07a20868f1
3,532
cpp
C++
src/Sphere.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/Sphere.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/Sphere.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
// Sphere.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "Sphere.h" #include "Gripper.h" #include "MarkedList.h" CSphere::CSphere(const gp_Pnt& pos, double radius, const wxChar* title, const HeeksColor& col, float opacity) : CSolid(BRepPrimAPI_MakeSphere(pos, radius), title, col, opacity), in_set(false), m_pos(pos), m_radius(radius) { InitializeProperties(); } CSphere::CSphere(const TopoDS_Solid &solid, const wxChar* title, const HeeksColor& col, float opacity) : CSolid(solid, title, col, opacity), in_set(false), m_pos(0, 0, 0), m_radius(0.0) { InitializeProperties(); } CSphere::CSphere( const CSphere & rhs ) : CSolid(rhs), in_set(false) { InitializeProperties(); m_pos = rhs.m_pos; m_radius = rhs.m_radius; } CSphere & CSphere::operator= ( const CSphere & rhs ) { if (this != &rhs) { m_pos = rhs.m_pos; m_radius = rhs.m_radius; CSolid::operator=( rhs ); } return(*this); } void CSphere::InitializeProperties() { m_pos.Initialize(_("centre"), this, true); m_radius.Initialize(_("radius"), this, true); } HeeksObj *CSphere::MakeACopy(void)const { return new CSphere(*this); } const wxBitmap &CSphere::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/sphere.png"))); return *icon; } bool CSphere::IsDifferent(HeeksObj *other) { CSphere* sphere = (CSphere*)other; if(sphere->m_pos.Distance(m_pos) > wxGetApp().m_geom_tol || sphere->m_radius != m_radius) return true; return CShape::IsDifferent(other); } void CSphere::MakeTransformedShape(const gp_Trsf &mat) { m_pos.Transform(mat); double scale = gp_Vec(1, 0, 0).Transformed(mat).Magnitude(); m_radius = fabs(m_radius * scale); m_shape = BRepPrimAPI_MakeSphere(m_pos, m_radius).Shape(); } wxString CSphere::StretchedName(){ return _("Ellipsoid");} void CSphere::GetGripperPositions(std::list<GripData> *list, bool just_for_endof) { list->push_back(GripData(GripperTypeTranslate,m_pos.X(),m_pos.Y(),m_pos.Z(),NULL)); list->push_back(GripData(GripperTypeScale,m_pos.X() + m_radius,m_pos.Y(),m_pos.Z(),NULL)); } void CSphere::OnPropertySet(Property& prop) { if (in_set) { return; } if (prop == m_pos || prop == m_radius) { m_shape = BRepPrimAPI_MakeSphere(m_pos, m_radius).Shape(); delete_faces_and_edges(); KillGLLists(); create_faces_and_edges(); } else { CSolid::OnPropertySet(prop); } } bool CSphere::GetCentrePoint(double* pos) { extract(m_pos, pos); return true; } bool CSphere::GetScaleAboutMatrix(double *m) { gp_Trsf mat; mat.SetTranslationPart(gp_Vec(m_pos.XYZ())); extract(mat, m); return true; } void CSphere::SetXMLElement(TiXmlElement* element) { element->SetDoubleAttribute("px", m_pos.X()); element->SetDoubleAttribute("py", m_pos.Y()); element->SetDoubleAttribute("pz", m_pos.Z()); element->SetDoubleAttribute("r", m_radius); CSolid::SetXMLElement(element); } void CSphere::SetFromXMLElement(TiXmlElement* pElem) { in_set = true; // get the attributes for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next()) { std::string name(a->Name()); if(name == "px"){m_pos.SetX(a->DoubleValue());} else if(name == "py"){m_pos.SetY(a->DoubleValue());} else if(name == "pz"){m_pos.SetZ(a->DoubleValue());} else if(name == "r"){m_radius = a->DoubleValue();} } in_set = false; CSolid::SetFromXMLElement(pElem); }
24.191781
111
0.688845
[ "shape", "transform", "solid" ]
8468b5be15e639a116b2a0fd9c5d767b32654b1d
12,486
cpp
C++
dev/Gems/RoadsAndRivers/Code/Tests/RoadsAndRiversTest.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
2
2020-12-22T01:02:01.000Z
2020-12-22T01:02:05.000Z
dev/Gems/RoadsAndRivers/Code/Tests/RoadsAndRiversTest.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/RoadsAndRivers/Code/Tests/RoadsAndRiversTest.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates, or * a third party where indicated. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "StdAfx.h" #include <AzTest/AzTest.h> #include <Mocks/ITimerMock.h> #include <Mocks/ICryPakMock.h> #include <Mocks/IConsoleMock.h> #include <Mocks/ISystemMock.h> #include <AzCore/UnitTest/TestTypes.h> #include <AzCore/Component/ComponentApplication.h> #include <AzCore/Component/Entity.h> #include <AzCore/Math/Random.h> #include <AzCore/Math/Spline.h> #include <AzCore/Memory/Memory.h> #include <AzCore/Memory/SystemAllocator.h> #include <LmbrCentral/Shape/SplineComponentBus.h> #include "RoadRiverCommon.h" #include "RoadsAndRiversModule.h" #include "RoadComponent.h" #include "RiverComponent.h" namespace UnitTest { class WidthInterpolator : public AllocatorsFixture { public: void EdgeCases() { const float tolerance = 1e-4; { RoadsAndRivers::RoadWidthInterpolator m_interpolator; // empty interpolator returns 0.0f EXPECT_NEAR(m_interpolator.GetWidth(0.0f), 0.0f, tolerance); } { RoadsAndRivers::RoadWidthInterpolator m_interpolator; const float width = 2.0f; m_interpolator.InsertDistanceWidthKeyFrame(1.0f, width); // interpolator with 1 key frame always returns this keyframe EXPECT_NEAR(m_interpolator.GetWidth(0.0f), width, tolerance); EXPECT_NEAR(m_interpolator.GetWidth(1.0f), width, tolerance); EXPECT_NEAR(m_interpolator.GetWidth(2.0f), width, tolerance); } { RoadsAndRivers::RoadWidthInterpolator m_interpolator; m_interpolator.InsertDistanceWidthKeyFrame(1.0f, 2.0f); m_interpolator.InsertDistanceWidthKeyFrame(2.0f, 10.0f); // distance more than edge points yields edge points EXPECT_NEAR(m_interpolator.GetWidth(0.0f), 2.0f, tolerance); EXPECT_NEAR(m_interpolator.GetWidth(3.0f), 10.0f, tolerance); } } void Interpolation() { // Inserting sorted keys { RoadsAndRivers::RoadWidthInterpolator m_interpolator; m_interpolator.InsertDistanceWidthKeyFrame(1.0f, 1.0f); m_interpolator.InsertDistanceWidthKeyFrame(2.0f, 10.0f); m_interpolator.InsertDistanceWidthKeyFrame(3.0f, 5.0f); auto res = m_interpolator.GetWidth(1.5f); EXPECT_GT(res, 1.0f); EXPECT_LT(res, 10.0f); res = m_interpolator.GetWidth(2.5f); EXPECT_LT(res, 10.0f); EXPECT_GT(res, 5.0f); EXPECT_NEAR(m_interpolator.GetWidth(2.0f), 10.0f, 1e-4); } // Inserting unsorted keys { RoadsAndRivers::RoadWidthInterpolator m_interpolator; m_interpolator.InsertDistanceWidthKeyFrame(3.0f, 5.0f); m_interpolator.InsertDistanceWidthKeyFrame(1.0f, 1.0f); m_interpolator.InsertDistanceWidthKeyFrame(2.0f, 10.0f); auto res = m_interpolator.GetWidth(1.5f); EXPECT_GT(res, 1.0f); EXPECT_LT(res, 10.0f); res = m_interpolator.GetWidth(2.5f); EXPECT_LT(res, 10.0f); EXPECT_GT(res, 5.0f); EXPECT_NEAR(m_interpolator.GetWidth(2.0f), 10.0f, 1e-4); } } }; struct MockGlobalEnvironment { MockGlobalEnvironment() { m_stubEnv.pTimer = &m_stubTimer; m_stubEnv.pCryPak = &m_stubPak; m_stubEnv.pConsole = &m_stubConsole; m_stubEnv.pSystem = &m_stubSystem; m_stubEnv.p3DEngine = nullptr; gEnv = &m_stubEnv; } ~MockGlobalEnvironment() { gEnv = nullptr; } private: SSystemGlobalEnvironment m_stubEnv; testing::NiceMock<TimerMock> m_stubTimer; testing::NiceMock<CryPakMock> m_stubPak; testing::NiceMock<ConsoleMock> m_stubConsole; testing::NiceMock<SystemMock> m_stubSystem; }; class RoadsAndRiversTestApp : public ::testing::Test { public: RoadsAndRiversTestApp() : m_application() , m_systemEntity(nullptr) { } class MockTransformComponent : public AZ::Component { public: AZ_COMPONENT(MockTransformComponent, "{8F4C932A-6BAD-464B-AFB3-87CC8EA31FB5}", AZ::Component); void Activate() override {} void Deactivate() override {} static void Reflect(AZ::ReflectContext* reflect) { AZ_UNUSED(reflect); } static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } }; class MockSplineComponent : public AZ::Component , private LmbrCentral::SplineComponentRequestBus::Handler { public: AZ_COMPONENT(MockSplineComponent, "{F0905297-1E24-4044-BFDA-BDE3583F1E57}", AZ::Component); void Activate() override { LmbrCentral::SplineComponentRequestBus::Handler::BusConnect(GetEntityId()); } void Deactivate() override { LmbrCentral::SplineComponentRequestBus::Handler::BusDisconnect(); } static void Reflect(AZ::ReflectContext* reflect) { AZ_UNUSED(reflect); } static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("SplineService", 0x2b674d3c)); provided.push_back(AZ_CRC("VertexContainerService", 0x22cf8e10)); } MockSplineComponent() { m_spline = AZStd::make_shared<AZ::LinearSpline>(); } AZ::SplinePtr GetSpline() override { return m_spline; } void ChangeSplineType(AZ::u64 /*splineType*/) override {} void SetClosed(bool /*closed*/) override {} // SplineComponentRequestBus/VertexContainerInterface bool GetVertex(size_t index, AZ::Vector3& vertex) const override { return false; } void AddVertex(const AZ::Vector3& vertex) override { m_spline->m_vertexContainer.AddVertex(vertex); } bool UpdateVertex(size_t index, const AZ::Vector3& vertex) override { return false; } bool InsertVertex(size_t index, const AZ::Vector3& vertex) override { return false; } bool RemoveVertex(size_t index) override { return false; } void SetVertices(const AZStd::vector<AZ::Vector3>& vertices) override { } void ClearVertices() override { m_spline->m_vertexContainer.Clear(); } size_t Size() const override { return m_spline->m_vertexContainer.Size(); } bool Empty() const override { return m_spline->m_vertexContainer.Empty(); } private: AZ::SplinePtr m_spline; }; void SetUp() override { AZ::ComponentApplication::Descriptor appDesc; appDesc.m_memoryBlocksByteSize = 10 * 1024 * 1024; appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_FULL; appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; appStartup.m_createStaticModulesCallback = [](AZStd::vector<AZ::Module*>& modules) { modules.emplace_back(new RoadsAndRivers::RoadsAndRiversModule); }; m_systemEntity = m_application.Create(appDesc, appStartup); m_systemEntity->Init(); m_systemEntity->Activate(); m_application.RegisterComponentDescriptor(MockTransformComponent::CreateDescriptor()); m_application.RegisterComponentDescriptor(MockSplineComponent::CreateDescriptor()); m_application.RegisterComponentDescriptor(RoadsAndRivers::RoadComponent::CreateDescriptor()); m_application.RegisterComponentDescriptor(RoadsAndRivers::RiverComponent::CreateDescriptor()); } void TearDown() override { delete m_systemEntity; m_application.Destroy(); } AZ::ComponentApplication m_application; AZ::Entity* m_systemEntity; MockGlobalEnvironment m_mocks; }; TEST_F(WidthInterpolator, EdgeCases) { EdgeCases(); } TEST_F(WidthInterpolator, Interpolation) { Interpolation(); } TEST_F(RoadsAndRiversTestApp, RoadsAndRivers_RiverComponent) { AZ::Entity* riverEntity = aznew AZ::Entity("river_entity"); ASSERT_TRUE(riverEntity != nullptr); riverEntity->CreateComponent<MockTransformComponent>(); riverEntity->CreateComponent<MockSplineComponent>(); riverEntity->CreateComponent<RoadsAndRivers::RiverComponent>(); m_application.AddEntity(riverEntity); RoadsAndRivers::RiverComponent* riverComp = riverEntity->FindComponent<RoadsAndRivers::RiverComponent>(); ASSERT_TRUE(riverComp != nullptr); } TEST_F(RoadsAndRiversTestApp, RoadsAndRivers_RoadComponent) { AZ::Entity* roadEntity = aznew AZ::Entity("road_entity"); ASSERT_TRUE(roadEntity != nullptr); roadEntity->CreateComponent<MockTransformComponent>(); roadEntity->CreateComponent<MockSplineComponent>(); roadEntity->CreateComponent<RoadsAndRivers::RoadComponent>(); m_application.AddEntity(roadEntity); RoadsAndRivers::RoadComponent* roadComp = roadEntity->FindComponent<RoadsAndRivers::RoadComponent>(); ASSERT_TRUE(roadComp != nullptr); } TEST_F(RoadsAndRiversTestApp, RoadsAndRivers_RiverRequestBus) { AZ::Entity* riverEntity = aznew AZ::Entity("activated_river_entity"); ASSERT_TRUE(riverEntity != nullptr); riverEntity->CreateComponent<MockTransformComponent>(); riverEntity->CreateComponent<MockSplineComponent>(); riverEntity->CreateComponent<RoadsAndRivers::RiverComponent>(); riverEntity->Init(); riverEntity->Activate(); AZ::Plane surfacePlane; RoadsAndRivers::RiverRequestBus::EventResult(surfacePlane, riverEntity->GetId(), &RoadsAndRivers::RiverRequestBus::Events::GetWaterSurfacePlane); AZ::Vector4 planeEquation = surfacePlane.GetPlaneEquationCoefficients(); AZ::Vector4 expectedPlane(0.0f, 0.0f, 1.0f, 0.0f); ASSERT_TRUE(planeEquation.IsClose(expectedPlane)); } TEST_F(RoadsAndRiversTestApp, RoadsAndRivers_RoadsAndRiversGeometryRequestsBus) { AZ::Entity* riverEntity = aznew AZ::Entity("activated_river_entity"); ASSERT_TRUE(riverEntity != nullptr); riverEntity->CreateComponent<MockTransformComponent>(); riverEntity->CreateComponent<MockSplineComponent>(); riverEntity->CreateComponent<RoadsAndRivers::RiverComponent>(); riverEntity->Init(); MockSplineComponent* spline = riverEntity->FindComponent<MockSplineComponent>(); spline->AddVertex(AZ::Vector3(0.0f, 0.0f, 0.0f)); spline->AddVertex(AZ::Vector3(5.0f, 0.0f, 0.0f)); spline->AddVertex(AZ::Vector3(10.0f, 0.0f, 0.0f)); spline->AddVertex(AZ::Vector3(15.0f, 0.0f, 0.0f)); riverEntity->Activate(); AZStd::vector<AZ::Vector3> quadVertices; quadVertices.clear(); RoadsAndRivers::RoadsAndRiversGeometryRequestsBus::EventResult(quadVertices, riverEntity->GetId(), &RoadsAndRivers::RoadsAndRiversGeometryRequestsBus::Events::GetQuadVertices); ASSERT_TRUE(quadVertices.size() == 32); } AZ_UNIT_TEST_HOOK(); }
37.836364
184
0.635832
[ "shape", "vector" ]
846bcf725ef9710b1c16284b0447383635b86d04
2,248
hpp
C++
__unit_tests/gv_framework_unit_test/unit_test_render_simple_2d.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
2
2018-12-03T13:17:31.000Z
2020-04-08T07:00:02.000Z
__unit_tests/gv_framework_unit_test/unit_test_render_simple_2d.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
__unit_tests/gv_framework_unit_test/unit_test_render_simple_2d.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
namespace unit_test_render_simple_2d { int tick_count = 0; class gv_unit_test_render_simple : public gv_unit_test_with_renderer { public: virtual gv_string name() { return "unit_test_render_simple_2d"; } virtual void render() { gv_string_tmp s = "just a simple test of text draw ====>>"; s << "tick_count:" << tick_count; gv_global::debug_draw.get()->draw_string(*s, gv_vector2i(100, 120), gv_color::RED()); gv_global::debug_draw.get()->draw_string(*s, gv_vector2i(100, 120 + 10), gv_color::GREEN()); gv_global::debug_draw.get()->draw_string(*s, gv_vector2i(100, 120 + 20), gv_color::BLUE()); gv_global::debug_draw.get()->draw_triangle(gv_vector3(100, 160, 0.5f), gv_vector3(140, 160, 0.5f), gv_vector3(100, 200, 0.5f), gv_color::RED()); gv_global::debug_draw.get()->draw_triangle(gv_vector3(150, 160, 0.5f), gv_vector3(190, 160, 0.5f), gv_vector3(150, 200, 0.5f), gv_color::GREEN()); gv_global::debug_draw.get()->draw_triangle(gv_vector3(200, 160, 0.5f), gv_vector3(240, 160, 0.5f), gv_vector3(200, 200, 0.5f), gv_color::BLUE()); gv_global::debug_draw.get()->draw_triangle(gv_vector3(250, 160, 0.5f), gv_vector3(290, 160, 0.5f), gv_vector3(250, 200, 0.5f), gv_color::RED(), gv_color::GREEN(), gv_color::BLUE()); gv_vector3 a = gv_vector3(100, 220, 0.5f); gv_vector3 ex = gv_vector3(50, 0, 0); gv_vector3 ey = gv_vector3(0, 50, 0); gv_global::debug_draw.get()->draw_quad(a, a + ex, a + ey, a + ex + ey, gv_color::RED()); a += ex + ex / 2; gv_global::debug_draw.get()->draw_quad(a, a + ex, a + ey, a + ex + ey, gv_color::GREEN()); a += ex + ex / 2; gv_global::debug_draw.get()->draw_quad(a, a + ex, a + ey, a + ex + ey, gv_color::BLUE()); a += ex + ex / 2; gv_global::debug_draw.get()->draw_quad(a, a + ex, a + ey, a + ex + ey, gv_color::RED(), gv_color::GREEN(), gv_color::BLUE(), gv_color::WHITE()); a = gv_vector3(100, 280, 0.5f); gv_global::debug_draw.get()->draw_line(a, a + ex, gv_color::RED(), gv_color::BLUE()); a += ex + ex / 2; gv_global::debug_draw.get()->draw_line(a, a + ex, gv_color::GREEN(), gv_color::BLUE()); tick_count++; }; virtual bool is_finished() { if (tick_count < 1000) return false; return true; } } test; gv_unit_test_with_renderer* ptest = &test; };
43.230769
183
0.662367
[ "render" ]
846feebfbe33297797112999030e31c1140afb76
7,412
cpp
C++
src/psm/src/pdnsim.cpp
mooredan/OpenROAD
ab235a982f49c6ce063b36d750fb4132d0046c8b
[ "BSD-3-Clause-Clear" ]
null
null
null
src/psm/src/pdnsim.cpp
mooredan/OpenROAD
ab235a982f49c6ce063b36d750fb4132d0046c8b
[ "BSD-3-Clause-Clear" ]
null
null
null
src/psm/src/pdnsim.cpp
mooredan/OpenROAD
ab235a982f49c6ce063b36d750fb4132d0046c8b
[ "BSD-3-Clause-Clear" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2020, The Regents of the University of Minnesota All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "psm/pdnsim.h" #include <tcl.h> #include <fstream> #include <iostream> #include <iomanip> #include <sstream> #include "opendb/db.h" #include "ir_solver.h" #include <string> #include <vector> #include "gmat.h" #include "node.h" #include "utl/Logger.h" namespace psm { PDNSim::PDNSim() : _db(nullptr), _sta(nullptr), _logger(nullptr), _vsrc_loc(""), _out_file(""), _em_out_file(""), _enable_em(0), _bump_pitch_x(0), _bump_pitch_y(0), _spice_out_file(""), _power_net("") {}; PDNSim::~PDNSim() { _db = nullptr; _sta = nullptr; _vsrc_loc = ""; _power_net = ""; _out_file = ""; _em_out_file = ""; _enable_em = 0; _spice_out_file = ""; _bump_pitch_x = 0; _bump_pitch_y = 0; //_net_voltage_map = nullptr; } void PDNSim::init(utl::Logger* logger, odb::dbDatabase* db, sta::dbSta* sta) { _db = db; _sta = sta; _logger = logger; } void PDNSim::set_power_net(std::string net) { _power_net = net; } void PDNSim::set_bump_pitch_x(float bump_pitch) { _bump_pitch_x = bump_pitch; } void PDNSim::set_bump_pitch_y(float bump_pitch) { _bump_pitch_y = bump_pitch; } void PDNSim::set_pdnsim_net_voltage(std::string net, float voltage) { _net_voltage_map.insert(std::pair<std::string, float>(net, voltage)); } void PDNSim::import_vsrc_cfg(std::string vsrc) { _vsrc_loc = vsrc; _logger->info(utl::PSM, 1, "Reading voltage source file: {}.", _vsrc_loc); } void PDNSim::import_out_file(std::string out_file) { _out_file = out_file; _logger->info( utl::PSM, 2, "Output voltage file is specified as: {}.", _out_file); } void PDNSim::import_em_out_file(std::string em_out_file) { _em_out_file = em_out_file; _logger->info(utl::PSM, 3, "Output current file specified {}.", _em_out_file); } void PDNSim::import_enable_em(int enable_em) { _enable_em = enable_em; if (_enable_em == 1) { _logger->info(utl::PSM, 4, "EM calculation is enabled."); } } void PDNSim::import_spice_out_file(std::string out_file) { _spice_out_file = out_file; _logger->info( utl::PSM, 5, "Output spice file is specified as: {}.", _spice_out_file); } void PDNSim::write_pg_spice() { IRSolver* irsolve_h = new IRSolver(_db, _sta, _logger, _vsrc_loc, _power_net, _out_file, _em_out_file, _spice_out_file, _enable_em, _bump_pitch_x, _bump_pitch_y, _net_voltage_map); if (!irsolve_h->Build()) { delete irsolve_h; } else { int check_spice = irsolve_h->PrintSpice(); if (check_spice) { _logger->info( utl::PSM, 6, "SPICE file is written at: {}.", _spice_out_file); } else { _logger->error( utl::PSM, 7, "Failed to write out spice file: {}.", _spice_out_file); } } } int PDNSim::analyze_power_grid() { GMat* gmat_obj; IRSolver* irsolve_h = new IRSolver(_db, _sta, _logger, _vsrc_loc, _power_net, _out_file, _em_out_file, _spice_out_file, _enable_em, _bump_pitch_x, _bump_pitch_y, _net_voltage_map); if (!irsolve_h->Build()) { delete irsolve_h; return 0; } gmat_obj = irsolve_h->GetGMat(); irsolve_h->SolveIR(); std::vector<Node*> nodes = gmat_obj->GetAllNodes(); int vsize; vsize = nodes.size(); for (int n = 0; n < vsize; n++) { Node* node = nodes[n]; if (node->GetLayerNum() != 1) continue; } _logger->report("########## IR report #################"); _logger->report("Worstcase voltage: {:3.2e} V", irsolve_h->wc_voltage); _logger->report("Average IR drop : {:3.2e} V", abs(irsolve_h->supply_voltage_src - irsolve_h->avg_voltage)); _logger->report("Worstcase IR drop: {:3.2e} V", abs(irsolve_h->supply_voltage_src - irsolve_h->wc_voltage)); _logger->report("######################################"); if (_enable_em == 1) { _logger->report("########## EM analysis ###############"); _logger->report("Maximum current: {:3.2e} A", irsolve_h->max_cur); _logger->report("Average current: {:3.2e} A", irsolve_h->avg_cur); _logger->report("Number of resistors: {}", irsolve_h->num_res); _logger->report("######################################"); } delete irsolve_h; return 1; } int PDNSim::check_connectivity() { IRSolver* irsolve_h = new IRSolver(_db, _sta, _logger, _vsrc_loc, _power_net, _out_file, _em_out_file, _spice_out_file, _enable_em, _bump_pitch_x, _bump_pitch_y, _net_voltage_map); if (!irsolve_h->BuildConnection()) { delete irsolve_h; return 0; } int val = irsolve_h->GetConnectionTest(); delete irsolve_h; return val; } } // namespace psm
30.883333
80
0.565434
[ "vector" ]
84764041332f645df8780d38b0851790ef2bbd83
70,444
cpp
C++
libnd4j/include/helpers/impl/shape.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
2,206
2019-06-12T18:57:14.000Z
2022-03-29T08:14:27.000Z
libnd4j/include/helpers/impl/shape.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
1,685
2019-06-12T17:41:33.000Z
2022-03-29T21:45:15.000Z
libnd4j/include/helpers/impl/shape.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
572
2019-06-12T22:13:57.000Z
2022-03-31T16:46:46.000Z
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by raver119 on 07.10.2017. // #include <helpers/shape.h> namespace shape { SD_HOST sd::LongType *computeResultShape(sd::LongType const *originalShapeBuffer, int *dimension, int dimensionLength) { sd::LongType *retShape; int retShapeLength; if (dimensionLength == 1 && dimension[0] == 2147483647) { retShape = new sd::LongType[2]; retShape[0] = 1; retShape[1] = 1; retShapeLength = 2; } else { retShape = shape::removeIndex<sd::LongType, int>(shape::shapeOf(originalShapeBuffer), dimension, shape::shapeInfoLength(shape::rank(originalShapeBuffer)), dimensionLength); retShapeLength = shape::rank(originalShapeBuffer) - dimensionLength; } // ensure vector is proper shape if (retShapeLength == 1) { if (dimension[0] == 0) { auto newRetShape = new sd::LongType[2]{1, retShape[0]}; delete[] retShape; retShape = newRetShape; retShapeLength = 2; } else { auto newRetShape = new sd::LongType[2]{retShape[0], 1}; delete[] retShape; retShape = newRetShape; retShapeLength = 2; } } else if (retShapeLength == 0) { auto newRetShape = new sd::LongType[2]{1, 1}; delete[] retShape; retShape = newRetShape; retShapeLength = 2; } auto ret = shape::shapeBuffer(retShapeLength, sd::ArrayOptions::dataType(originalShapeBuffer), retShape); delete[] retShape; return ret; } SD_HOST sd::LongType *shapeInfoOnlyShapeAndStride(const sd::LongType *shapeInfo, sd::LongType *dimension, int dimensionLength, bool reverseCopyStride, sd::LongType *buffer) { sd::LongType *theShape = shape::shapeOf(shapeInfo); sd::LongType *theStride = shape::stride(shapeInfo); int rank = dimensionLength == 1 ? 2 : dimensionLength; sd::LongType *ret = buffer; // set the rank ret[0] = rank; sd::LongType *retShape = shape::shapeOf(ret); sd::LongType *retStride = shape::stride(ret); int len = rank; if (dimensionLength == 1) { if (shape::isMatrix(theShape, shape::rank(shapeInfo))) { if (dimension[0] == 0) { sd::LongType newStride[2] = {theStride[dimension[0]], 1}; sd::LongType newShape[2] = {theShape[dimension[0]], 1}; retShape[0] = newShape[0]; retShape[1] = newShape[1]; retStride[0] = newStride[0]; retStride[1] = newStride[1]; } else { sd::LongType newStride[2] = {theStride[dimension[0]], 1}; sd::LongType newShape[2] = {theShape[dimension[0]], 1}; retShape[0] = newShape[0]; retShape[1] = newShape[1]; retStride[0] = newStride[0]; retStride[1] = newStride[1]; } } else { sd::LongType newStride[2] = {1, theStride[dimension[0]]}; sd::LongType newShape[2] = {1, theShape[dimension[0]]}; retShape[0] = newShape[0]; retShape[1] = newShape[1]; retStride[0] = newStride[0]; retStride[1] = newStride[1]; } } else { sd::LongType *newIndexes = dimension; if (reverseCopyStride) shape::reverseCopyTo(theStride, retStride, newIndexes, len); else shape::copyTo(len, theStride, retStride, newIndexes); shape::copyTo(len, theShape, retShape, newIndexes); } ret[shape::shapeInfoLength(rank) - 1] = shape::order(shapeInfo); return ret; } SD_HOST sd::LongType *shapeInfoOnlyShapeAndStride(const sd::LongType *shapeInfo, sd::LongType *dimension, int dimensionLength, bool reverseCopyStride) { int rank = dimensionLength == 1 ? 2 : dimensionLength; traceNew(4); sd::LongType *ret = new sd::LongType[shape::shapeInfoLength(rank)]; return shapeInfoOnlyShapeAndStride(shapeInfo, dimension, dimensionLength, reverseCopyStride, ret); } SD_HOST sd::LongType *createShapeInfo(sd::LongType *shape, sd::LongType *stride, int rank) { traceNew(5); sd::LongType *ret = new sd::LongType[shape::shapeInfoLength(rank)]; return createShapeInfo(shape, stride, rank, ret); } SD_HOST sd::LongType *createShapeInfo(sd::LongType *shape, sd::LongType *stride, int rank, sd::LongType *buffer) { buffer[0] = rank; sd::LongType *retShape = shape::shapeOf(buffer); sd::LongType *retStride = shape::stride(buffer); for (int i = 0; i < rank; i++) { retShape[i] = shape[i]; retStride[i] = stride[i]; } return buffer; } #ifndef SD_CUDA /** * Length of a tad given * the shape information */ SD_LIB_EXPORT SD_HOST sd::LongType tadLength(const sd::LongType *shapeInfo, int *dimension, int dimensionLength) { if (dimensionLength == 1) { return shape::shapeOf(shapeInfo)[dimension[0]]; } else { sd::LongType ret = 1; for (int i = 0; i < shape::rank(shapeInfo); i++) { for (int j = 0; j < dimensionLength; j++) { if (i == dimension[j]) ret *= shape::shapeOf(shapeInfo)[dimension[j]]; } } return ret; } } SD_LIB_EXPORT SD_HOST int tadElementWiseStride(sd::LongType *shapeInfo, int *dimension, int dimensionLength) { return reductionIndexElementWiseStride(shapeInfo, dimension, dimensionLength); } SD_LIB_EXPORT SD_HOST bool isEmpty(const sd::LongType *shapeInfo) { return ((shape::extra(shapeInfo) & ARRAY_EMPTY) == ARRAY_EMPTY); } SD_LIB_EXPORT SD_HOST bool strideDescendingCAscendingF(const sd::LongType *shapeBuffer) { int rank = shape::rank(shapeBuffer); sd::LongType *strides = shape::stride(const_cast<sd::LongType *>(shapeBuffer)); char order = shape::order(shapeBuffer); if (shape::isRowVector(shapeBuffer) && strides[0] == 1 && strides[1] == 1) return true; if (order == 'c') { for (int i = 1; i < rank; i++) if (strides[i - 1] <= strides[i]) return false; return true; } else if (order == 'f') { for (int i = 1; i < rank; i++) if (strides[i - 1] >= strides[i]) return false; return true; } else { printf("Unknown order for array!\n"); return false; } } // max array is outer for min array, min array is sub-array of max array // function calculates the coordinates of min array (and saves them into minIdxs) given coordinates of max array // (already stored in maxIdxs) SD_LIB_EXPORT SD_HOST void maxIndToMinInd(int *maxIdxs, int *minIdxs, const sd::LongType *maxShapeInfo, const sd::LongType *minShapeInfo, const int *dimsToExclude, int dimsLen) { const auto maxRank = shape::rank(maxShapeInfo); const auto minRank = shape::rank(minShapeInfo); // if(minRank >= maxRank) // throw std::runtime_error("shape::maxIndToMinInd method: rank of min array should be smaller then rank of max // array!"); if (dimsLen == -1) dimsLen = maxRank - minRank; // if size is not given (= -1) then it is equal to ranks difference if (maxRank == minRank) { if (dimsToExclude == nullptr) { // --> means dimsToExclude == {0,1,2,...,dimsLen-1} for (int i = 0; i < maxRank; ++i) { if (i < dimsLen) minIdxs[i] = maxIdxs[i]; else { if (maxIdxs[i] > minShapeInfo[i + 1]) minIdxs[i] = maxIdxs[i] % minShapeInfo[i + 1]; else if (maxIdxs[i] == minShapeInfo[i + 1]) minIdxs[i] = 0; else minIdxs[i] = maxIdxs[i]; } } } else { for (int i = 0, dim = 0; i < maxRank; ++i) { if (dim < dimsLen && dimsToExclude[dim] == i) { minIdxs[i] = maxIdxs[i]; ++dim; continue; } if (maxIdxs[i] > minShapeInfo[i + 1]) minIdxs[i] = maxIdxs[i] % minShapeInfo[i + 1]; else if (maxIdxs[i] == minShapeInfo[i + 1]) minIdxs[i] = 0; else minIdxs[i] = maxIdxs[i]; } } } else { if (dimsToExclude == nullptr) { // --> means dimsToExclude == {0,1,2,...,dimsLen-1} for (int i = 0; i < minRank; ++i) { if (maxIdxs[i + dimsLen] > minShapeInfo[i + 1]) minIdxs[i] = maxIdxs[i + dimsLen] % minShapeInfo[i + 1]; else if (maxIdxs[i + dimsLen] == minShapeInfo[i + 1]) minIdxs[i] = 0; else minIdxs[i] = maxIdxs[i + dimsLen]; } } else { for (int minI = 0, maxI = 0, dim = 0; maxI < maxRank; ++maxI) { if (dim < dimsLen && dimsToExclude[dim] == maxI) { ++dim; continue; } if (maxIdxs[maxI] == minShapeInfo[minI + 1]) minIdxs[minI] = 0; else if (maxIdxs[maxI] > minShapeInfo[minI + 1]) minIdxs[minI] = maxIdxs[maxI] % minShapeInfo[minI + 1]; else minIdxs[minI] = maxIdxs[maxI]; ++minI; } } } } SD_LIB_EXPORT SD_HOST sd::LongType subArrayIndex(const sd::LongType maxIdx, const sd::LongType *maxShapeInfo, const sd::LongType *minShapeInfo, const int *dimsToExclude, const int dimsLen) { int maxIdxs[SD_MAX_RANK]; shape::index2coords(const_cast<sd::LongType &>(maxIdx), maxShapeInfo, maxIdxs); int minIdxs[SD_MAX_RANK]; maxIndToMinInd(maxIdxs, minIdxs, maxShapeInfo, minShapeInfo, dimsToExclude, dimsLen); return shape::coords2index(minShapeInfo, minIdxs); } ////////////////////////////////////////////////////////////////////// SD_LIB_EXPORT SD_HOST sd::LongType subArrayOffset(const sd::LongType maxIdx, const sd::LongType *maxShapeInfo, const sd::LongType *minShapeInfo, const int *dimsToExclude, const int dimsLen) { int maxIdxs[SD_MAX_RANK]; shape::index2coords(const_cast<sd::LongType &>(maxIdx), maxShapeInfo, maxIdxs); int minIdxs[SD_MAX_RANK]; maxIndToMinInd(maxIdxs, minIdxs, maxShapeInfo, minShapeInfo, dimsToExclude, dimsLen); return getOffset(minShapeInfo, minIdxs); } ////////////////////////////////////////////////////////////////////// SD_LIB_EXPORT SD_HOST int outerArrayOffsets(sd::LongType *maxOffsets, const sd::LongType minIdx, const sd::LongType *maxShapeInfo, const sd::LongType *minShapeInfo, int *memBuff, const int *dimsToExclude) { const auto rankMin = shape::rank(minShapeInfo); const auto rankMax = shape::rank(maxShapeInfo); const auto diff = rankMax - rankMin; // the size of dimsToExclude is equal to diff int *indices = memBuff; int *increment = memBuff + rankMax; int N, minI, maxI; // calculate min per-dim-indices which corresponds to absolute minIdx index shape::index2coords(minIdx, minShapeInfo, indices); // transform storage indices to contain per-dim max indices, purpose - memory saving // fill increment array as well if (dimsToExclude == nullptr) { // means dimsToExclude == {0,1,2,...,diff-1} for (minI = rankMin - 1, maxI = rankMax - 1; maxI >= diff; --maxI, --minI) { increment[maxI] = (maxShapeInfo[maxI + 1] == minShapeInfo[minI + 1]) ? 0 : minShapeInfo[minI + 1]; indices[maxI] = indices[minI]; } for (maxI = 0; maxI < diff; ++maxI) { increment[maxI] = 1; indices[maxI] = 0; } } else { for (N = diff - 1, minI = rankMin - 1, maxI = rankMax - 1; maxI >= 0; --maxI) { if (N >= 0 && dimsToExclude[N] == maxI) { increment[maxI] = 1; indices[maxI] = 0; --N; } else { increment[maxI] = (maxShapeInfo[maxI + 1] == minShapeInfo[minI + 1]) ? 0 : minShapeInfo[minI + 1]; indices[maxI] = indices[minI--]; } } } maxI = rankMax - 1; N = 0; int step; maxOffsets[N++] = shape::getOffset(maxShapeInfo, indices); // nested loops - producing of absolute indices for max array while (maxI >= 0) { if (increment[maxI] != 0) { indices[maxI] += increment[maxI]; if (indices[maxI] >= maxShapeInfo[maxI + 1]) { indices[maxI] %= increment[maxI]; // restore initial value of indices[maxI] step = -1; } else { maxOffsets[N++] = shape::getOffset(maxShapeInfo, indices); step = rankMax - 1 - maxI; } } else if (maxI == rankMax - 1) step = -1; maxI += step; } return N; } ////////////////////////////////////////////////////////////////////// SD_LIB_EXPORT SD_HOST int outerArrayIndexes(int *maxIdxs, const sd::LongType minIdx, const sd::LongType *maxShapeInfo, const sd::LongType *minShapeInfo, const int *dimsToExclude) { const auto rankMin = shape::rank(minShapeInfo); const auto rankMax = shape::rank(maxShapeInfo); const auto diff = rankMax - rankMin; // the size of dimsToExclude is equal to diff int indices[SD_MAX_RANK], increment[SD_MAX_RANK]; int N, minI, maxI; // calculate min per-dim-indices which corresponds to absolute minIdx index shape::index2coords(minIdx, minShapeInfo, indices); // transform storage indices to contain per-dim max indices, purpose - memory saving // fill increment array as well if (dimsToExclude == nullptr) { // means dimsToExclude == {0,1,2,...,diff-1} for (minI = rankMin - 1, maxI = rankMax - 1; maxI >= diff; --maxI, --minI) { increment[maxI] = (maxShapeInfo[maxI + 1] == minShapeInfo[minI + 1]) ? 0 : minShapeInfo[minI + 1]; indices[maxI] = indices[minI]; } for (maxI = 0; maxI < diff; ++maxI) { increment[maxI] = 1; indices[maxI] = 0; } } else { for (N = diff - 1, minI = rankMin - 1, maxI = rankMax - 1; maxI >= 0; --maxI) { if (N >= 0 && dimsToExclude[N] == maxI) { increment[maxI] = 1; indices[maxI] = 0; --N; } else { increment[maxI] = (maxShapeInfo[maxI + 1] == minShapeInfo[minI + 1]) ? 0 : minShapeInfo[minI + 1]; indices[maxI] = indices[minI--]; } } } maxI = rankMax - 1; N = 0; int step; maxIdxs[N++] = shape::coords2index(maxShapeInfo, indices); // nested loops - producing of absolute indices for max array while (maxI >= 0) { if (increment[maxI] != 0) { indices[maxI] += increment[maxI]; if (indices[maxI] >= maxShapeInfo[maxI + 1]) { indices[maxI] %= increment[maxI]; // restore initial value of indices[maxI] step = -1; } else { maxIdxs[N++] = shape::coords2index(maxShapeInfo, indices); step = rankMax - 1 - maxI; } } else if (maxI == rankMax - 1) step = -1; maxI += step; } return N; } #endif /** * Computes the standard packed array strides for a given shape. * * @param shape the shape of a matrix: * @param startNum the start number for the strides * @return the strides for a matrix of n dimensions */ SD_HOST sd::LongType *calcStridesFortran(sd::LongType const *shape, int rank, int startNum) { // if (isVector(shape, rank)) { // traceNew(5); // sd::LongType *ret = new sd::LongType[2]; // for (int i = 0; i < 2; i++) // ret[i] = 1; // return ret; // } int dimensions = rank; traceNew(5); sd::LongType *stride = new sd::LongType[dimensions]; sd::LongType st = startNum; for (int j = 0; j < rank; j++) { stride[j] = st; st *= shape[j]; } return stride; } SD_HOST sd::LongType *calcStridesFortran(sd::LongType const *shape, int rank, int startNum, sd::LongType *ret) { // if (isVector(shape, rank)) { // for (int i = 0; i < rank; i++) // ret[i] = 1; // return ret; // } // int dimensions = rank; sd::LongType st = startNum; for (int j = 0; j < rank; j++) { ret[j] = st; st *= shape[j]; } return ret; } /** * Computes the standard packed array strides for a given shape. * * @param shape the shape of a matrix: * @param startNum the start number for the strides * @return the strides for a matrix of n dimensions */ SD_HOST sd::LongType *calcStrides(sd::LongType const *shape, int rank, int startNum) { traceNew(7); sd::LongType *stride = new sd::LongType[rank]; if (rank == 1) { stride[0] = 1; return stride; } // if (shape::isVector(shape, rank)) { // for (int i = 0; i < 2; i++) // stride[i] = 1; // return stride; // } sd::LongType st = startNum; for (int j = rank - 1; j >= 0; j--) { stride[j] = st; st *= shape[j]; } return stride; } SD_HOST sd::LongType *calcStrides(sd::LongType const *shape, int rank, int startNum, sd::LongType *ret) { if (rank == 1) { ret[0] = 1; return ret; } // if (shape::isVector(shape, rank)) { // for (int i = 0; i < 2; i++) // ret[i] = 1; // return ret; // } sd::LongType st = startNum; for (int j = rank - 1; j >= 0; j--) { ret[j] = st; st *= shape[j]; } return ret; } ////////////////////////////////////////////////////////////////////// SD_HOST void updateStrides(sd::LongType *shapeInfo, const char order) { int rank = shapeInfo[0]; int doubleRank = 2 * rank; if (rank > 0) { if (order == 'c') { shapeInfo[doubleRank] = 1; // set unity as last stride for c order for (int j = 1; j < rank; ++j) { shapeInfo[doubleRank - j] = shapeInfo[doubleRank - j + 1] * shapeInfo[rank + 1 - j]; } } else { shapeInfo[rank + 1] = 1; // set unity as first stride for f order for (int j = rank + 1; j < doubleRank; ++j) { shapeInfo[j + 1] = shapeInfo[j] * shapeInfo[j - rank]; } } } // set last 2 elements in shapeInfo shapeInfo[doubleRank + 2] = 1; shapeInfo[doubleRank + 3] = (int)order; } ////////////////////////////////////////////////////////////////////// SD_HOST void updateStrides(const int rank, const sd::LongType *shapeOnly, sd::LongType *stridesOnly, const char order) { if (rank > 0) { if (order == 'c') { stridesOnly[rank - 1] = 1; // set unity as last stride for c order for (int j = 1; j < rank; ++j) stridesOnly[rank - 1 - j] = stridesOnly[rank - j] * shapeOnly[rank - j]; } else { stridesOnly[0] = 1; // set unity as first stride for f order for (int j = 1; j < rank; ++j) { stridesOnly[j] = stridesOnly[j - 1] * shapeOnly[j - 1]; } } } } /** * @param toCopy the shape to copy * @return a copy of the original struct */ SD_HOST ShapeInformation *shapeCopy(ShapeInformation *toCopy) { auto copy = new ShapeInformation; traceNew(8); copy->shape = new sd::LongType[toCopy->rank]; memcpy(copy->shape, toCopy->shape, toCopy->rank * sizeof(sd::LongType)); traceNew(9); copy->stride = new sd::LongType[toCopy->rank]; for (int i = 0; i < toCopy->rank; i++) { copy->stride[i] = toCopy->stride[i]; } copy->order = toCopy->order; copy->rank = toCopy->rank; copy->offset = toCopy->offset; copy->elementWiseStride = toCopy->elementWiseStride; return copy; } SD_HOST int computeElementWiseStride(int rank, sd::LongType const *shape, sd::LongType const *stride, int isFOrder) { if (rank == 0) return 1; if (shape::isVector(shape, rank)) { return stride[rank - 1]; } else { int oldnd; sd::LongType *oldDims = shape::copyOf(rank, shape); sd::LongType *oldStrides = shape::copyOf(rank, stride); sd::LongType np, op, last_stride; sd::LongType oldStart, oldStop, ok, newStart, newStop, nk; traceNew(10); auto newStrides = new sd::LongType[rank]; oldnd = 0; // set the shape to be 1 x length int newShapeRank = 2; auto newShape = new sd::LongType[newShapeRank]; newShape[0] = 1; newShape[1] = shape::prodLong(shape, rank); /* * Remove axes with dimension 1 from the old array. They have no effect * but would need special cases since their strides do not matter. */ for (oldStart = 0; oldStart < rank; oldStart++) { if (shape[oldStart] != 1) { oldDims[oldnd] = shape[oldStart]; oldStrides[oldnd] = stride[oldStart]; oldnd++; } } np = 1; for (newStart = 0; newStart < newShapeRank; newStart++) { np *= newShape[newStart]; } op = 1; for (oldStart = 0; oldStart < oldnd; oldStart++) { op *= oldDims[oldStart]; } if (np != op) { /* different total sizes; no hope */ delete[] newStrides; delete[] newShape; delete[] oldStrides; delete[] oldDims; return 0; } if (np == 0) { /* the current code does not handle 0-sized arrays, so give up */ delete[] newStrides; delete[] newShape; delete[] oldStrides; delete[] oldDims; return 0; } /* oldStart to oldStop and newStart to newStop give the axis ranges currently worked with */ oldStart = 0; oldStop = 1; newStart = 0; newStop = 1; while (newStart < newShapeRank && oldStart < oldnd) { np = newShape[newStart]; op = oldDims[oldStart]; while (np != op) { if (np < op) { /* Misses trailing 1s, these are handled later */ np *= newShape[newStop++]; } else { op *= oldDims[oldStop++]; } } /* Check whether the original axes can be combined */ for (ok = oldStart; ok < oldStop - 1; ok++) { if (isFOrder) { if (oldStrides[ok + 1] != oldDims[ok] * oldStrides[ok]) { /* not contiguous enough */ delete[] newStrides; delete[] newShape; delete[] oldStrides; delete[] oldDims; return 0; } } else { /* C order */ if (oldStrides[ok] != oldDims[ok + 1] * oldStrides[ok + 1]) { /* not contiguous enough */ delete[] newStrides; delete[] newShape; delete[] oldStrides; delete[] oldDims; return 0; } } } /* Calculate new strides for all axes currently worked with */ if (isFOrder) { newStrides[newStart] = oldStrides[oldStart]; for (nk = newStart + 1; nk < newStop; nk++) { newStrides[nk] = newStrides[nk - 1] * newShape[nk - 1]; } } else { /* C order */ newStrides[newStop - 1] = oldStrides[oldStop - 1]; for (nk = newStop - 1; nk > newStart; nk--) { newStrides[nk - 1] = newStrides[nk] * newShape[nk]; } } newStart = newStop++; oldStart = oldStop++; } /* * Set strides corresponding to trailing 1s of the new shape. */ if (newStart >= 1) { last_stride = newStrides[newStart - 1]; } else { last_stride = stride[rank - 1]; } if (isFOrder) { if (newStart >= 1) last_stride *= newShape[newStart - 1]; } for (nk = newStart; nk < newShapeRank; nk++) { newStrides[nk] = last_stride; } // returns the last element of the new stride array int ret = last_stride; delete[] newStrides; delete[] newShape; delete[] oldStrides; delete[] oldDims; return ret; } } /** * Get the shape info buffer * for the given rank and shape. */ SD_HOST sd::LongType *shapeBuffer(int rank, sd::DataType dtype, sd::LongType const *shape) { sd::LongType *stride = shape::calcStrides(shape, rank); traceNew(11); auto shapeInfo = new shape::ShapeInformation(); shapeInfo->shape = const_cast<sd::LongType *>(shape); shapeInfo->stride = stride; shapeInfo->offset = 0; shapeInfo->rank = rank; int elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0); shapeInfo->order = 'c'; shapeInfo->elementWiseStride = elementWiseStride; auto shapeInfoBuffer = shape::toShapeBuffer(shapeInfo); delete[] stride; delete shapeInfo; sd::ArrayOptions::setDataType(shapeInfoBuffer, dtype); return shapeInfoBuffer; } /** * This is special method, it returns ONLY 2D shapebuffer. * * This method is used only for SoftMax */ SD_HOST sd::LongType *shapeBuffer(int rank, sd::DataType dtype, sd::LongType const *shape, sd::LongType *buffer) { sd::LongType stride[SD_MAX_RANK]; shape::calcStrides(shape, rank, stride); shape::ShapeInformation shapeInfo; shapeInfo.shape = const_cast<sd::LongType *>(shape); shapeInfo.stride = stride; shapeInfo.offset = 0; shapeInfo.rank = rank; auto elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0); shapeInfo.order = 'c'; shapeInfo.elementWiseStride = elementWiseStride; shape::toShapeBuffer(&shapeInfo, buffer); sd::ArrayOptions::setDataType(buffer, dtype); return buffer; } /** * Get the shape info buffer * for the given rank and shape. */ SD_HOST sd::LongType *shapeBufferFortran(int rank, sd::DataType dtype, sd::LongType const *shape) { auto stride = shape::calcStridesFortran(shape, rank); traceNew(12); auto shapeInfo = new shape::ShapeInformation(); shapeInfo->shape = const_cast<sd::LongType *>(shape); shapeInfo->stride = stride; shapeInfo->offset = 0; shapeInfo->rank = rank; int elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0); shapeInfo->order = 'f'; shapeInfo->elementWiseStride = elementWiseStride; auto shapeInfoBuffer = shape::toShapeBuffer(shapeInfo); delete[] stride; delete shapeInfo; sd::ArrayOptions::setDataType(shapeInfoBuffer, dtype); return shapeInfoBuffer; } SD_HOST sd::LongType *shapeBufferFortran(int rank, sd::DataType dtype, sd::LongType const *shape, sd::LongType *output) { sd::LongType stride[SD_MAX_RANK]; shape::calcStridesFortran(shape, rank, stride); shape::ShapeInformation shapeInfo; shapeInfo.shape = const_cast<sd::LongType *>(shape); shapeInfo.stride = stride; shapeInfo.offset = 0; shapeInfo.rank = rank; auto elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0); shapeInfo.order = 'f'; shapeInfo.elementWiseStride = elementWiseStride; shape::toShapeBuffer(&shapeInfo, output); sd::ArrayOptions::setDataType(output, dtype); return output; } /** * * @param length * @param shape * @param rearrange * @return */ SD_HOST sd::LongType *doPermuteSwap(int length, sd::LongType *shape, int *rearrange) { traceNew(16); sd::LongType *ret = new sd::LongType[length]; for (int i = 0; i < length; i++) { ret[i] = shape[rearrange[i]]; } return ret; } /** * * @param length * @param shape * @param rearrange * @return */ SD_HOST void doPermuteSwap(int length, sd::LongType **shape, int *rearrange) { if (length == 1) { return; } else { sd::LongType *shapeDeref = *shape; if (shape::prodLong(shapeDeref, length) < 2) { return; } } bool inOrder = true; for (int i = 0; i < length - 1; i++) { inOrder = inOrder && rearrange[i] + 1 == rearrange[i + 1]; } // all in order, nothing to do if (inOrder) return; sd::LongType *shapeDeref = *shape; // we know they are just reversed, dimension length of 2 if (length == 2) { auto shapeFirst = shapeDeref[0]; auto shapeSecond = shapeDeref[1]; shapeDeref[0] = shapeSecond; shapeDeref[1] = shapeFirst; return; } else if (length == 1) { // no permute return; } auto temp = new sd::LongType[length]; memcpy(temp, shapeDeref, sizeof(sd::LongType) * length); for (int i = 0; i < length; i++) { shapeDeref[i] = temp[rearrange[i]]; } delete[] temp; } SD_HOST void permuteShapeBufferInPlace(sd::LongType *shapeBuffer, int *rearrange, sd::LongType *out) { if (shapeBuffer != out) memcpy(out, shapeBuffer, sizeof(sd::LongType) * shape::shapeInfoLength(shapeBuffer)); shape::doPermuteShapeInfo(out, rearrange); } SD_HOST sd::LongType *permuteShapeBuffer(sd::LongType const *shapeBuffer, int *rearrange) { auto len = shape::shapeInfoLength(shape::rank(shapeBuffer)); sd::LongType *copy = shape::copyOf(len, shapeBuffer); shape::doPermuteShapeInfo(copy, rearrange); return copy; } SD_HOST void doPermuteShapeInfo(sd::LongType *shapeInfo, const int *rearrange, sd::LongType len) { if (len == -1) // calculate array length if it is not given len = shape::length(shapeInfo); // check whether shape is like {1} or {1,1} or {1,1,1,1,...} - in this case we don't need permute if (len == 1) return; const int rank = shape::rank(shapeInfo); // check whether rearrange is like {0,1,2,3,...} - in this case we don't need permute as well bool isPermutNecessary = false; for (int i = 0; i < rank; ++i) if (rearrange[i] != i) { isPermutNecessary = true; break; } if (!isPermutNecessary) return; // check whether rearrange contains correct indexes for (int i = 0; i < rank; ++i) { if (rearrange[i] >= rank || rearrange[i] < 0) { sd_printf( "shape::doPermuteShapeInfo function failed: rearrange indexes are incorrect. Given permute indices must be < rank and >= 0. Rearrange at index %d was %d\n", i, rearrange[i]); return; } } // if everything is ok then perform permute auto temp = new sd::LongType[shape::shapeInfoLength(rank) - 3]; memcpy(temp, shapeInfo, sizeof(sd::LongType) * (shape::shapeInfoLength(rank) - 3)); for (int i = 0; i < rank; ++i) { shapeInfo[i + 1] = temp[rearrange[i] + 1]; shapeInfo[i + 1 + rank] = temp[rearrange[i] + 1 + rank]; } shape::checkStridesEwsAndOrder(shapeInfo); delete[] temp; } SD_HOST sd::LongType *createPermuteIndexes(int originalRank, int *dimension, int dimensionLength) { int delta = originalRank - dimensionLength; traceNew(17); sd::LongType *ret = new sd::LongType[originalRank]; for (int i = 0; i < delta; i++) { ret[i] = i + dimensionLength; } for (int i = delta; i < originalRank; i++) { ret[i] = i - delta; } return ret; } /** * Permute the shape information * @param info the shape information to permute * @param rearrange the order to re arrange * @param rank the rank of the rearrange array */ SD_HOST void permute(ShapeInformation **info, int *rearrange, int rank) { ShapeInformation *infoDeref = *info; checkArrangeArray(rearrange, rank, rank); shape::doPermuteSwap(rank, &infoDeref->shape, rearrange); shape::doPermuteSwap(rank, &infoDeref->stride, rearrange); char order = getOrder(rank, infoDeref->shape, infoDeref->stride, infoDeref->elementWiseStride); infoDeref->order = order; } /** * Return a copy of a buffer. * This buffer allocates memory * that must be freed elsewhere. */ SD_HOST void copyTo(int length, sd::LongType const *from, sd::LongType *to, sd::LongType *indexes) { for (int i = 0; i < length; i++) { to[i] = from[indexes[i]]; } } SD_HOST sd::LongType *sliceOfShapeBuffer(sd::LongType sliceIdx, sd::LongType *shapeBuffer) { int rank = shape::rank(shapeBuffer); int newRank = rank - 1; if (newRank < 2) newRank = 2; sd::LongType *newShapeBuffer = new sd::LongType[shape::shapeInfoLength(newRank)]; newShapeBuffer[0] = newRank; sd::LongType *currShape = shape::shapeOf(shapeBuffer); sd::LongType *currStride = shape::stride(shapeBuffer); // initialize new shape and stride by taking the shape and stride + 1 // and adding to the shape information // a slice is always just taking the existing shape and cutting the first index off // of the shape and stride sd::LongType *newShape = shape::shapeOf(newShapeBuffer); sd::LongType *newStride = shape::stride(newShapeBuffer); if (shape::isVector(shapeBuffer)) { sd::LongType *currShape = shape::shapeOf(shapeBuffer); // row vector: slice index 0 is a valid index, just copy the whole thing if (currShape[0] == 1) { if (sliceIdx == 0) { memcpy(newShapeBuffer, shapeBuffer, shape::shapeInfoByteLength(shape::rank(shapeBuffer))); return newShapeBuffer; } } // column vector: this will be a scalar else { delete[] newShapeBuffer; sd::LongType *scalar = shape::createScalarShapeInfo(); int offset = shape::offset(shapeBuffer); scalar[shape::shapeInfoLength(2) - 3] = offset + sliceIdx; return scalar; } } else if (shape::isMatrix(shapeBuffer)) { newShape[0] = 1; newShape[1] = currShape[1]; newStride[0] = 1; newStride[1] = currStride[1]; } else { for (int i = 0; i < newRank; i++) { newShape[i] = currShape[i + 1]; newStride[i] = currStride[i + 1]; } } auto indices = new sd::LongType[rank]; memset((void *)indices, 0, rank * sizeof(sd::LongType)); indices[0] = sliceIdx; sd::LongType offset = shape::getOffset(newShapeBuffer, indices); newShapeBuffer[shape::shapeInfoLength(newRank) - 3] = offset; // set current order and ews newShapeBuffer[2 * newRank + 2] = shape::elementWiseStride(shapeBuffer); newShapeBuffer[2 * newRank + 3] = shape::order(shapeBuffer); // correct order and ews if necessary shape::checkStridesEwsAndOrder(newShapeBuffer); delete[] indices; return newShapeBuffer; } /** * Returns the element wise stride for this information * buffer relative to a dimension and reduction index */ SD_HOST sd::LongType reductionIndexElementWiseStride(sd::LongType *buffer, int *dimension, int dimensionLength) { if (dimensionLength > 1) { if (shape::order(buffer) == 'f') { /** * The element wise stride belongs to a reduction index. * When used out of order, we can get rid of the data * dependencies and rely on using the max dimension * specified for stride instead. * Say we take the sum(0,1) along arr * we can use arr.stride(1) as a representation * along which to iterate. */ if (shape::shapeOf(buffer)[dimension[dimensionLength - 1]] != 1) { // int tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]]; // return tadElementWiseStride; auto tadElementWiseStride = shape::stride(buffer)[dimension[0]]; return tadElementWiseStride; } return 1; } else { /** * The element wise stride belongs to a reduction index. * When used out of order, we can get rid of the data * dependencies and rely on using the max dimension * specified for stride instead. * Say we take the sum(0,1) along arr * we can use arr.stride(1) as a representation * along which to iterate. */ if (shape::shapeOf(buffer)[dimension[dimensionLength - 1]] != 1) { auto tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]]; return tadElementWiseStride; } return 1; } } else { if (shape::order(buffer) == 'f') { /** * The element wise stride belongs to a reduction index. * When used out of order, we can get rid of the data * dependencies and rely on using the max dimension * specified for stride instead. * Say we take the sum(0,1) along arr * we can use arr.stride(1) as a representation * along which to iterate. */ auto tadElementWiseStride = shape::stride(buffer)[dimension[0]]; return tadElementWiseStride; } else { /** * The element wise stride belongs to a reduction index. * When used out of order, we can get rid of the data * dependencies and rely on using the max dimension * specified for stride instead. * Say we take the sum(0,1) along arr * we can use arr.stride(1) as a representation * along which to iterate. */ auto tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]]; return tadElementWiseStride; } } } SD_HOST sd::LongType *everyIndexBut(const sd::LongType *indexes, int indexesLength, int begin, int end) { int len = end - indexesLength; traceNew(20); auto ret = new sd::LongType[len]; int retIdx = 0; // not here that we do 0 based indexing for end - this assumes things like: // 0 to 4 are specified for (int i = begin; i < end; i++) { bool found = false; for (int j = 0; j < indexesLength; j++) { if (indexes[j] == i) { found = true; break; } } if (!found) { ret[retIdx++] = i; } } return ret; } /** * Keep the given indexes in the data * @param data * @param index * @param indexLength * @param dataLength * @return */ SD_HOST sd::LongType *keep(volatile sd::LongType *data, int const *index, int indexLength, int dataLength) { traceNew(23); sd::LongType *ret = new sd::LongType[indexLength]; int count = 0; for (int i = 0; i < dataLength; i++) { int contains = 0; for (int j = 0; j < indexLength; j++) { if (i == index[j]) { contains = 1; break; } } if (contains) ret[count++] = data[i]; } return ret; } /** * Get the length per slice of the * given shape and the dimension * @param rank the rank of the shape * @param shape the shape of to get * the length per slice for * @param dimension the dimension to * get the length per slice for * @param dimensionLength the length of the dimension array * @return the length per slice of the given shape * along the given dimension */ SD_HOST sd::LongType lengthPerSlice(int rank, sd::LongType const *shape, int const *dimension, int dimensionLength) { if (shape::isVector(shape, rank)) { // return total length for row vectors if (dimensionLength == 1 && shape[0] == 1) { return shape::prodLong(shape, rank); } } else if (rank == dimensionLength) return shape::prodLong(shape, rank); int absSelta = sd::math::sd_abs<int>(rank - dimensionLength); traceNew(27); auto ret2 = shape::removeIndex<sd::LongType>(shape, dimension, rank, dimensionLength); auto ret = prodLong(ret2, absSelta); delete[] ret2; return ret; } /** * calculates the offset for a tensor * @param index * @param arr * @param tensorShape * @return */ SD_HOST sd::LongType sliceOffsetForTensor(int rank, int index, sd::LongType const *shape, sd::LongType const *tensorShape, int tensorShapeLength, int const *dimension, int dimensionLength) { auto tensorLength = prodLong(tensorShape, tensorShapeLength); auto lengthPerSlice2 = lengthPerSlice(rank, shape, dimension, dimensionLength); if (lengthPerSlice2 <= 0) { return 0; } sd::LongType offset = index * tensorLength / lengthPerSlice2; return offset; } /** * Computes the number * of tensors along * a given dimension */ SD_HOST sd::LongType tensorsAlongDimension(volatile int rank, volatile int length, volatile sd::LongType *shape, int *dimension, int dimensionLength) { sd::LongType *tensorShape = shape::keep(shape, dimension, dimensionLength, rank); sd::LongType ret = length / shape::prodLong(tensorShape, dimensionLength); delete[] tensorShape; return ret; } /** * Computes the number * of tensors along * a given dimension */ SD_HOST sd::LongType tensorsAlongDimension(sd::LongType *shapeInfo, int *dimension, int dimensionLength) { sd::LongType *keepShape = shape::shapeOf(shapeInfo); sd::LongType *tensorShape = shape::keep(keepShape, dimension, dimensionLength, rank(shapeInfo)); sd::LongType ret = shape::length(shapeInfo) / shape::prodLong(tensorShape, dimensionLength); delete[] tensorShape; return ret; } ////////////////////////////////////////////////////////////////////// SD_HOST void getOffsetBroadcast(const sd::LongType &startInd, const sd::LongType ind, const sd::LongType *shapeInfo1, const sd::LongType *shapeInfo2, const sd::LongType *shapeInfo3, const bool sameOffsets12, const bool sameOffsets13, int *coords, sd::LongType &offset1, sd::LongType &offset2, sd::LongType &offset3) { const sd::LongType *shape1 = shape::shapeOf(shapeInfo1); const sd::LongType *strides1 = shape::stride(shapeInfo1); const sd::LongType *shape2 = shape::shapeOf(shapeInfo2); const sd::LongType *strides2 = shape::stride(shapeInfo2); const sd::LongType *shape3 = shape::shapeOf(shapeInfo3); const sd::LongType *strides3 = shape::stride(shapeInfo3); if (startInd == ind) { if (shape::rank(shapeInfo1) == 0) { offset1 = offset2 = offset3 = 0; return; } shape::index2coords(ind, shapeInfo1, coords); offset1 = shape::getOffset(shapeInfo1, coords); if (sameOffsets12) offset2 = offset1; else offset2 = shape::getOffset(shapeInfo2, coords); if (sameOffsets13) offset3 = offset1; else offset3 = shape::getOffset(shapeInfo3, coords); return; } int axis = shapeInfo1[0] - 1; while (coords[axis] == shape1[axis] - 1) { if (!sameOffsets12 && shape2[axis] != 1) offset2 -= (shape2[axis] - 1) * strides2[axis]; if (!sameOffsets13 && shape3[axis] != 1) offset3 -= (shape3[axis] - 1) * strides3[axis]; if (shape1[axis] != 1) offset1 -= (shape1[axis] - 1) * strides1[axis]; coords[axis--] = 0; } ++coords[axis]; offset1 += strides1[axis]; if (!sameOffsets12 && shape2[axis] != 1) offset2 += strides2[axis]; if (!sameOffsets13 && shape3[axis] != 1) offset3 += strides3[axis]; if (sameOffsets12) offset2 = offset1; if (sameOffsets13) offset3 = offset1; } /** * Returns a shape buffer * for the shape information metadata. */ SD_HOST sd::LongType *toShapeBuffer(ShapeInformation *info) { traceNew(29); auto ret = new sd::LongType[shapeInfoLength(info->rank)]; int count = 1; int rank = info->rank; ret[0] = info->rank; for (int i = 0; i < rank; i++) { ret[count++] = info->shape[i]; } for (int i = 0; i < rank; i++) { ret[count++] = info->stride[i]; } ret[count++] = info->offset; ret[count++] = info->elementWiseStride; ret[count] = info->order; return ret; } SD_HOST sd::LongType *toShapeBuffer(ShapeInformation *info, sd::LongType *ret) { int count = 1; int rank = info->rank; ret[0] = info->rank; if (ret[0] == 0) { ret[1] = 0; ret[2] = 1; ret[3] = 99; return ret; } for (int i = 0; i < rank; i++) { ret[count++] = info->shape[i]; } for (int i = 0; i < rank; i++) { ret[count++] = info->stride[i]; } ret[count++] = info->offset; ret[count++] = info->elementWiseStride; ret[count++] = info->order; return ret; } SD_HOST void printIntArray(const sd::LongType *arr, const int length) { for (int i = 0; i < length; i++) { printf(" %lld ", (long long)arr[i]); } printf("\n"); } SD_HOST void printIntArray(const int *arr, const int length) { for (int i = 0; i < length; i++) { printf(" %i ", arr[i]); } printf("\n"); } SD_HOST void printShapeInfo(const sd::LongType *shapeInfo) { int rank = shape::rank(shapeInfo); sd::LongType *shape = shape::shapeOf(shapeInfo); printf("Rank %d\n", rank); printf("Shape:\n"); for (int i = 0; i < rank; i++) { printf(" %lld ", (long long)shape[i]); } printf("\n"); sd::LongType *stride = shape::stride(shapeInfo); printf("Stride:\n"); for (int i = 0; i < rank; i++) { printf(" %lld ", (long long)stride[i]); } printf("\n"); printf("Order %c\n", shape::order(shapeInfo)); } SD_HOST void printShapeInfoLinear(const sd::LongType *shapeInfo) { int rank = shape::rank(shapeInfo); int lim = shape::shapeInfoLength(rank); printf("ShapeInfo: ["); for (int i = 0; i < lim; i++) { printf("%lld", (long long)shapeInfo[i]); if (i < lim - 1) { printf(", "); } } printf("]\n"); #ifndef __CUDA_ARCH__ fflush(stdout); #endif } SD_HOST void printShapeInfoLinear(const char *msg, int rank, const sd::LongType *shape, const sd::LongType *strides) { printf("%s : [", msg); for (int i = 0; i < rank; i++) { printf("%lld, ", (long long)shape[i]); } for (int i = 0; i < rank; i++) { printf("%lld", (long long)strides[i]); if (i < rank - 1) printf(", "); } printf("]\n"); #ifndef __CUDA_ARCH__ fflush(stdout); #endif } SD_HOST void printShapeInfoLinear(const char *msg, const sd::LongType *shapeInfo) { int rank = shape::rank(shapeInfo); int lim = shape::shapeInfoLength(rank); printf("%s : [", msg); for (int i = 0; i < lim; i++) { printf("%lld", (long long)shapeInfo[i]); if (i < lim - 1) { printf(", "); } } printf("]\n"); #ifndef __CUDACC__ fflush(stdout); #endif } SD_HOST void printArray(float *arr, int length) { printf("Array: ["); for (int i = 0; i < length; i++) { printf("%f", arr[i]); if (i + 1 < length) printf(", "); } printf("]\n"); } SD_HOST void transposeInplace(sd::LongType *shapeBuffer) { int rank = shape::rank(shapeBuffer); sd::LongType *shape = shape::shapeOf(shapeBuffer); sd::LongType *strides = shape::stride(shapeBuffer); // swap shape for (int e = 0; e < rank / 2; e++) { int idx1 = rank - e - 1; int idx2 = e; int tmp = shape[idx2]; shape[idx2] = shape[idx1]; shape[idx1] = tmp; } // swap strides for (int e = 0; e < rank / 2; e++) { int idx1 = rank - e - 1; int idx2 = e; int tmp = strides[idx2]; strides[idx2] = strides[idx1]; strides[idx1] = tmp; } if (shape::order(shapeBuffer) == 'c') shapeBuffer[shape::shapeInfoLength(shapeBuffer) - 1] = 102; else shapeBuffer[shape::shapeInfoLength(shapeBuffer) - 1] = 99; } SD_HOST int rearMostLeftOverItem(sd::LongType *data, sd::LongType *dimension, int dimensionLength) { sd::LongType *stride = shape::stride(data); // corner case: return the final item when its greater than the max, since its guaranteed to be left over // note here that strides are interpreted in reverse for tad // start from the front rather than the back int rank = shape::rank(data); if (shape::order(data) == 'f') { int dimIdx = dimensionLength - 1; for (int i = rank - 1; i >= 0; i--) { /** * Needs to find an algorithm such that: * looping backwards will find the highest dimension left * that isn't included in the dimension index list. * * This can also be thought of as the last item of the first index * of the difference between the full list of indices and * the dimension indices. * * We should avoid excessive object creation by only looping backwards. */ if (dimension[dimIdx--] != i) { int ret = stride[i]; return ret; } } } else { int dimIdx = dimensionLength - 1; for (int i = rank - 1; i >= 0; i--) { /** * Needs to find an algorithm such that: * looping backwards will find the highest dimension left * that isn't included in the dimension index list. * * This can also be thought of as the last item of the first index * of the difference between the full list of indices and * the dimension indices. * * We should avoid excessive object creation by only looping backwards. */ if (dimension[dimIdx--] != i) { int ret = stride[i]; return ret; } } } int ret = stride[0]; return ret; } SD_HOST sd::LongType *shapeBufferOfNpy(cnpy::NpyArray arr) { return shape::shapeBufferOfNpy(arr.shape.size(), (unsigned int *)arr.shape.data(), arr.fortranOrder); } // SD_HOST sd::LongType *shapeBufferOfNpyBuffer(char *buffer) { // unsigned sd::LongType *shape; // unsigned int ndims, wordSize; // bool fortranOrder; // cnpy::parseNpyHeaderStr(std::string(buffer),wordSize,shape,ndims,fortranOrder); // sd::LongType * ret = shape::shapeBufferOfNpy(ndims,shape,fortranOrder); // delete[] shape; // return ret; // } SD_HOST sd::LongType *shapeBufferOfNpy(int rank, unsigned int *shape, bool fortranOrder) { if (fortranOrder) { sd::LongType *shapeBufferRet = shape::shapeBufferFortran(rank, sd::FLOAT32, (sd::LongType *)shape); return shapeBufferRet; } else { sd::LongType *newShape = new sd::LongType[rank]; for (int i = 0; i < rank; i++) { newShape[i] = shape[i]; } sd::LongType *shapeBufferRet = shape::shapeBuffer(rank, sd::FLOAT32, newShape); delete[] newShape; return shapeBufferRet; } } ////////////////////////////////////////////////////////////////////////// // copy-past from java hasDefaultStridesForShape function SD_HOST bool areStridesDefault(const sd::LongType *shapeInfo) { const int rank = shape::rank(shapeInfo); if (rank == 0) return true; if (!strideDescendingCAscendingF(shapeInfo)) return false; sd::LongType defaultShapeInfo[SD_MAX_SHAPEINFOLENGTH]; memcpy(defaultShapeInfo, shapeInfo, shape::shapeInfoByteLength(shapeInfo)); shape::updateStrides(defaultShapeInfo, shape::order(shapeInfo)); bool result = true; for (int i = rank + 1; i <= 2 * rank; ++i) if (defaultShapeInfo[i] != shapeInfo[i]) { result = false; break; } return result; } ////////////////////////////////////////////////////////////////////// SD_HOST bool reshapeC(const sd::LongType *oldShapeInfo, const char newOrder, const int newRank, const sd::LongType *newShape, sd::LongType *newShapeInfo) { // copy shape from newShape into newShapeInfo newShapeInfo[0] = newRank; memcpy(newShapeInfo + 1, newShape, newRank * sizeof(sd::LongType)); // copy order newShapeInfo[2 * newRank + 3] = newOrder; return shape::reshapeC(oldShapeInfo, newShapeInfo); } ////////////////////////////////////////////////////////////////////// SD_HOST bool reshapeC(const sd::LongType *oldShapeInfo, sd::LongType *newShapeInfo) { // newShapeInfo contains rank, shape and order; but no strides, type and ews const int newRank = shape::rank(newShapeInfo); // if oldShapeInfo is scalar or vector with length=1 if (shape::length(oldShapeInfo) == 1) { for (sd::Unsigned i = 0; i < newRank; ++i) shape::stride(newShapeInfo)[i] = 1; newShapeInfo[2 * newRank + 1] = shape::type(oldShapeInfo); *shape::ews(newShapeInfo) = 1; return true; } const auto oldOrder = shape::order(oldShapeInfo); const auto newOrder = shape::order(newShapeInfo); const auto oldEws = shape::elementWiseStride(const_cast<sd::LongType *>(oldShapeInfo)); if (oldEws > 0 && oldOrder != newOrder) return false; // *** FIRST STAGE - exclude unity dimensions from oldShapeInfo and newShapeInfo (if such are present of course), // since they don't affect on strides evaluation, however they complicate code // FIXME - indeed we don't need to allocate so large memory amount (4*SD_MAX_RANK), sufficient amount is // (2*oldNumOfNonUnities + 2*newNumOfNonUnities) sd::LongType tempBuffer[4 * SD_MAX_RANK]; sd::LongType *oldShape = tempBuffer, *newShape = tempBuffer + 2 * SD_MAX_RANK, *oldStrides, *newStrides; // exclude unities from oldShapeInfo const int oldNumOfNonUnities = shape::excludeUnitiesFromShapeInfo(oldShapeInfo, oldShape, oldStrides); const int newNumOfNonUnities = shape::excludeUnitiesFromShapeInfo(newShapeInfo, newShape, newStrides); // *** SECOND STAGE - strides evaluation int oldStart(0), oldStop(1), newStart(0), newStop(1), newDim, oldDim; while (newStart < newNumOfNonUnities && oldStart < oldNumOfNonUnities) { newDim = newShape[newStart]; oldDim = oldShape[oldStart]; while (newDim != oldDim && newDim > 0 && oldDim > 0) { if (newDim < oldDim) newDim *= newShape[newStop++]; else oldDim *= oldShape[oldStop++]; } // check c-contiguous of old axes range for (sd::Unsigned i = oldStart; i < oldStop - 1; ++i) // do not check value of last stride, it doesn't matter if (oldStrides[i] != oldShape[i + 1] * oldStrides[i + 1]) return false; // not contiguous // fill newStrides in c manner newStrides[newStop - 1] = oldStrides[oldStop - 1]; // copy last stride for (int i = newStop - 2; i >= newStart; --i) newStrides[i] = newStrides[i + 1] * newShape[i + 1]; newStart = newStop++; oldStart = oldStop++; } // fill new calculated strides into newShapeInfo, take into account possible unities in shape for (int j = 0, i = 0; i < newRank; ++i) shape::stride(newShapeInfo)[i] = (shape::shapeOf(newShapeInfo)[i] == 1) ? 1 : newStrides[j++]; // set ews if (oldEws == 0) shape::checkStridesEwsAndOrder(newShapeInfo, newOrder, newNumOfNonUnities, newShape, newStrides); // set ews and order else { newShapeInfo[2 * newRank + 3] = oldOrder; // order *shape::ews(newShapeInfo) = oldEws; // ews } newShapeInfo[2 * newShapeInfo[0] + 1] = 0; sd::ArrayOptions::copyDataType(newShapeInfo, oldShapeInfo); // type return true; } SD_HOST bool canReshape(const int oldRank, sd::LongType *oldShape, const int newRank, sd::LongType *newShapeOf, bool isFOrder) { sd::LongType oldnd; sd::LongType *oldDims = shape::copyOf(oldRank, shape::shapeOf(oldShape)); sd::LongType *oldStrides = shape::copyOf(oldRank, shape::stride(oldShape)); sd::LongType np, op, last_stride; sd::LongType oldStart, oldStop, ok, newStart, newStop, nk; auto newStrides = new sd::LongType[newRank]; oldnd = 0; /* * Remove axes with dimension 1 from the old array. They have no effect * but would need special cases since their strides do not matter. */ for (oldStart = 0; oldStart < oldRank; oldStart++) { if (shape::shapeOf(oldShape)[oldStart] != 1) { oldDims[oldnd] = shape::shapeOf(oldShape)[oldStart]; oldStrides[oldnd] = shape::stride(oldShape)[oldStart]; oldnd++; } } np = 1; for (newStart = 0; newStart < newRank; newStart++) { np *= newShapeOf[newStart]; } op = 1; for (oldStart = 0; oldStart < oldnd; oldStart++) { op *= oldDims[oldStart]; } if (np != op) { /* different total sizes; no hope */ delete[] oldDims; delete[] oldStrides; delete[] newStrides; return false; } if (np == 0) { /* the current code does not handle 0-sized arrays, so give up */ delete[] oldDims; delete[] oldStrides; delete[] newStrides; return false; } /* oldStart to oldStop and newStart to newStop give the axis ranges currently worked with */ oldStart = 0; oldStop = 1; newStart = 0; newStop = 1; while (newStart < newRank && oldStart < oldnd) { np = newShapeOf[newStart]; op = oldDims[oldStart]; while (np != op) { if (np < op) { /* Misses trailing 1s, these are handled later */ np *= newShapeOf[newStop++]; } else { op *= oldDims[oldStop++]; } } /* Check whether the original axes can be combined */ for (ok = oldStart; ok < oldStop - 1; ok++) { if (isFOrder) { if (oldStrides[ok + 1] != oldDims[ok] * oldStrides[ok]) { /* not contiguous enough */ delete[] oldDims; delete[] oldStrides; delete[] newStrides; return false; } } else { /* C order */ if (oldStrides[ok] != oldDims[ok + 1] * oldStrides[ok + 1]) { /* not contiguous enough */ delete[] oldDims; delete[] oldStrides; delete[] newStrides; return false; } } } /* Calculate new strides for all axes currently worked with */ if (isFOrder) { newStrides[newStart] = oldStrides[oldStart]; for (nk = newStart + 1; nk < newStop; nk++) { newStrides[nk] = newStrides[nk - 1] * newShapeOf[nk - 1]; } } else { /* C order */ newStrides[newStop - 1] = oldStrides[oldStop - 1]; for (nk = newStop - 1; nk > newStart; nk--) { newStrides[nk - 1] = newStrides[nk] * newShapeOf[nk]; } } newStart = newStop++; oldStart = oldStop++; } delete[] oldDims; delete[] oldStrides; delete[] newStrides; return true; } ////////////////////////////////////////////////////////////////////// void calcOffsets(const sd::LongType *shapeInfo, sd::LongType *offsets, const char order) { // firstly consider simple case when ews > 0 const sd::LongType ews = shape::elementWiseStride(shapeInfo); if (ews > 0) { // set offset for first sub-array, it is equal to zero always offsets[0] = 0; sd::LongType e = 0; if (order != shape::order(shapeInfo)) for (int i = 1; i <= shape::rank(shapeInfo); ++i) if (shapeInfo[i] != 1) ++e; // check whether input is CommonVector if (order == shape::order(shapeInfo) || e == 1) { // e==1 means common vector e = 1; sd::LongType len = shape::length(shapeInfo); while (e < len) { offsets[e] = offsets[e - 1] + ews; e++; } return; } } shape::calcOffsets(shape::rank(shapeInfo), shape::shapeOf(const_cast<sd::LongType *>(shapeInfo)), shape::stride(const_cast<sd::LongType *>(shapeInfo)), offsets, order); } ////////////////////////////////////////////////////////////////////// void calcOffsets(const int rank, const sd::LongType *shape, const sd::LongType *strides, sd::LongType *offsets, const char order) { const uint64_t len = shape::prodLong(shape, rank); // set offset for first sub-array, it is equal to zero always offsets[0] = 0; sd::Unsigned coords[SD_MAX_RANK]; memset(coords, 0, sizeof(sd::Unsigned) * rank); if (order == 'c') { for (uint64_t i = 1; i < len; ++i) { int axis = rank - 1; offsets[i] = 0; while (coords[axis] == shape[axis] - 1) { offsets[i] -= (shape[axis] - 1) * strides[axis]; coords[axis--] = 0; } ++coords[axis]; offsets[i] += offsets[i - 1] + strides[axis]; } } else { for (uint64_t i = 1; i < len; ++i) { int axis = 0; offsets[i] = 0; while (coords[axis] == shape[axis] - 1) { offsets[i] -= (shape[axis] - 1) * strides[axis]; coords[axis++] = 0; } ++coords[axis]; offsets[i] += offsets[i - 1] + strides[axis]; } } } ////////////////////////////////////////////////////////////////////// void SD_HOST checkStridesEwsAndOrder(sd::LongType *shapeInfo) { // FIXME - indeed we don't need to allocate so large memory amount (2*SD_MAX_RANK), sufficient amount is // (2*oldNumOfNonUnities + 2*newNumOfNonUnities) sd::LongType tempBuffer[2 * SD_MAX_RANK]; sd::LongType *shape = tempBuffer, *strides; // exclude unities from shapeInfo const int numOfNonUnities = shape::excludeUnitiesFromShapeInfo(shapeInfo, shape, strides); shape::checkStridesEwsAndOrder(shapeInfo, shape::order(shapeInfo), numOfNonUnities, shape, strides); } ////////////////////////////////////////////////////////////////////// void SD_HOST checkStridesEwsAndOrder(sd::LongType *shapeInfo, const char proposedOrder, const int numOfNonUnities, const sd::LongType *shapeNoUnities, const sd::LongType *stridesNoUnities) { const int rank = shape::rank(shapeInfo); if (shape::length(shapeInfo) == 1) { *shape::ews(shapeInfo) = 1; shapeInfo[rank * 2 + 3] = (int)proposedOrder; return; } if (numOfNonUnities == 1) { // case of common vector *shape::ews(shapeInfo) = *stridesNoUnities; shapeInfo[rank * 2 + 3] = (int)proposedOrder; return; } bool contiguous = true; //*** check whether strides are in c contiguous order ***// for (sd::Unsigned i = 0; i < numOfNonUnities - 1; ++i) { if (stridesNoUnities[i] != shapeNoUnities[i + 1] * stridesNoUnities[i + 1]) { contiguous = false; break; } } if (contiguous) { *shape::ews(shapeInfo) = stridesNoUnities[numOfNonUnities - 1]; shapeInfo[rank * 2 + 3] = 99; return; } contiguous = true; //*** check whether strides are in f contiguous order ***// for (sd::Unsigned i = 1; i < numOfNonUnities; ++i) { if (stridesNoUnities[i] != shapeNoUnities[i - 1] * stridesNoUnities[i - 1]) { contiguous = false; break; } } if (contiguous) { *shape::ews(shapeInfo) = stridesNoUnities[0]; shapeInfo[rank * 2 + 3] = 102; return; } *shape::ews(shapeInfo) = 0; shapeInfo[rank * 2 + 3] = (int)proposedOrder; } ////////////////////////////////////////////////////////////////////// SD_HOST void calcSubArrsShapeInfoAndOffsets(const sd::LongType *wholeShapeInfo, const sd::LongType numOfSubArrs, const int dimsSize, const int *dimsToExclude, sd::LongType *subArrShapeInfo, sd::LongType *subArrOffsets, bool keepUnitiesInShape) { const int rank = shape::rank(wholeShapeInfo); if (dimsSize == rank || dimsSize == 0) { // means there is one sub-array and it coincides with whole array, return // copy of wholeShapeInfo and one zero offset in this case memcpy(subArrShapeInfo, wholeShapeInfo, shape::shapeInfoLength(rank) * sizeof(sd::LongType)); *subArrOffsets = 0; return; } const int subArrRank = keepUnitiesInShape ? rank : rank - dimsSize; subArrShapeInfo[0] = subArrRank; // rank subArrShapeInfo[2 * subArrRank + 1] = 0; // clear (to avoid uninitialized) sd::ArrayOptions::copyDataType(subArrShapeInfo, wholeShapeInfo); // type subArrShapeInfo[2 * subArrRank + 3] = shape::order(wholeShapeInfo); // order sd::LongType *shape = new sd::LongType[dimsSize]; sd::LongType *strides = new sd::LongType[dimsSize]; for (int k = subArrRank - 1, j = dimsSize - 1, i = rank - 1; i >= 0; --i) { if (j >= 0 && i == dimsToExclude[j]) { strides[j] = shape::stride(wholeShapeInfo)[i]; shape[j--] = shape::shapeOf(wholeShapeInfo)[i]; if (keepUnitiesInShape) { shape::shapeOf(subArrShapeInfo)[k] = 1; shape::stride(subArrShapeInfo)[k--] = shape::stride(wholeShapeInfo)[i]; } } else { shape::shapeOf(subArrShapeInfo)[k] = shape::shapeOf(wholeShapeInfo)[i]; shape::stride(subArrShapeInfo)[k--] = shape::stride(wholeShapeInfo)[i]; } } // calculation of sub-array offsets (subArrOffsets) shape::calcOffsets(dimsSize, shape, strides, subArrOffsets); // evaluate ews shape::checkStridesEwsAndOrder(subArrShapeInfo); delete[] strides; delete[] shape; } ////////////////////////////////////////////////////////////////////// void calcSubArrShapeInfoAndOffset(const sd::LongType *idx, const sd::LongType *maxShapeInfo, sd::LongType *minShapeInfo, sd::LongType &minOffset, const bool keepUnitiesInShape, const bool isStrided, const int numOfUntiesInMinShape) { const sd::Unsigned maxRank = shape::rank(maxShapeInfo); minOffset = 0; sd::Unsigned first, last, stride, n(isStrided ? 3 : 2); minShapeInfo[0] = keepUnitiesInShape ? maxRank : maxRank - numOfUntiesInMinShape; for (sd::Unsigned step = 0, j = 0, i = 0; i < maxRank; ++i, step += n) { if (idx[step] == idx[step + 1]) { // means whole dimension shape::shapeOf(minShapeInfo)[j] = shape::shapeOf(maxShapeInfo)[i]; shape::stride(minShapeInfo)[j++] = shape::stride(maxShapeInfo)[i]; } else { first = idx[step] >= 0 ? idx[step] : idx[step] + shape::sizeAt(maxShapeInfo, i) + 1; last = idx[step + 1] >= 0 ? idx[step + 1] : idx[step + 1] + shape::sizeAt(maxShapeInfo, i) + 1; if (last < first) throw("shape::calcSubArrShapeInfoAndOffset: negative range in input indexes is found!"); if (isStrided) { stride = idx[step + 2]; last /*resulting sub-array axis*/ = (last - first + stride - 1) / stride; // ceil (last - first) / stride; } else { stride = 1; last /*resulting sub-array axis*/ = last - first; } minOffset += first * shape::stride(maxShapeInfo)[i]; if (!keepUnitiesInShape && last == 1) continue; shape::shapeOf(minShapeInfo)[j] = last; shape::stride(minShapeInfo)[j++] = last == 1 ? shape::stride(maxShapeInfo)[i] : shape::stride(maxShapeInfo)[i] * stride; } } minShapeInfo[2 * shape::rank(minShapeInfo) + 1] = 0; // zero minShapeInfo[2 * shape::rank(minShapeInfo) + 3] = shape::order(maxShapeInfo); // order sd::ArrayOptions::copyDataType(minShapeInfo, maxShapeInfo); // type shape::checkStridesEwsAndOrder(minShapeInfo); } ////////////////////////////////////////////////////////////////////// SD_HOST int excludeUnitiesFromShapeInfo(const sd::LongType *inShapeInfo, sd::LongType *&shapeNoUnities, sd::LongType *&stridesNoUnities) { const int rank = shape::rank(inShapeInfo); const int numOfNonUnities = shape::numOfNonUnitDims(rank, shape::shapeOf(inShapeInfo)); if (numOfNonUnities == rank) { // no unities in shape, no copy procedure shapeNoUnities = const_cast<sd::LongType *>(inShapeInfo) + 1; stridesNoUnities = const_cast<sd::LongType *>(inShapeInfo) + 1 + rank; return numOfNonUnities; } for (sd::Unsigned j = 0, i = 0; i < rank; ++i) { if (shape::shapeOf(inShapeInfo)[i] != 1) { shapeNoUnities[j] = shape::shapeOf(inShapeInfo)[i]; shapeNoUnities[numOfNonUnities + j++] = shape::stride(inShapeInfo)[i]; } } stridesNoUnities = shapeNoUnities + numOfNonUnities; return numOfNonUnities; } ////////////////////////////////////////////////////////////////////// SD_HOST void excludeUnitiesFromShapeInfo(const sd::LongType *inShapeInfo, const int *dimsToExclude, const int dimsSize, sd::LongType *outShapeInfo) { outShapeInfo[0] = inShapeInfo[0] - dimsSize; for (sd::Unsigned j = 0, k = 0, i = 0; i < inShapeInfo[0]; ++i) { if (j < dimsSize && i == dimsToExclude[j]) { ++j; continue; } shape::shapeOf(outShapeInfo)[k] = shape::shapeOf(inShapeInfo)[i]; shape::stride(outShapeInfo)[k++] = shape::stride(inShapeInfo)[i]; } outShapeInfo[2 * outShapeInfo[0] + 1] = 0; sd::ArrayOptions::copyDataType(outShapeInfo, inShapeInfo); // type *shape::ews(outShapeInfo) = shape::elementWiseStride(inShapeInfo); // ews outShapeInfo[2 * outShapeInfo[0] + 3] = shape::order(inShapeInfo); // order } }
33.512845
176
0.577083
[ "object", "shape", "vector", "transform" ]
847d4e03892fb3648c11e1c7b04a2a6bbd452f1c
16,746
cpp
C++
common/SoapyRPCSocket.cpp
antonblanchard/SoapyRemote
6d9bd820da470cfe7b27b2e6946af93cfece448f
[ "BSL-1.0" ]
null
null
null
common/SoapyRPCSocket.cpp
antonblanchard/SoapyRemote
6d9bd820da470cfe7b27b2e6946af93cfece448f
[ "BSL-1.0" ]
null
null
null
common/SoapyRPCSocket.cpp
antonblanchard/SoapyRemote
6d9bd820da470cfe7b27b2e6946af93cfece448f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2015-2019 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include "SoapySocketDefs.hpp" #include "SoapyRPCSocket.hpp" #include "SoapyURLUtils.hpp" #include <SoapySDR/Logger.hpp> #include <cstring> //strerror #include <cerrno> //errno #include <algorithm> //max #include <mutex> static std::mutex sessionMutex; static size_t sessionCount = 0; SoapySocketSession::SoapySocketSession(void) { std::lock_guard<std::mutex> lock(sessionMutex); sessionCount++; if (sessionCount > 1) return; #ifdef _MSC_VER WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); int ret = WSAStartup(wVersionRequested, &wsaData); if (ret != 0) { SoapySDR::logf(SOAPY_SDR_ERROR, "SoapySocketSession::WSAStartup: %d", ret); } #endif } SoapySocketSession::~SoapySocketSession(void) { std::lock_guard<std::mutex> lock(sessionMutex); sessionCount--; if (sessionCount > 0) return; #ifdef _MSC_VER WSACleanup(); #endif } void SoapyRPCSocket::setDefaultTcpSockOpts(void) { if (this->null()) return; int one = 1; int ret = ::setsockopt(_sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one)); if (ret != 0) { this->reportError("setsockopt(TCP_NODELAY)"); } #ifdef TCP_QUICKACK ret = ::setsockopt(_sock, IPPROTO_TCP, TCP_QUICKACK, (const char *)&one, sizeof(one)); if (ret != 0) { this->reportError("setsockopt(TCP_QUICKACK)"); } #endif //TCP_QUICKACK } SoapyRPCSocket::SoapyRPCSocket(void): _sock(INVALID_SOCKET) { return; } SoapyRPCSocket::SoapyRPCSocket(const std::string &url): _sock(INVALID_SOCKET) { SoapyURL urlObj(url); SockAddrData addr; const auto errorMsg = urlObj.toSockAddr(addr); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+url+")", errorMsg); } else { _sock = ::socket(addr.addr()->sa_family, urlObj.getType(), 0); } } SoapyRPCSocket::~SoapyRPCSocket(void) { if (this->close() != 0) { SoapySDR::logf(SOAPY_SDR_ERROR, "SoapyRPCSocket::~SoapyRPCSocket: %s", this->lastErrorMsg()); } } bool SoapyRPCSocket::null(void) { return _sock == INVALID_SOCKET; } bool SoapyRPCSocket::status(void) { int opt = 0; socklen_t optlen = sizeof(opt); ::getsockopt(_sock, SOL_SOCKET, SO_ERROR, (char *)&opt, &optlen); if (opt != 0) this->reportError("getsockopt(SO_ERROR)", opt); return opt == 0; } int SoapyRPCSocket::close(void) { if (this->null()) return 0; int ret = ::closesocket(_sock); _sock = INVALID_SOCKET; if (ret != 0) this->reportError("closesocket()"); return ret; } int SoapyRPCSocket::bind(const std::string &url) { SoapyURL urlObj(url); SockAddrData addr; const auto errorMsg = urlObj.toSockAddr(addr); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+url+")", errorMsg); return -1; } if (this->null()) _sock = ::socket(addr.addr()->sa_family, urlObj.getType(), 0); if (this->null()) { this->reportError("socket("+url+")"); return -1; } //setup reuse address int one = 1; int ret = ::setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&one, sizeof(one)); if (ret != 0) { this->reportError("setsockopt(SO_REUSEADDR)"); } #ifdef __APPLE__ ret = ::setsockopt(_sock, SOL_SOCKET, SO_REUSEPORT, (const char *)&one, sizeof(one)); if (ret != 0) { this->reportError("setsockopt(SO_REUSEPORT)"); } #endif //__APPLE__ if (urlObj.getType() == SOCK_STREAM) this->setDefaultTcpSockOpts(); ret = ::bind(_sock, addr.addr(), addr.addrlen()); if (ret == -1) this->reportError("bind("+url+")"); return ret; } int SoapyRPCSocket::listen(int backlog) { int ret = ::listen(_sock, backlog); if (ret == -1) this->reportError("listen()"); return ret; } SoapyRPCSocket *SoapyRPCSocket::accept(void) { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); int client = ::accept(_sock, (struct sockaddr*)&addr, &addrlen); if (client == INVALID_SOCKET) return NULL; SoapyRPCSocket *clientSock = new SoapyRPCSocket(); clientSock->_sock = client; clientSock->setDefaultTcpSockOpts(); return clientSock; } int SoapyRPCSocket::connect(const std::string &url) { SoapyURL urlObj(url); SockAddrData addr; const auto errorMsg = urlObj.toSockAddr(addr); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+url+")", errorMsg); return -1; } if (this->null()) _sock = ::socket(addr.addr()->sa_family, urlObj.getType(), 0); if (this->null()) { this->reportError("socket("+url+")"); return -1; } if (urlObj.getType() == SOCK_STREAM) this->setDefaultTcpSockOpts(); int ret = ::connect(_sock, addr.addr(), addr.addrlen()); if (ret == -1) this->reportError("connect("+url+")"); return ret; } int SoapyRPCSocket::connect(const std::string &url, const long timeoutUs) { SoapyURL urlObj(url); SockAddrData addr; const auto errorMsg = urlObj.toSockAddr(addr); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+url+")", errorMsg); return -1; } if (this->null()) _sock = ::socket(addr.addr()->sa_family, urlObj.getType(), 0); if (this->null()) { this->reportError("socket("+url+")"); return -1; } if (urlObj.getType() == SOCK_STREAM) this->setDefaultTcpSockOpts(); //enable non blocking int ret = this->setNonBlocking(true); if (ret != 0) return ret; //non blocking connect, check for non busy ret = ::connect(_sock, addr.addr(), addr.addrlen()); if (ret != 0 and SOCKET_ERRNO != SOCKET_EINPROGRESS) { this->reportError("connect("+url+")"); return ret; } //fill in the select structures struct timeval tv; tv.tv_sec = timeoutUs / 1000000; tv.tv_usec = timeoutUs % 1000000; fd_set fds; FD_ZERO(&fds); FD_SET(_sock, &fds); //wait for connect or timeout ret = ::select(_sock+1, NULL, &fds, NULL, &tv); if (ret != 1) { this->reportError("connect("+url+")", SOCKET_ETIMEDOUT); return -1; } //get the error code from connect() int opt = 0; socklen_t optlen = sizeof(opt); ::getsockopt(_sock, SOL_SOCKET, SO_ERROR, (char *)&opt, &optlen); if (opt != 0) { this->reportError("connect("+url+")", opt); return opt; } //revert non blocking on socket ret = this->setNonBlocking(false); if (ret != 0) return ret; return opt; } int SoapyRPCSocket::setNonBlocking(const bool nonblock) { int ret = 0; #ifdef _MSC_VER u_long mode = nonblock?1:0; // 1 to enable non-blocking socket ret = ioctlsocket(_sock, FIONBIO, &mode); #else int mode = fcntl(_sock, F_GETFL, 0); if (nonblock) mode |= O_NONBLOCK; else mode &= ~(O_NONBLOCK); ret = fcntl(_sock, F_SETFL, mode); #endif if (ret != 0) this->reportError("setNonBlocking("+std::string(nonblock?"true":"false")+")"); return ret; } int SoapyRPCSocket::multicastJoin(const std::string &group, const std::string &sendAddr, const std::vector<std::string> &recvAddrs, const bool loop, const int ttl) { /* * Multicast join docs: * http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html * http://www.tenouk.com/Module41c.html */ //lookup group url SoapyURL urlObj(group); SockAddrData addr; auto errorMsg = urlObj.toSockAddr(addr); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+group+")", errorMsg); return -1; } //lookup send url SockAddrData sendAddrData; errorMsg = SoapyURL("", sendAddr).toSockAddr(sendAddrData); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+sendAddr+")", errorMsg); return -1; } //create socket if null if (this->null()) _sock = ::socket(addr.addr()->sa_family, SOCK_DGRAM, 0); if (this->null()) { this->reportError("socket("+group+")"); return -1; } int ret = 0; int loopInt = loop?1:0; switch(addr.addr()->sa_family) { case AF_INET: { //setup IP_MULTICAST_LOOP ret = ::setsockopt(_sock, IPPROTO_IP, IP_MULTICAST_LOOP, (const char *)&loopInt, sizeof(loopInt)); if (ret != 0) { this->reportError("setsockopt(IP_MULTICAST_LOOP)"); return -1; } //setup IP_MULTICAST_TTL ret = ::setsockopt(_sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&ttl, sizeof(ttl)); if (ret != 0) { this->reportError("setsockopt(IP_MULTICAST_TTL)"); return -1; } //setup IP_MULTICAST_IF auto *send_addr_in = (const struct sockaddr_in *)sendAddrData.addr(); ret = ::setsockopt(_sock, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&send_addr_in->sin_addr, sizeof(send_addr_in->sin_addr)); if (ret != 0) { this->reportError("setsockopt(IP_MULTICAST_IF, "+sendAddr+")"); return -1; } //setup IP_ADD_MEMBERSHIP auto *addr_in = (const struct sockaddr_in *)addr.addr(); for (const auto &recvAddr : recvAddrs) { SockAddrData recvAddrData; errorMsg = SoapyURL("", recvAddr).toSockAddr(recvAddrData); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+sendAddr+")", errorMsg); return -1; } struct ip_mreq mreq; mreq.imr_multiaddr = addr_in->sin_addr; mreq.imr_interface = ((const struct sockaddr_in *)recvAddrData.addr())->sin_addr; ret = ::setsockopt(_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq)); if (ret != 0) { this->reportError("setsockopt(IP_ADD_MEMBERSHIP, "+recvAddr+")"); return -1; } } break; } case AF_INET6: { //setup IPV6_MULTICAST_LOOP ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (const char *)&loopInt, sizeof(loopInt)); if (ret != 0) { this->reportError("setsockopt(IPV6_MULTICAST_LOOP)"); return -1; } //setup IPV6_MULTICAST_HOPS ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char *)&ttl, sizeof(ttl)); if (ret != 0) { this->reportError("setsockopt(IPV6_MULTICAST_HOPS)"); return -1; } //setup IPV6_MULTICAST_IF auto *send_addr_in6 = (const struct sockaddr_in6 *)sendAddrData.addr(); ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, (const char *)&send_addr_in6->sin6_scope_id, sizeof(send_addr_in6->sin6_scope_id)); if (ret != 0) { this->reportError("setsockopt(IPV6_MULTICAST_IF, "+sendAddr+")"); return -1; } //setup IPV6_ADD_MEMBERSHIP auto *addr_in6 = (const struct sockaddr_in6 *)addr.addr(); for (const auto &recvAddr : recvAddrs) { SockAddrData recvAddrData; errorMsg = SoapyURL("", recvAddr).toSockAddr(recvAddrData); if (not errorMsg.empty()) { this->reportError("getaddrinfo("+sendAddr+")", errorMsg); return -1; } struct ipv6_mreq mreq6; mreq6.ipv6mr_multiaddr = addr_in6->sin6_addr; mreq6.ipv6mr_interface = ((const struct sockaddr_in6 *)recvAddrData.addr())->sin6_scope_id;; ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (const char *)&mreq6, sizeof(mreq6)); if (ret != 0) { this->reportError("setsockopt(IPV6_ADD_MEMBERSHIP, "+recvAddr+")"); return -1; } } break; } default: break; } return 0; } int SoapyRPCSocket::send(const void *buf, size_t len, int flags) { int ret = ::send(_sock, (const char *)buf, int(len), flags | MSG_NOSIGNAL); if (ret == -1) this->reportError("send()"); return ret; } int SoapyRPCSocket::recv(void *buf, size_t len, int flags) { int ret = ::recv(_sock, (char *)buf, int(len), flags); if (ret == -1) this->reportError("recv()"); return ret; } int SoapyRPCSocket::sendto(const void *buf, size_t len, const std::string &url, int flags) { SockAddrData addr; SoapyURL(url).toSockAddr(addr); int ret = ::sendto(_sock, (char *)buf, int(len), flags, addr.addr(), addr.addrlen()); if (ret == -1) this->reportError("sendto("+url+")"); return ret; } int SoapyRPCSocket::recvfrom(void *buf, size_t len, std::string &url, int flags) { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); int ret = ::recvfrom(_sock, (char *)buf, int(len), flags, (struct sockaddr*)&addr, &addrlen); if (ret == -1) this->reportError("recvfrom()"); else url = SoapyURL((struct sockaddr *)&addr).toString(); return ret; } bool SoapyRPCSocket::selectRecv(const long timeoutUs) { struct timeval tv; tv.tv_sec = timeoutUs / 1000000; tv.tv_usec = timeoutUs % 1000000; fd_set readfds; FD_ZERO(&readfds); FD_SET(_sock, &readfds); int ret = ::select(_sock+1, &readfds, NULL, NULL, &tv); if (ret == -1) this->reportError("select()"); return ret == 1; } int SoapyRPCSocket::selectRecvMultiple(const std::vector<SoapyRPCSocket *> &socks, const long timeoutUs) { struct timeval tv; tv.tv_sec = timeoutUs / 1000000; tv.tv_usec = timeoutUs % 1000000; fd_set readfds; FD_ZERO(&readfds); int maxSock(socks.front()->_sock); for (const auto &sock : socks) { maxSock = std::max(sock->_sock, maxSock); FD_SET(sock->_sock, &readfds); } int ret = ::select(maxSock+1, &readfds, NULL, NULL, &tv); if (ret == -1) return ret; int mask = 0; for (size_t i = 0; i < socks.size(); i++) { if (FD_ISSET(socks[i]->_sock, &readfds)) mask |= (1 << i); } return mask; } static std::string errToString(const int err) { char buff[1024]; #ifdef _MSC_VER FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, sizeof(buff), NULL); return buff; #else //http://linux.die.net/man/3/strerror_r #ifdef STRERROR_R_XSI strerror_r(err, buff, sizeof(buff)); #else //this version may decide to use its own internal string return strerror_r(err, buff, sizeof(buff)); #endif return buff; #endif } void SoapyRPCSocket::reportError(const std::string &what) { this->reportError(what, SOCKET_ERRNO); } void SoapyRPCSocket::reportError(const std::string &what, const int err) { if (err == 0) _lastErrorMsg = what; else this->reportError(what, std::to_string(err) + ": " + errToString(err)); } void SoapyRPCSocket::reportError(const std::string &what, const std::string &errorMsg) { _lastErrorMsg = what + " [" + errorMsg + "]"; } std::string SoapyRPCSocket::getsockname(void) { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); int ret = ::getsockname(_sock, (struct sockaddr *)&addr, &addrlen); if (ret == -1) this->reportError("getsockname()"); if (ret != 0) return ""; return SoapyURL((struct sockaddr *)&addr).toString(); } std::string SoapyRPCSocket::getpeername(void) { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); int ret = ::getpeername(_sock, (struct sockaddr *)&addr, &addrlen); if (ret == -1) this->reportError("getpeername()"); if (ret != 0) return ""; return SoapyURL((struct sockaddr *)&addr).toString(); } int SoapyRPCSocket::setBuffSize(const bool isRecv, const size_t numBytes) { int opt = int(numBytes); int ret = ::setsockopt(_sock, SOL_SOCKET, isRecv?SO_RCVBUF:SO_SNDBUF, (const char *)&opt, sizeof(opt)); if (ret == -1) this->reportError("setsockopt("+std::string(isRecv?"SO_RCVBUF":"SO_SNDBUF")+")"); return ret; } int SoapyRPCSocket::getBuffSize(const bool isRecv) { int opt = 0; socklen_t optlen = sizeof(opt); int ret = ::getsockopt(_sock, SOL_SOCKET, isRecv?SO_RCVBUF:SO_SNDBUF, (char *)&opt, &optlen); if (ret == -1) this->reportError("getsockopt("+std::string(isRecv?"SO_RCVBUF":"SO_SNDBUF")+")"); if (ret != 0) return ret; //adjustment for linux kernel socket buffer doubling for bookkeeping #ifdef __linux opt = opt/2; #endif return opt; }
28.674658
167
0.611728
[ "vector" ]
847dfbd96047241dc054e1e5f88ee4cddbe51696
3,967
cpp
C++
first_year/mp/sesion5/src/SecuenciaEnteros.cpp
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
first_year/mp/sesion5/src/SecuenciaEnteros.cpp
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
first_year/mp/sesion5/src/SecuenciaEnteros.cpp
chelunike/trust_me_i_am_an_engineer
40261dd8a6699910ef7d6bb7f63e2b961d6ae027
[ "Apache-2.0" ]
null
null
null
/***************************************************************************/ // FUNDAMENTOS DE PROGRAMACIÓN // // (C) FRANCISCO JOSÉ CORTIJO BON // DEPARTAMENTO DE CIENCIAS DE LA COMPUTACIÓN E INTELIGENCIA ARTIFICIAL // // Clase "SecuenciaEnteros" // Versión mínima operativa. // // Fichero: SecuenciaEnteros.cpp // /***************************************************************************/ #include <string> #include "SecuenciaEnteros.h" using namespace std; /***************************************************************************/ // Constructor sin argumentos SecuenciaEnteros :: SecuenciaEnteros (void) : total_utilizados (0) {} /***************************************************************************/ // Devuelve el número de casillas ocupadas int SecuenciaEnteros :: TotalUtilizados (void) { return (total_utilizados); } /***************************************************************************/ // Devuelve el número de casillas disponibles int SecuenciaEnteros :: Capacidad (void) { return (TAMANIO); } /***************************************************************************/ // "Vacía" completamente la secuencia void SecuenciaEnteros :: EliminaTodos(void) { total_utilizados = 0; } /***************************************************************************/ // Añade un elemento ("nuevo") al vector. // PRE: total_utilizados < TAMANIO // La adición se realiza si hay alguna casilla disponible. // El nuevo elemento se coloca al final del vector. // Si no hay espacio, no se hace nada. void SecuenciaEnteros :: Aniade (int nuevo) { if (total_utilizados < TAMANIO){ vector_privado[total_utilizados] = nuevo; total_utilizados++; } } /***************************************************************************/ // Devuelve el elemento de la casilla "indice" // PRE: 0 <= indice < total_utilizados int SecuenciaEnteros :: Elemento (int indice) { return (vector_privado[indice]); } /***************************************************************************/ // Cambia el contenido de la casilla "indice" por el valor "nuevo" // PRE: 0 <= indice < total_utilizados void SecuenciaEnteros :: Modifica (int indice, int nuevo) { if ((indice >= 0) && (indice < total_utilizados)) { vector_privado[indice] = nuevo; } } /***************************************************************************/ // Eliminar el carácter de la posición dada por "indice". // Realiza un borrado físico (desplazamiento y sustitución). // PRE: 0 <= indice < total_utilizados void SecuenciaEnteros :: Elimina (int indice) { if ((indice >= 0) && (indice < total_utilizados)) { int tope = total_utilizados-1; // posic. del último for (int i = indice ; i < tope ; i++) vector_privado[i] = vector_privado[i+1]; total_utilizados--; } } /***************************************************************************/ // Inserta el carácter "nuevo" en la posición dada por "indice". // Desplaza todos los caracteres una posición a la derecha antes de // copiar en "indice" en valor "nuevo". // PRE: 0 <= indice < total_utilizados void SecuenciaEnteros :: Inserta (int indice, int valor_nuevo) { if ((total_utilizados < TAMANIO) && (indice >= 0) && (indice < total_utilizados)) { for (int i = total_utilizados ; i > indice ; i--) vector_privado[i] = vector_privado[i-1]; vector_privado[indice] = valor_nuevo; total_utilizados++; } } /***************************************************************************/ // Compone un string con todos los enteros que están // almacenados en la secuencia y lo devuelve. string SecuenciaEnteros :: ToString() { string cadena; cadena = "[ "; for (int i=0; i<total_utilizados; i++) cadena = cadena + " " + to_string(vector_privado[i]); cadena = cadena + "]"; return (cadena); } /***************************************************************************/
28.539568
77
0.50542
[ "vector" ]
847f6f2084779c713eed615024a18401c4ea5ccd
2,052
cc
C++
cpp_src/core/selectfunc/functions/highlight.cc
AlexSnet/reindexer
6de57939bbd5968954427ef0b3ca58ef9134caaa
[ "Apache-2.0" ]
695
2017-07-07T16:54:23.000Z
2022-03-19T09:48:30.000Z
cpp_src/core/selectfunc/functions/highlight.cc
AlexSnet/reindexer
6de57939bbd5968954427ef0b3ca58ef9134caaa
[ "Apache-2.0" ]
63
2018-01-18T02:57:48.000Z
2022-03-04T10:28:05.000Z
cpp_src/core/selectfunc/functions/highlight.cc
AlexSnet/reindexer
6de57939bbd5968954427ef0b3ca58ef9134caaa
[ "Apache-2.0" ]
72
2017-07-12T21:12:59.000Z
2021-11-28T14:35:06.000Z
#include "highlight.h" #include "core/keyvalue/key_string.h" #include "core/keyvalue/p_string.h" #include "core/payload/payloadiface.h" #include "core/selectfunc/ctx/ftctx.h" namespace reindexer { bool Highlight::process(ItemRef &res, PayloadType &pl_type, const SelectFuncStruct &func, std::vector<key_string> &stringsHolder) { if (func.funcArgs.size() < 2) throw Error(errParams, "Invalid highlight params need minimum 2 - have %d", func.funcArgs.size()); if (!func.ctx || func.ctx->type != BaseFunctionCtx::kFtCtx) return false; FtCtx::Ptr ftctx = reindexer::reinterpret_pointer_cast<FtCtx>(func.ctx); AreaHolder::Ptr area = ftctx->Area(res.Id()); if (!area) { return false; } Payload pl(pl_type, res.Value()); VariantArray kr; if (func.tagsPath.empty()) { pl.Get(func.field, kr); } else { pl.GetByJsonPath(func.tagsPath, kr, KeyValueUndefined); } const string *data = p_string(kr[0]).getCxxstr(); auto pva = area->GetAreas(func.fieldNo); if (!pva || pva->empty()) return false; auto &va = *pva; string result_string; result_string.reserve(data->size() + va.size() * (func.funcArgs[0].size() + func.funcArgs[1].size())); result_string = *data; int offset = 0; Word2PosHelper word2pos(*data, ftctx->GetData()->extraWordSymbols_); for (auto area : va) { std::pair<int, int> pos = ftctx->GetData()->isWordPositions_ ? word2pos.convert(area.start_, area.end_) : std::make_pair(area.start_, area.end_); // printf("%d(%d),%d(%d) %s\n", area.start_, pos.first, area.end_, pos.second, data->c_str()); result_string.insert(pos.first + offset, func.funcArgs[0]); offset += func.funcArgs[0].size(); result_string.insert(pos.second + offset, func.funcArgs[1]); offset += func.funcArgs[1].size(); } stringsHolder.emplace_back(make_key_string(result_string)); res.Value().Clone(); if (func.tagsPath.empty()) { pl.Set(func.field, VariantArray{Variant{stringsHolder.back()}}); } else { throw Error(errConflict, "SetByJsonPath is not implemented yet!"); } return true; } } // namespace reindexer
31.090909
131
0.699318
[ "vector" ]
84843f531e98729cfc1bb9201e6ddd52eb49c38d
3,590
cpp
C++
TinyRaster/TinyRaster/TestApplication.cpp
Andrewcjp/tinyraster
5e55325dcc7d0b7c9642727ea72ec64af81b3b49
[ "MIT" ]
null
null
null
TinyRaster/TinyRaster/TestApplication.cpp
Andrewcjp/tinyraster
5e55325dcc7d0b7c9642727ea72ec64af81b3b49
[ "MIT" ]
null
null
null
TinyRaster/TinyRaster/TestApplication.cpp
Andrewcjp/tinyraster
5e55325dcc7d0b7c9642727ea72ec64af81b3b49
[ "MIT" ]
null
null
null
/*--------------------------------------------------------------------- * * Copyright © 2015 Minsi Chen * E-mail: m.chen@derby.ac.uk * * The source is written for the Graphics I and II modules. You are free * to use and extend the functionality. The code provided here is functional * however the author does not guarantee its performance. ---------------------------------------------------------------------*/ #include "TestApplication.h" #include "AppWindow.h" #include "Resource.h" #include <Windowsx.h> TestApplication* TestApplication::s_oglapp = NULL; TestApplication::TestApplication() { m_appwnd = NULL; m_hInst = 0; m_terminate = FALSE; } TestApplication::~TestApplication() { if ( m_appwnd ) delete m_appwnd; } BOOL TestApplication::MyRegisterClass(HINSTANCE hinst) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = this->WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hinst; wcex.hIcon = LoadIcon(hinst, MAKEINTRESOURCE(IDI_OGLWIN32)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = L"AppWindow"; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); if ( !RegisterClassEx ( &wcex ) ) return FALSE; return TRUE; } TestApplication* TestApplication::CreateApplication(HINSTANCE hinst) { if ( ! s_oglapp ) { s_oglapp = new TestApplication(); s_oglapp->m_hInst = hinst; s_oglapp->MyRegisterClass(hinst); //Now create an OGLWindow for this application s_oglapp->CreateApplicationWindow(1280,720);//1280/720 } return s_oglapp; } void TestApplication::DestroyApplication() { if ( s_oglapp ) delete s_oglapp; } TestApplication* TestApplication::GetApplication() { return s_oglapp; } void TestApplication::CreateApplicationWindow( int width, int height ) { if ( !m_appwnd ) { m_appwnd = new AppWindow(); if ( m_appwnd->InitWindow(m_hInst, width, height) ) m_appwnd->SetVisible(TRUE); } } int TestApplication::Run() { MSG msg; while ( !m_terminate ) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { //peek for windows message if ( msg.message == WM_QUIT ) { s_oglapp->GetApplicationWindow()->DestroyOGLWindow(); Kill(); break; } else { TranslateMessage ( &msg ); DispatchMessage ( &msg ); } } //get the OGLWindow to render stuff; m_appwnd->Render(); } return (int) msg.wParam; } void TestApplication::Kill() { m_terminate = TRUE; } LRESULT CALLBACK TestApplication::WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { int wmId, wmEvent; switch ( msg ) { case WM_SIZE: s_oglapp->GetApplicationWindow()->Resize( LOWORD(lparam), HIWORD(lparam) ); break; /*case WM_CLOSE: s_oglapp->GetApplicationWindow()->DestroyOGLWindow(); break;*/ case WM_MOUSEMOVE: //inform the cursor position to OGLWindow s_oglapp->GetApplicationWindow()->MouseMove( GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam) ); break; case WM_LBUTTONUP: s_oglapp->GetApplicationWindow()->MouseLBUp( GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam) ); break; case WM_LBUTTONDOWN: s_oglapp->GetApplicationWindow()->MouseLBDown( GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam) ); break; case WM_KEYUP: s_oglapp->GetApplicationWindow()->KeyUp(wparam); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: s_oglapp->GetApplicationWindow()->Render(); break; default: return DefWindowProc( hwnd, msg, wparam, lparam ); } return 0; }
21.626506
95
0.679944
[ "render" ]
8486be7b6275d4780225732ccb32a71f668ab42b
931
hpp
C++
src/WinGiant/RPC/Service.hpp
kasicass/wingiant
9b45179bff6fada230c610ddb55b7dfd343de9a9
[ "MIT" ]
1
2020-08-20T12:55:41.000Z
2020-08-20T12:55:41.000Z
src/WinGiant/RPC/Service.hpp
kasicass/wingiant
9b45179bff6fada230c610ddb55b7dfd343de9a9
[ "MIT" ]
null
null
null
src/WinGiant/RPC/Service.hpp
kasicass/wingiant
9b45179bff6fada230c610ddb55b7dfd343de9a9
[ "MIT" ]
1
2019-12-18T10:14:36.000Z
2019-12-18T10:14:36.000Z
// struct MyData; // MyData d; // // void addService(msgpack::object obj); // // RPC::Service svc("MyService"); // svc.registerCall("add", addService); // if (svc.start()) // { // while (1) // { // if (!svc.runOnce()) // ::Sleep(100); // } // } #pragma once #pragma warning(disable: 4244) // conversion from 'double' to 'float', possible loss of data #include <msgpack.hpp> #include <string> #include <map> #include "../IPC/Sub.hpp" namespace WinGiant { namespace RPC { class Service { public: typedef void (*SERVICE_CALLBACK)(void*,msgpack::object); public: Service(const std::wstring& serviceAddress); ~Service(); void registerCall(const std::string& proto, SERVICE_CALLBACK func, void *data); bool start(); bool runOnce(); // true if handle one call, false if not private: std::wstring serviceAddress_; std::map<std::string, std::pair<SERVICE_CALLBACK, void*>> protoMap_; IPC::Sub sub_; }; }}
19.395833
93
0.66058
[ "object" ]
84870939ae0e112f24b82ef3bd3d7cf0587df010
1,250
cpp
C++
ABC/ABC245/D/abc245-d.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC245/D/abc245-d.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/ABC245/D/abc245-d.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/** * @file abc245-d.cpp * @brief ABC245 Problem D - Polynomial division * @author Keitaro Naruse * @date 2022-03-26, 2022-03-27 * @copyright MIT License * @details https://atcoder.jp/contests/abc245/tasks/abc245_d */ // # Solution #include <iostream> #include <vector> template< class T > std::ostream& operator<<( std::ostream& os, const std::vector< T >& v ) { for( auto k : v ) { os << k << " "; } return( os ); } int main() { // Read N. M = [ 1, 10^2 ] int N, M; std::cin >> N >> M; // Read Ai = [ -10^2, 10^2 ] std::vector< int > A( N + 1, 0 ); for( int i = 0; i <= N; i ++ ) { std::cin >> A.at( i ); } // Read Ci = [ -10^6, 10^6 ] std::vector< int > C( N + M + 1, 0 ); for( int j = 0; j <= N + M; j ++ ) { std::cin >> C.at( j ); } // Main std::vector< int > B( M + 1, 0 ); for( int k = M; k >= 0; k -- ) { int AB_sum = 0; for( int i = 1; i <= M - k; i ++ ) { if( 0 <= N - i && k + i <= M ) { AB_sum += A.at( N - i ) * B.at( k + i ); } } B.at( k ) = ( C.at( N + k ) - AB_sum ) / A.at( N ); } std::cout << B << std::endl; // Finalize return( 0 ); }
21.929825
71
0.4232
[ "vector" ]
848980f33403eb4c8b63ae2d9b0d6bf5d3c48109
1,152
cpp
C++
unwrap.cpp
PatxiofromAlphensign/SparseTensor
61d8dbc0a48a3d431a0ad43649729ddf8e5bb9ad
[ "BSD-2-Clause" ]
null
null
null
unwrap.cpp
PatxiofromAlphensign/SparseTensor
61d8dbc0a48a3d431a0ad43649729ddf8e5bb9ad
[ "BSD-2-Clause" ]
null
null
null
unwrap.cpp
PatxiofromAlphensign/SparseTensor
61d8dbc0a48a3d431a0ad43649729ddf8e5bb9ad
[ "BSD-2-Clause" ]
null
null
null
#include <util.h> #include <vector> #include <iostream> namespace M { Value a; SparseTensor::SparseMatrixEntry sparse(2,5,a ); template<typename T> concept floating = std::floating_point<T>; template<floating T> void f(std::vector<T> vec) { } struct stuff { std::ostream& os; stuff(std::ostream& os ) : os(os) {} template<typename T> void operator<(T& obj) {os << obj;} }; template<typename T> concept isfloating = std::is_floating_point_v<T>; struct main { SparseTensor::SparseMatrixEntry sp; main(std::ostream& os, int ab, int b, Value val) : sp(ab,b,val) {} template <isfloating T> void operator<(T& obj) {std::cout << obj;} }; template< class T > struct is_floating_point : std::integral_constant< bool, std::is_same<float, typename std::remove_cv<T>::type>::value > {}; template<typename T> concept test = true; }; template <M::test T> void test(T &a) {} int main() { std::vector<int> vec = {1,2}; int t = 69; M::stuff(std::cout) < t; test(t); };
21.333333
74
0.569444
[ "vector" ]
84929e28a2647573e656738b48ad8832e86ee536
4,884
cc
C++
modules/perception/onboard/subnode.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
22
2018-10-10T14:46:32.000Z
2022-02-28T12:43:43.000Z
modules/perception/onboard/subnode.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
5
2020-06-13T00:36:33.000Z
2022-02-10T17:50:43.000Z
modules/perception/onboard/subnode.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
12
2018-12-24T02:17:19.000Z
2021-12-06T01:54:09.000Z
/****************************************************************************** * Copyright 2018 The Apollo 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 "modules/perception/onboard/subnode.h" #include <sstream> #include "modules/common/log.h" namespace apollo { namespace perception { using apollo::common::ErrorCode; using apollo::common::Status; using std::vector; using std::string; using std::ostringstream; bool Subnode::Init(const DAGConfig::Subnode &subnode_config, const vector<EventID> &sub_events, const vector<EventID> &pub_events, EventManager *event_manager, SharedDataManager *shared_data_manager) { name_ = subnode_config.name(); id_ = subnode_config.id(); reserve_ = subnode_config.reserve(); if (subnode_config.has_type()) { type_ = subnode_config.type(); } CHECK(event_manager != nullptr) << "event_manager == nullptr"; event_manager_ = event_manager; CHECK(shared_data_manager != nullptr) << "shared_data_manager == nullptr"; shared_data_manager_ = shared_data_manager; // fill sub and pub meta events. if (!event_manager_->GetEventMeta(sub_events, &sub_meta_events_)) { AERROR << "failed to get Sub EventMeta. node: <" << name_ << ", " << id_ << ">"; return false; } if (!event_manager_->GetEventMeta(pub_events, &pub_meta_events_)) { AERROR << "failed to get Pub EventMeta. node: <" << id_ << ", " << name_ << ">"; return false; } if (!InitInternal()) { AERROR << "failed to Init inner members."; return false; } inited_ = true; return true; } void Subnode::Run() { if (!inited_) { AERROR << "Subnode not inited, run failed. node: <" << id_ << ", " << name_ << ">"; return; } if (type_ == DAGConfig::SUBNODE_IN) { AINFO << "Subnode == SUBNODE_IN, EXIT THREAD. subnode:" << DebugString(); return; } while (!stop_) { Status status = ProcEvents(); ++total_count_; if (status.code() == ErrorCode::PERCEPTION_ERROR) { ++failed_count_; AWARN << "Subnode: " << name_ << " proc event failed. " << " total_count: " << total_count_ << " failed_count: " << failed_count_; continue; } // FATAL error, so exit thread. if (status.code() == ErrorCode::PERCEPTION_FATAL) { AERROR << "Subnode: " << name_ << " proc event FATAL error, EXIT. " << " total_count: " << total_count_ << " failed_count: " << failed_count_; break; } } } string Subnode::DebugString() const { ostringstream oss; oss << "{id: " << id_ << ", name: " << name_ << ", reserve: " << reserve_ << ", type:" << DAGConfig::SubnodeType_Name(type_); oss << ", SubEvents: ["; for (size_t idx = 0; idx < sub_meta_events_.size(); ++idx) { oss << "<" << sub_meta_events_[idx].to_string() << ">"; } oss << "], PubEvents: ["; for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) { oss << "<" << pub_meta_events_[idx].to_string() << ">"; } oss << "]}"; return oss.str(); } Status CommonSubnode::ProcEvents() { CHECK(sub_meta_events_.size() == 1u) << "CommonSubnode sub_meta_events == 1"; CHECK(pub_meta_events_.size() == 1u) << "CommonSubnode pub_meta_events == 1"; Event sub_event; if (!event_manager_->Subscribe(sub_meta_events_[0].event_id, &sub_event)) { AERROR << "failed to subscribe. meta_event: <" << sub_meta_events_[0].to_string() << ">"; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to subscribe event."); } Event pub_event = sub_event; pub_event.event_id = pub_meta_events_[0].event_id; // user defined logic api. if (!HandleEvent(sub_event, &pub_event)) { AWARN << "failed to call handle_event_. sub_event: <" << sub_event.to_string() << "> pub_event: <" << pub_event.to_string(); return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call handle_event_."); } if (!event_manager_->Publish(pub_event)) { AERROR << "failed to publish pub_event: <" << pub_event.to_string() << ">"; return Status(ErrorCode::PERCEPTION_ERROR, "Failed to publish pub_event."); } return Status::OK(); } } // namespace perception } // namespace apollo
31.714286
80
0.613432
[ "vector" ]
8498683af60f666c17902c17685d8616630bf083
6,668
cpp
C++
cadmium/example/main-count-fives.cpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
cadmium/example/main-count-fives.cpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
cadmium/example/main-count-fives.cpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2017, Damian Vicino * Carleton University, Universite de Nice-Sophia Antipolis * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ //counting until 5 and output every 5 seconds. #include <iostream> #include <chrono> #include <algorithm> #include <cadmium/logger/tuple_to_ostream.hpp> #include <cadmium/modeling/coupled_model.hpp> #include <cadmium/modeling/ports.hpp> #include <cadmium/concept/coupled_model_assert.hpp> #include <cadmium/engine/pdevs_runner.hpp> #include <cadmium/basic_model/accumulator.hpp> #include <cadmium/basic_model/int_generator_one_sec.hpp> #include <cadmium/basic_model/reset_generator_five_sec.hpp> #include <cadmium/logger/common_loggers.hpp> using namespace std; using hclock=chrono::high_resolution_clock; /** * This example uses 2 generatos ticking one every second and one every 5 seconds * they are grouped into a coupled model, in another coupled model we have an infinite counter. * The one sec generator ticks on the counter add, and the 5 seconds one in the reset of the counter. * Every five sec an output of the count (5) is expected. * This example shows simple coupled models collaborating. * * The experiment runtime is measured using the chrono library. */ template<typename TIME> using test_accumulator=cadmium::basic_models::accumulator<int, TIME>; using test_accumulator_defs=cadmium::basic_models::accumulator_defs<int>; using reset_tick=cadmium::basic_models::accumulator_defs<int>::reset_tick; using empty_iports = std::tuple<>; using empty_eic=std::tuple<>; using empty_ic=std::tuple<>; //2 generators doing output in 2 ports using generators_oports=std::tuple<cadmium::basic_models::int_generator_one_sec_defs::out, cadmium::basic_models::reset_generator_five_sec_defs::out>; using generators_submodels=cadmium::modeling::models_tuple<cadmium::basic_models::reset_generator_five_sec, cadmium::basic_models::int_generator_one_sec>; using generators_eoc=std::tuple< cadmium::modeling::EOC<cadmium::basic_models::reset_generator_five_sec, cadmium::basic_models::reset_generator_five_sec_defs::out, cadmium::basic_models::reset_generator_five_sec_defs::out>, cadmium::modeling::EOC<cadmium::basic_models::int_generator_one_sec, cadmium::basic_models::int_generator_one_sec_defs::out, cadmium::basic_models::int_generator_one_sec_defs::out> >; template<typename TIME> using coupled_generators_model=cadmium::modeling::coupled_model<TIME, empty_iports, generators_oports, generators_submodels, empty_eic, generators_eoc, empty_ic>; //1 accumulator wrapped in a coupled model using accumulator_eic=std::tuple< cadmium::modeling::EIC<test_accumulator_defs::add, test_accumulator, test_accumulator_defs::add>, cadmium::modeling::EIC<test_accumulator_defs::reset, test_accumulator, test_accumulator_defs::reset> >; using accumulator_eoc=std::tuple< cadmium::modeling::EOC<test_accumulator, test_accumulator_defs::sum, test_accumulator_defs::sum> >; using accumulator_submodels=cadmium::modeling::models_tuple<test_accumulator>; template<typename TIME> using coupled_accumulator_model=cadmium::modeling::coupled_model<TIME, typename test_accumulator<TIME>::input_ports, typename test_accumulator<TIME>::output_ports, accumulator_submodels, accumulator_eic, accumulator_eoc, empty_ic>; //top model interconnecting the 2 coupled models using top_outport = test_accumulator_defs::sum; using top_oports = std::tuple<top_outport>; using top_submodels=cadmium::modeling::models_tuple<coupled_generators_model, coupled_accumulator_model>; using top_eoc=std::tuple< cadmium::modeling::EOC<coupled_accumulator_model, test_accumulator_defs::sum, top_outport> >; using top_ic=std::tuple< cadmium::modeling::IC<coupled_generators_model, cadmium::basic_models::int_generator_one_sec_defs::out, coupled_accumulator_model, test_accumulator_defs::add>, cadmium::modeling::IC<coupled_generators_model, cadmium::basic_models::reset_generator_five_sec_defs::out , coupled_accumulator_model, test_accumulator_defs::reset> >; template<typename TIME> using top_model=cadmium::modeling::coupled_model<TIME, empty_iports, top_oports, top_submodels, empty_eic, top_eoc, top_ic>; using messages_logger=cadmium::logger::logger<cadmium::logger::logger_message_routing, cadmium::logger::verbatim_formatter, cadmium::logger::cout_sink_provider>; //LOG ALL TO COUT using namespace cadmium::logger; using info=logger<logger_info, verbatim_formatter, cout_sink_provider>; using debug=logger<logger_debug, verbatim_formatter, cout_sink_provider>; using state=logger<logger_state, verbatim_formatter, cout_sink_provider>; using log_messages=logger<logger_messages, verbatim_formatter, cout_sink_provider>; using routing=logger<logger_message_routing, verbatim_formatter, cout_sink_provider>; using global_time=logger<logger_global_time, verbatim_formatter, cout_sink_provider>; using local_time=logger<logger_local_time, verbatim_formatter, cout_sink_provider>; using log_all=multilogger<info, debug, state, log_messages, routing, global_time, local_time>; int main(){ auto start = hclock::now(); //to measure simulation execution time cadmium::engine::runner<float, top_model, log_all> r{0.0}; r.runUntil(100.0); auto elapsed = std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1>>> (hclock::now() - start).count(); cout << "Simulation took:" << elapsed << "sec" << endl; return 0; }
49.761194
231
0.804889
[ "model" ]
849e72712244fb777ea82af9a0336576864f0f7f
21,097
cpp
C++
Source/moja.flint/src/writesystemconfig.cpp
moja-global/flint
2c65c5808d908247ce8ee4d9f87f11c7dd57794e
[ "BSL-1.0" ]
null
null
null
Source/moja.flint/src/writesystemconfig.cpp
moja-global/flint
2c65c5808d908247ce8ee4d9f87f11c7dd57794e
[ "BSL-1.0" ]
1
2020-07-12T11:30:00.000Z
2020-07-18T14:50:16.000Z
Source/moja.flint/src/writesystemconfig.cpp
moja-global/flint
2c65c5808d908247ce8ee4d9f87f11c7dd57794e
[ "BSL-1.0" ]
null
null
null
#include "moja/flint/ilandunitdatawrapper.h" #include "moja/flint/ipool.h" #include "moja/flint/itiming.h" #include "moja/flint/spatiallocationinfo.h" #include "moja/flint/externalvariable.h" #include "moja/flint/flintdatavariable.h" #include "moja/flint/variable.h" #include "moja/flint/writesystemconfig.h" #include <moja/flint/configuration/configuration.h> #include <moja/flint/configuration/iterationbase.h> #include <moja/flint/configuration/landscape.h> #include <moja/flint/configuration/library.h> #include <moja/flint/configuration/localdomain.h> #include <moja/flint/configuration/module.h> #include <moja/flint/configuration/operationmanager.h> #include <moja/dynamic.h> #include <moja/logging.h> #include <moja/notificationcenter.h> #include <moja/signals.h> #include <Poco/File.h> #include <Poco/Path.h> #include <boost/format.hpp> #include <fstream> #include <ostream> namespace moja { namespace flint { // -------------------------------------------------------------------------------------------- void WriteSystemConfig::configure(const DynamicObject& config) { _name = config["name"].convert<std::string>(); _outputPath = config.contains("output_path") ? config["output_path"].convert<std::string>() : ""; _writeFrequency = config.contains("write_frequency") ? config["write_frequency"].convert<UInt32>() : 0; _writeOutstepFrequency = config.contains("write_outstep_frequency") ? config["write_outstep_frequency"].convert<UInt32>() : 0; // set all notifications to false for (auto& val : _onNotificationArray) val = false; if (config.contains("on_notification")) { // is it an array or single entry auto dynamic = config["on_notification"]; if (dynamic.isVector()) { const auto& arr = dynamic.extract<const DynamicVector>(); for (auto& val : arr) { auto notStr = val.convert<std::string>(); _onNotificationArray[convertNotificationStringToIndex(notStr)] = true; } } else { _onNotificationArray[convertNotificationStringToIndex(config["on_notification"].convert<std::string>())] = true; } } else { _onNotificationArray[static_cast<int>(OnNotificationType::TimingInit)] = true; } } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::subscribe(NotificationCenter& notificationCenter) { notificationCenter.subscribe(signals::SystemInit, &WriteSystemConfig::onSystemInit, *this); notificationCenter.subscribe(signals::LocalDomainInit, &WriteSystemConfig::onLocalDomainInit, *this); notificationCenter.subscribe(signals::PreTimingSequence, &WriteSystemConfig::onPreTimingSequence, *this); notificationCenter.subscribe(signals::TimingInit, &WriteSystemConfig::onTimingInit, *this); notificationCenter.subscribe(signals::TimingShutdown, &WriteSystemConfig::onTimingShutdown, *this); notificationCenter.subscribe(signals::OutputStep, &WriteSystemConfig::onOutputStep, *this); notificationCenter.subscribe(signals::Error, &WriteSystemConfig::onError, *this); } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onSystemInit() { Poco::File workingFolder(_outputPath); if (!workingFolder.exists()) { try { workingFolder.createDirectories(); } catch (Poco::FileExistsException&) { /* Poco has a bug here, exception shouldn't be thrown, has been fixed in 1.7.8 */ } } if (workingFolder.exists() && !workingFolder.isDirectory()) { MOJA_LOG_ERROR << "Error creating spatial tiled point configurations output folder: " << _outputPath; } auto outputFolderPath = (boost::format("%1%%2%%3%") % workingFolder.path() % Poco::Path::separator() % _name).str(); Poco::File outputFolder(outputFolderPath); if (!outputFolder.exists()) { try { outputFolder.createDirectories(); } catch (Poco::FileExistsException&) { /* Poco has a bug here, exception shouldn't be thrown, has been fixed in 1.7.8 */ } } } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onLocalDomainInit() { _writeCellProcessed = 0; _spatialLocationInfo = nullptr; if (_landUnitData->hasVariable("spatialLocationInfo")) { _spatialLocationInfo = std::static_pointer_cast<flint::SpatialLocationInfo>( _landUnitData->getVariable("spatialLocationInfo")->value().extract<std::shared_ptr<flint::IFlintData>>()); } } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onPreTimingSequence() { _writeThisCell = (_writeFrequency == 0) || ((_writeCellProcessed % _writeFrequency) == 0); _writeCellProcessed++; if (_writeThisCell && _onNotificationArray[static_cast<int>(OnNotificationType::PreTimingSequence)]) WriteConfig("PreTimingSequence"); } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onTimingInit() { if (_writeThisCell && _onNotificationArray[static_cast<int>(OnNotificationType::TimingInit)]) WriteConfig("TimingInit"); } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onTimingShutdown() { if (_writeThisCell && _onNotificationArray[static_cast<int>(OnNotificationType::TimingShutdown)]) WriteConfig("TimingShutdown"); } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onOutputStep() { const auto timing = _landUnitData->timing(); int timestep = timing->step(); int timesubstep = timing->subStep(); if ((_writeOutstepFrequency != 0) && ((timestep - 1) % _writeOutstepFrequency) != 0) return; if (_writeThisCell && _onNotificationArray[static_cast<int>(OnNotificationType::OutputStep)]) WriteConfig("OutputStep"); } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::onError(std::string msg) { if (_writeThisCell && _onNotificationArray[static_cast<int>(OnNotificationType::Error)]) WriteConfig("Error"); } // -------------------------------------------------------------------------------------------- void outputDynamicToStream(std::ofstream& fout, const DynamicVar& object, int level); void outputDynamicObjectToStream(std::ofstream& fout, const DynamicObject& object, int level); void outputVectorToStream(std::ofstream& fout, const std::vector<DynamicObject>& object, int level); void outputVectorToStream(std::ofstream& fout, const DynamicVector& object, int level); #define OUTPUT_LEVEL_WS(level) \ for (int i = 0; i < level; i++) fout << "\t"; // -------------------------------------------------------------------------------------------- void outputDynamicObjectToStream(std::ofstream& fout, const DynamicObject& object, int level) { fout << "{" << std::endl; auto first = true; for (auto& item : object) { if (!first) fout << "," << std::endl; OUTPUT_LEVEL_WS(level + 1); fout << "\"" << item.first << "\": "; outputDynamicToStream(fout, item.second, level + 1); first = false; } fout << std::endl; OUTPUT_LEVEL_WS(level); fout << "}"; } // -------------------------------------------------------------------------------------------- std::string escape_json(const std::string& s) { std::ostringstream o; for (auto c = s.cbegin(); c != s.cend(); ++c) { if (*c == '"' || *c == '\\' || ('\x00' <= *c && *c <= '\x1f')) // o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(*c); o << "\\"; o << *c; } return o.str(); } // -------------------------------------------------------------------------------------------- template <typename T> inline void outputBoostVectorToStream(std::ofstream& fout, const std::vector<boost::optional<T>>& object, int level) { fout << "[" << std::endl; auto first = true; for (auto item : object) { if (!first) { fout << "," << std::endl; } OUTPUT_LEVEL_WS(level + 1); if (item) { T val = item.get(); outputDynamicToStream(fout, val, level + 1); } else outputDynamicToStream(fout, DynamicVar(0.00), level + 1); first = false; } fout << std::endl; OUTPUT_LEVEL_WS(level); fout << "]"; } // -------------------------------------------------------------------------------------------- void outputDynamicToStream(std::ofstream& fout, const DynamicVar& object, int level) { if (object.isStruct()) { auto& obj = object.extract<const DynamicObject>(); outputDynamicObjectToStream(fout, obj, level); } else if (object.isVector()) { if (object.type() == typeid(std::vector<boost::optional<int>>)) { auto& vec = object.extract<const std::vector<boost::optional<int>>>(); outputBoostVectorToStream(fout, vec, level); } else if (object.type() == typeid(std::vector<boost::optional<unsigned char>>)) { auto& vec = object.extract<const std::vector<boost::optional<unsigned char>>>(); outputBoostVectorToStream(fout, vec, level); } else if (object.type() == typeid(std::vector<boost::optional<double>>)) { auto& vec = object.extract<const std::vector<boost::optional<double>>>(); outputBoostVectorToStream(fout, vec, level); } else if (object.type() == typeid(std::vector<DynamicObject>)) { auto& vec = object.extract<const std::vector<DynamicObject>>(); outputVectorToStream(fout, vec, level); } else { auto& vec = object.extract<const DynamicVector>(); outputVectorToStream(fout, vec, level); } } else if (object.isBoolean()) { bool val = object; fout << (val ? "true" : "false"); } else if (object.isEmpty()) { fout << "null"; } else if (object.isString()) { fout << "\"" << escape_json(object.extract<const std::string>()) << "\""; } else if (object.isInteger()) { int val = object; fout << val; } else if (object.isNumeric()) { auto val = object.extract<double>(); fout << val; } else if (object.isSigned()) { fout << "\"** Signed\""; } else { if (object.type() == typeid(DateTime)) { DateTime dt = object.extract<DateTime>(); std::string simpleDateStr = (boost::format("{ \"$date\": \"%1%/%2%/%3%\" }") % dt.year() % dt.month() % dt.day()).str(); fout << simpleDateStr; // fout << "\"" << escape_json(simpleDateStr) << "\""; } else if (object.type() == typeid(Int16)) { fout << object.extract<const Int16>(); } else if (object.type() == typeid(std::shared_ptr<IFlintData>)) { auto ptr = std::static_pointer_cast<IFlintData>(object.extract<std::shared_ptr<IFlintData>>()); auto flintDataVar = ptr->exportObject(); outputDynamicToStream(fout, flintDataVar, level); } else fout << "\"** UNKNOWN VALUE TYPE\""; } } // -------------------------------------------------------------------------------------------- void outputVectorToStream(std::ofstream& fout, const std::vector<DynamicObject>& object, int level) { fout << "[" << std::endl; auto first = true; for (auto& item : object) { if (!first) { fout << "," << std::endl; } OUTPUT_LEVEL_WS(level + 1); outputDynamicToStream(fout, item, level + 1); first = false; } fout << std::endl; OUTPUT_LEVEL_WS(level); fout << "]"; } // -------------------------------------------------------------------------------------------- void outputVectorToStream(std::ofstream& fout, const DynamicVector& object, int level) { fout << "[" << std::endl; auto first = true; for (auto& item : object) { if (!first) { fout << "," << std::endl; } OUTPUT_LEVEL_WS(level + 1); outputDynamicToStream(fout, item, level + 1); first = false; } fout << std::endl; OUTPUT_LEVEL_WS(level); fout << "]"; } // -------------------------------------------------------------------------------------------- void WriteSystemConfig::WriteConfig(std::string notificationStr) const { const auto timing = _landUnitData->timing(); auto timestep = timing->step(); auto timesubstep = timing->subStep(); Poco::File workingFolder(_outputPath); auto configFilename = (boost::format("%1%%2%%3%%4%%5%_%6%_%7%_%8%_%9%_%10%.json") % workingFolder.path() % Poco::Path::separator() % _name % Poco::Path::separator() % boost::io::group(std::setfill('0'), std::setw(5), _spatialLocationInfo ? _spatialLocationInfo->_tileIdx : 0) % boost::io::group(std::setfill('0'), std::setw(3), _spatialLocationInfo ? _spatialLocationInfo->_blockIdx : 0) % boost::io::group(std::setfill('0'), std::setw(6), _spatialLocationInfo ? _spatialLocationInfo->_cellIdx : 0) % notificationStr % timestep % timesubstep) .str(); Poco::File configFile(configFilename); if (configFile.exists()) configFile.remove(false); // delete existing config file // configFile.createFile() FileHandle pFile(configFilename, "wb"); std::ofstream fout; fout.open(configFilename); // , ios::out | ios::trunc); if (fout.fail()) { return; } auto config = _landUnitData->config(); if (config == nullptr) return; // Build libraries DynamicObject libraries; for (auto& library : config->libraries()) { if (library->hasPath()) { libraries[library->path()] = DynamicObject({{"library", library->library()}, {"order", library->name()}}); } else { libraries[library->name()] = configuration::libraryTypeToStr(library->type()); } } // Build localdomain DynamicObject localdomain; auto localDomainConfig = config->localDomain(); localdomain["type"] = configuration::LocalDomain::localDomainTypeToStr(localDomainConfig->type()); localdomain["start_date_init"] = (boost::format("%1%/%2%/%3%") % config->startDate().year() % config->startDate().month() % config->startDate().day()) .str(); localdomain["start_date"] = (boost::format("%1%/%2%/%3%") % timing->curStartDate().year() % timing->curStartDate().month() % timing->curStartDate().day()) .str(); localdomain["end_date"] = (boost::format("%1%/%2%/%3%") % config->endDate().year() % config->endDate().month() % config->endDate().day()) .str(); localdomain["sequencer_library"] = localDomainConfig->sequencerLibrary(); localdomain["sequencer"] = localDomainConfig->sequencer(); localdomain["simulateLandUnit"] = localDomainConfig->simulateLandUnit(); localdomain["landUnitBuildSuccess"] = localDomainConfig->landUnitBuildSuccess(); localdomain["operationManager"] = localDomainConfig->operationManagerObject()->settings(); // TODO: fillin other types of LocalDomain and iteration switch (localDomainConfig->type()) { case configuration::LocalDomainType::SpatialTiled: { switch (localDomainConfig->landscapeObject()->iterationType()) { case configuration::LocalDomainIterationType::NotAnIteration: break; case configuration::LocalDomainIterationType::ASpatialIndex: break; case configuration::LocalDomainIterationType::ASpatialMongoIndex: break; case configuration::LocalDomainIterationType::AreaOfInterest: break; case configuration::LocalDomainIterationType::LandscapeTiles: break; case configuration::LocalDomainIterationType::TileIndex: case configuration::LocalDomainIterationType::BlockIndex: case configuration::LocalDomainIterationType::CellIndex: { localdomain["landscape"] = DynamicObject( {//{ "iteration_type", //configuration::convertLocalDomainIterationTypeToStr(localDomainConfig->landscapeObject()->iterationType()) //}, {"iteration_type", "CellIndex"}, {"num_threads", localDomainConfig->numThreads()}, {"provider", localDomainConfig->landscapeObject()->providerName()}, {"cells", DynamicVector({DynamicObject({{"tile_index", _spatialLocationInfo->_tileIdx}, {"block_index", _spatialLocationInfo->_blockIdx}, {"cell_index", _spatialLocationInfo->_cellIdx}})})}}); } break; default: break; } } break; case configuration::LocalDomainType::SpatiallyReferencedSQL: { } break; case configuration::LocalDomainType::SpatiallyReferencedNoSQL: { } break; case configuration::LocalDomainType::ThreadedSpatiallyReferencedNoSQL: { } break; case configuration::LocalDomainType::Point: { } break; default: { } break; } // Build pools DynamicObject pools; for (auto& pool : _landUnitData->poolCollection()) { pools[pool->name()] = pool->value(); } // Build pools with Init values DynamicObject poolsInit; for (auto& pool : _landUnitData->poolCollection()) { poolsInit[pool->name()] = pool->initValue(); } // Build variables DynamicObject variables; for (auto& variable : _landUnitData->variables()) { auto& variableName = variable->info().name; if (variable->isFlintData()) { auto ptr = std::static_pointer_cast<FlintDataVariable>(variable); auto flintDataVar = DynamicObject({{"flintdata", DynamicObject({{"library", ptr->libraryName()}, {"type", ptr->variableName()}, {"settings", ptr->flintdata()->exportObject()}})}}); variables[variableName] = flintDataVar; } else if (variable->isExternal()) { auto ptr = std::static_pointer_cast<ExternalVariable>(variable); auto& val = ptr->value(); if (val.type() == typeid(std::shared_ptr<IFlintData>)) { auto flindata = val.extract<std::shared_ptr<IFlintData>>(); auto flintDataVar = DynamicObject({{"flintdata", DynamicObject({{"library", flindata->libraryName}, {"type", flindata->typeName}, {"settings", flindata->exportObject()}})}}); variables[variableName] = flintDataVar; } else variables[variableName] = ptr->value(); } else { auto ptr = std::static_pointer_cast<Variable>(variable); variables[variableName] = ptr->value(); } } // Build modules DynamicObject modules; for (auto& module : config->modules()) { modules[module->name()] = DynamicObject({{"library", module->libraryName()}, {"order", module->order()}, {"is_proxy", module->isProxy()}, {"settings", module->settings()}}); } // put bits together in config Dynamic auto configOutput = DynamicObject({{"LocalDomain", localdomain}, {"Libraries", libraries}, //{ "Spinup", DynamicObject() }, //{ "SpinupModules", DynamicObject() }, //{ "SpinupVariables", DynamicObject() }, {"Pools", pools}, {"Pools_Init", poolsInit}, {"Variables", variables}, {"Modules", modules}}); int level = 0; outputDynamicObjectToStream(fout, configOutput, level); fout << std::flush; fout.close(); } #undef OUTPUT_LEVEL_WS #undef RETRY_ATTEMPTS #undef RETRY_SLEEP } // namespace flint } // namespace moja
43.231557
129
0.550979
[ "object", "vector" ]
84a0040ba1336df15325870c58c33ea6a906e66d
3,483
cpp
C++
src/ros/hardware_interface.cpp
uob-erl/ur_modern_driver
9634a082cdec79af7dc13f6062d048cf4083cc65
[ "Apache-2.0" ]
7
2022-02-17T23:29:45.000Z
2022-03-12T09:23:54.000Z
src/ros/hardware_interface.cpp
uob-erl/ur_modern_driver
9634a082cdec79af7dc13f6062d048cf4083cc65
[ "Apache-2.0" ]
null
null
null
src/ros/hardware_interface.cpp
uob-erl/ur_modern_driver
9634a082cdec79af7dc13f6062d048cf4083cc65
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017, 2018 Simon Rasmussen (refactor) * * Copyright 2015, 2016 Thomas Timm Andersen (original version) * * 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 "ur_modern_driver/ros/hardware_interface.h" #include "ur_modern_driver/log.h" const std::string JointInterface::INTERFACE_NAME = "hardware_interface::JointStateInterface"; JointInterface::JointInterface(std::vector<std::string> &joint_names) { for (size_t i = 0; i < 6; i++) { registerHandle(hardware_interface::JointStateHandle(joint_names[i], &positions_[i], &velocities_[i], &efforts_[i])); } } void JointInterface::update(RTShared &packet) { positions_ = packet.q_actual; velocities_ = packet.qd_actual; efforts_ = packet.i_actual; } const std::string WrenchInterface::INTERFACE_NAME = "hardware_interface::ForceTorqueSensorInterface"; WrenchInterface::WrenchInterface(std::string wrench_frame) { // the frame_id for the Wrench is set to what is configured as the "base frame". // Refer to ros-industrial/ur_modern_driver#318 for the rationale. registerHandle(hardware_interface::ForceTorqueSensorHandle("wrench", wrench_frame, tcp_.begin(), tcp_.begin() + 3)); } void WrenchInterface::update(RTShared &packet) { tcp_ = packet.tcp_force; } const std::string VelocityInterface::INTERFACE_NAME = "hardware_interface::VelocityJointInterface"; VelocityInterface::VelocityInterface(URCommander &commander, hardware_interface::JointStateInterface &js_interface, std::vector<std::string> &joint_names, double max_vel_change) : commander_(commander), prev_velocity_cmd_({ 0, 0, 0, 0, 0, 0 }), max_vel_change_(max_vel_change) { for (size_t i = 0; i < 6; i++) { registerHandle(JointHandle(js_interface.getHandle(joint_names[i]), &velocity_cmd_[i])); } } bool VelocityInterface::write() { for (size_t i = 0; i < 6; i++) { // clamp value to ±max_vel_change double prev = prev_velocity_cmd_[i]; double lo = prev - max_vel_change_; double hi = prev + max_vel_change_; prev_velocity_cmd_[i] = std::max(lo, std::min(velocity_cmd_[i], hi)); } return commander_.speedj(prev_velocity_cmd_, max_vel_change_); } void VelocityInterface::reset() { for (auto &val : prev_velocity_cmd_) { val = 0; } } const std::string PositionInterface::INTERFACE_NAME = "hardware_interface::PositionJointInterface"; PositionInterface::PositionInterface(TrajectoryFollower &follower, hardware_interface::JointStateInterface &js_interface, std::vector<std::string> &joint_names) : follower_(follower) { for (size_t i = 0; i < 6; i++) { registerHandle(JointHandle(js_interface.getHandle(joint_names[i]), &position_cmd_[i])); } } bool PositionInterface::write() { return follower_.execute(position_cmd_); } void PositionInterface::start() { follower_.start(); } void PositionInterface::stop() { follower_.stop(); }
31.954128
120
0.718346
[ "vector" ]
84a28f390665a823139333663e7d342036b616e7
6,114
cpp
C++
src/tests/end2end/ReduceMeanTests.cpp
lisa0314/webnn-native-1
941b9c87615a9504715a3425e194aad0c2495d06
[ "Apache-2.0" ]
null
null
null
src/tests/end2end/ReduceMeanTests.cpp
lisa0314/webnn-native-1
941b9c87615a9504715a3425e194aad0c2495d06
[ "Apache-2.0" ]
null
null
null
src/tests/end2end/ReduceMeanTests.cpp
lisa0314/webnn-native-1
941b9c87615a9504715a3425e194aad0c2495d06
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The WebNN-native Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/tests/WebnnTest.h" class ReduceMeanTests : public WebnnTest { protected: void CheckReduceMean(const std::vector<int32_t>& inputShape, const std::vector<float>& inputData, const std::vector<int32_t>& expectedShape, const std::vector<float>& expectedValue, const std::vector<int32_t>& axes = {}, bool keepDimensions = false) { const ml::GraphBuilder builder = ml::CreateGraphBuilder(GetContext()); const ml::Operand a = utils::BuildInput(builder, "a", inputShape); ml::ReduceMeanOptions options; if (!axes.empty()) { options.axes = axes.data(); options.axesCount = axes.size(); } if (keepDimensions) { options.keepDimensions = keepDimensions; } const ml::Operand b = builder.ReduceMean(a, &options); const ml::Graph graph = utils::AwaitBuild(builder, {{"b", b}}); ASSERT_TRUE(graph); const ml::Input input = {inputData.data(), inputData.size() * sizeof(float)}; const ml::Result result = utils::AwaitCompute(graph, {{"a", input}}).Get("b"); EXPECT_TRUE(utils::CheckShape(result, expectedShape)); EXPECT_TRUE(utils::CheckValue(result, expectedValue)); } }; TEST_F(ReduceMeanTests, ReduceMeanDefault) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {}; const std::vector<float> expectedValue = {18.25}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {}); } TEST_F(ReduceMeanTests, ReduceMeanDefaultAxesKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {1, 1, 1}; const std::vector<float> expectedValue = {18.25}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {}, true); } TEST_F(ReduceMeanTests, ReduceMeanAxes0NotKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {2, 2}; const std::vector<float> expectedValue = {30., 1., 40., 2.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {0}); } TEST_F(ReduceMeanTests, ReduceMeanAxes1NotKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 2}; const std::vector<float> expectedValue = {12.5, 1.5, 35., 1.5, 57.5, 1.5}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {1}); } TEST_F(ReduceMeanTests, ReduceMeanAxes2NotKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 2}; const std::vector<float> expectedValue = {3., 11., 15.5, 21., 28., 31.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {2}); } TEST_F(ReduceMeanTests, ReduceMeanNegativeAxesNotKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 2}; const std::vector<float> expectedValue = {3., 11., 15.5, 21., 28., 31.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {-1}); } TEST_F(ReduceMeanTests, ReduceMeanAxes0KeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {1, 2, 2}; const std::vector<float> expectedValue = {30., 1., 40., 2.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {0}, true); } TEST_F(ReduceMeanTests, ReduceMeanAxes1KeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 1, 2}; const std::vector<float> expectedValue = {12.5, 1.5, 35., 1.5, 57.5, 1.5}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {1}, true); } TEST_F(ReduceMeanTests, ReduceMeanAxes2KeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 2, 1}; const std::vector<float> expectedValue = {3., 11., 15.5, 21., 28., 31.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {2}, true); } TEST_F(ReduceMeanTests, ReduceMeanNegativeAxesKeepDims) { const std::vector<int32_t> inputShape = {3, 2, 2}; const std::vector<float> inputData = {5., 1., 20., 2., 30., 1., 40., 2., 55., 1., 60., 2.}; const std::vector<int32_t> expectedShape = {3, 2, 1}; const std::vector<float> expectedValue = {3., 11., 15.5, 21., 28., 31.}; CheckReduceMean(inputShape, inputData, expectedShape, expectedValue, {-1}, true); }
49.707317
95
0.638044
[ "vector" ]
84a81542b03cd28742511f9860e6fac6f3f33eb5
5,533
cpp
C++
coursework2/src/mapgenrator/noise.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
coursework2/src/mapgenrator/noise.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
coursework2/src/mapgenrator/noise.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
// Copyright [2017] <Mengxuan Zhu> #include "../../include/noise.h" double noise::cubic_func(double x, const double param0, const double param1, const double param2, const double param3) { return param0+param1*x+param2*x*x+param3*x*x*x; } std::vector<double> noise::discrete_random_series(unsigned int size) { // set random number generator static std::random_device rd; static std::minstd_rand gen(rd()); static std::uniform_real_distribution<double> randu(0, 1); // generate a series of discreted random numbers std::vector<double> rdlist(size+1); std::generate(rdlist.begin(), rdlist.end(), []{ return randu(gen); }); return rdlist; } /* use cubic spline w/ natural BC the problem is to solve the equation: [[ 1 0 ] *[ m_0 = ypp [ step 4*step step ] m_1 [ step 4*step step ] m_2 [ step 4*step step ] m_3 [ ... ... ... ] ... [ step 4*step step ] m_n-1 [ 0 1 ]] m_n ] where ypp = 6*[0, ..., y_(i+1) - 2*y_i + y_(i-1), ... , 0]/step m is associated with the spline parameters use TDMA to solve this euqation */ std::vector<std::function<double(double)>> noise::cubic_spline_functions (const std::vector<double>& rdlist, const double step) { const unsigned int size = rdlist.size() - 1; // init diag elements std::vector<double> diag_main(size+1, 4*step); *diag_main.begin() = 1; *diag_main.rbegin() = 1; std::vector<double> diag_up(size, step); *diag_up.begin() = 0; std::vector<double> diag_down(size, step); *diag_down.rbegin() = 0; // init ypp vector std::vector<double> ypp(size+1); *ypp.begin() = 0; int index = {1}; std::generate(ypp.begin()+1, ypp.end()-1, [&index, &rdlist, &step]{ std::vector<double>::iterator x; double y2d = 6*(rdlist[index+1]-2*rdlist[index]+rdlist[index-1])/step; ++index; return y2d; }); *ypp.rbegin() = 0; // apply TDMA std::vector<double> mval(size+1); std::vector<double> up_prime(diag_up); std::vector<double> y_prime(ypp); up_prime[0] = diag_up[0] / diag_main[0]; y_prime[0] = ypp[0] / diag_main[0]; for (unsigned int i = 1; i < size; ++i) { up_prime[i] = diag_up[i] / (diag_main[i]-diag_down[i]*up_prime[i-1]); y_prime[i] = (ypp[i]-diag_down[i]*y_prime[i-1]) / (diag_main[i]-diag_down[i]*up_prime[i-1]); } y_prime[size] = (ypp[size]-diag_down[size]*y_prime[size-1]) / (diag_main[size]-diag_down[size]*up_prime[size-1]); mval[size] = y_prime[size]; for (int i = size-1; i >= 0; --i) { mval[i] = y_prime[i]-up_prime[i]*y_prime[i+1]; } // calc params of cubic interpolational function std::vector<std::function<double(double)>> splines(size); index = {0}; using namespace std::placeholders; std::generate(splines.begin(), splines.end(), [&step, &index, &mval, &rdlist]{ double param[4] = { rdlist[index], (rdlist[index+1]-rdlist[index])/step - step*mval[index]/2 - step*(mval[index+1]-mval[index])/6, mval[index]/2, (mval[index+1]-mval[index])/(6*step) }; auto cubic = std::bind(noise::cubic_func, _1, param[0], param[1], param[2], param[3]); ++index; return cubic; }); return splines; } // calc values of interpolational points std::vector<double> noise::coherent_series( std::vector<std::function<double(double)>> splines_function, int unsigned samples, const double step) { const int size = splines_function.size(); std::vector<double> result(size * samples); for (unsigned int i = 0; i < size*samples; ++i) { result[i] = splines_function[static_cast<int>(i/samples)] ((i%samples)*step/samples); } result.push_back(splines_function[size-1](step)); return result; } std::vector<double> noise::coherent_series(unsigned int size, unsigned int samples) { auto rdlist = (noise::discrete_random_series(size)); return noise::coherent_series(noise::cubic_spline_functions(rdlist), samples); } std::vector<std::vector<double>> noise::coherent_map(const unsigned int size1, const unsigned int size2, const unsigned int sample1, const unsigned int sample2) { std::vector<std::vector<double>> semi_coherent_noise_2d(size2+1, std::vector<double>(size1*sample1+1)); // coherent along axis 2, discrete along axis 1 std::generate(semi_coherent_noise_2d.begin(), semi_coherent_noise_2d.end(), [&size1, &sample1]{ auto randomlist = noise::discrete_random_series(size1); auto spline = noise::cubic_spline_functions(randomlist); return noise::coherent_series(spline, sample1); }); // transpose the map std::vector<std::vector<double>> semi_coherent_noise_2dT( size1*sample1+1, std::vector<double>(size2+1)); for (unsigned int i = 0; i < size1*sample1+1; ++i) for (unsigned int j = 0; j < size2+1; ++j) semi_coherent_noise_2dT[i][j] = semi_coherent_noise_2d[j][i]; // calc spline functions along axis 2 std::vector<std::vector<double>> coherent_noise_2d; for (unsigned int i = 0; i < size1*sample1+1; ++i) { auto dummy_coherent_noise = noise::coherent_series (noise::cubic_spline_functions (semi_coherent_noise_2dT[i]), sample2); coherent_noise_2d.push_back(dummy_coherent_noise); } return coherent_noise_2d; }
34.798742
91
0.622086
[ "vector" ]
84a855565b3b8b53c9fe9b5e190f9b406514e8ce
2,186
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/forward_list/debug/swap.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/forward_list/debug/swap.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/23_containers/forward_list/debug/swap.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// { dg-do run { target c++11 } } // Copyright (C) 2010-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // Check that iterators ownership is correctly manage on swap. #include <vector> #include <forward_list> #include <iostream> #include <testsuite_hooks.h> void test01() { std::forward_list<int> fl1{1, 3, 5}; std::forward_list<int> fl2{2, 4, 6}; std::vector<std::forward_list<int>::iterator> fl1_its; fl1_its.push_back(fl1.before_begin()); for (std::forward_list<int>::iterator it = fl1.begin(); it != fl1.end(); ++it) { fl1_its.push_back(it); } fl1_its.push_back(fl1.end()); std::vector<std::forward_list<int>::iterator> fl2_its; fl2_its.push_back(fl2.before_begin()); for (std::forward_list<int>::iterator it = fl2.begin(); it != fl2.end(); ++it) { fl2_its.push_back(it); } fl2_its.push_back(fl2.end()); fl1.swap(fl2); auto fit = fl1.before_begin(); // before-begin iterator is not transfered: // TODO: Validate with LWG group how before begin should be // treated. VERIFY( fit == fl1_its[0] ); // All other iterators are, even paste-the-end ones: for (size_t i = 1; i != fl2_its.size(); ++i) { VERIFY( ++fit == fl2_its[i] ); } fit = fl2.before_begin(); // TODO: Validate with LWG group how before begin should be // treated. VERIFY( fit == fl2_its[0] ); for (size_t i = 1; i != fl1_its.size(); ++i) { VERIFY( ++fit == fl1_its[i] ); } } int main() { test01(); return 0; }
27.670886
74
0.663769
[ "vector" ]
84aa6124d08958b505b60137c31f224a2f9b3b98
7,477
cc
C++
projects/node-pylon/src/genicam/portimpl.cc
bjoernrennfanz/node-pylon
8c20349d112de2674817a07b3ddbe2e5c481a676
[ "MIT" ]
null
null
null
projects/node-pylon/src/genicam/portimpl.cc
bjoernrennfanz/node-pylon
8c20349d112de2674817a07b3ddbe2e5c481a676
[ "MIT" ]
null
null
null
projects/node-pylon/src/genicam/portimpl.cc
bjoernrennfanz/node-pylon
8c20349d112de2674817a07b3ddbe2e5c481a676
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2017 - 2018 Björn Rennfanz <bjoern@fam-rennfanz.de> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // ---------------------------------------------------------------------------- // This is auto generated code by pylon-node-gen. // Do not edit this file or all your changes will be lost after re-generation. // ---------------------------------------------------------------------------- #include "portimpl.h" #include "../pylon_v8.h" using namespace v8; using namespace GenApi_3_0_Basler_pylon_v5_0; Nan::Persistent<FunctionTemplate> PortImplWrap::prototype; Nan::Persistent<Function> PortImplWrap::constructor; // Supported implementations // CPortImpl() // CPortImpl(CPortImpl& const arg0) PortImplWrap::PortImplWrap(Nan::NAN_METHOD_ARGS_TYPE info) : m_PortImpl(NULL) { // Check constructor arguments if (info.Length() == 0) { // CPortImpl() m_PortImpl = new CPortImpl(); } else if ((info.Length() == 1) && (info[0]->IsObject() && (pylon_v8::ToGCString(info[0]->ToObject()->GetConstructorName()) == "CPortImpl"))) { // Unwrap object PortImplWrap* arg0_wrap = ObjectWrap::Unwrap<PortImplWrap>(info[0]->ToObject()); CPortImpl* arg0 = arg0_wrap->GetWrapped(); // CPortImpl(CPortImpl& const arg0) m_PortImpl = new CPortImpl(*arg0); } } PortImplWrap::~PortImplWrap() { delete m_PortImpl; } NAN_MODULE_INIT(PortImplWrap::Initialize) { // Prepare constructor template Local <FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("PortImplWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Register prototypes to template Nan::SetPrototypeMethod(tpl, "getAccessMode", GetAccessMode); Nan::SetPrototypeMethod(tpl, "read", Read); Nan::SetPrototypeMethod(tpl, "write", Write); Nan::SetPrototypeMethod(tpl, "setPortImpl", SetPortImpl); Nan::SetPrototypeMethod(tpl, "getSwapEndianess", GetSwapEndianess); Nan::SetPrototypeMethod(tpl, "replay", Replay); Nan::SetPrototypeMethod(tpl, "invalidateNode", InvalidateNode); // Register template in Node JS prototype.Reset(tpl); Local<Function> function = Nan::GetFunction(tpl).ToLocalChecked(); constructor.Reset(function); Nan::Set(target, Nan::New("CPortImpl").ToLocalChecked(), function); } NAN_METHOD(PortImplWrap::GetAccessMode) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if (info.Length() == 0) { // Call wrapped method EAccessMode result = portImpl->GetAccessMode(); // Set return value info.GetReturnValue().Set(Nan::New<Number>(result)); } } NAN_METHOD(PortImplWrap::GetSwapEndianess) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if (info.Length() == 0) { // Call wrapped method EYesNo result = portImpl->GetSwapEndianess(); // Set return value info.GetReturnValue().Set(Nan::New<Number>(result)); } } NAN_METHOD(PortImplWrap::InvalidateNode) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if (info.Length() == 0) { // Call wrapped method portImpl->InvalidateNode(); // Set return value to undefined info.GetReturnValue().SetUndefined(); } } NAN_METHOD(PortImplWrap::Read) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if ((info.Length() == 3) && info[0]->IsObject() && info[1]->IsNumber() && info[2]->IsNumber()) { // TODO: Implement wrapper for void // Convert from number value __int128_t arg1 = static_cast<__int128_t>(info[1]->NumberValue()); // Convert from number value __int128_t arg2 = static_cast<__int128_t>(info[2]->NumberValue()); // Call wrapped method portImpl->Read(arg0, arg1, arg2); // Set return value to undefined info.GetReturnValue().SetUndefined(); } } NAN_METHOD(PortImplWrap::Replay) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if ((info.Length() == 2) && (info[0]->IsObject() && (pylon_v8::ToGCString(info[0]->ToObject()->GetConstructorName()) == "IPortWriteList")) && info[1]->IsBoolean()) { // Unwrap object PortWriteListWrap* arg0_wrap = ObjectWrap::Unwrap<PortWriteListWrap>(info[0]->ToObject()); IPortWriteList* arg0 = arg0_wrap->GetWrapped(); // Convert from boolean value bool arg1 = info[1]->BooleanValue(); // Call wrapped method portImpl->Replay(arg0, arg1); // Set return value to undefined info.GetReturnValue().SetUndefined(); } } NAN_METHOD(PortImplWrap::SetPortImpl) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if ((info.Length() == 1) && (info[0]->IsObject() && (pylon_v8::ToGCString(info[0]->ToObject()->GetConstructorName()) == "IPort"))) { // Unwrap object PortWrap* arg0_wrap = ObjectWrap::Unwrap<PortWrap>(info[0]->ToObject()); IPort* arg0 = arg0_wrap->GetWrapped(); // Call wrapped method portImpl->SetPortImpl(arg0); // Set return value to undefined info.GetReturnValue().SetUndefined(); } } NAN_METHOD(PortImplWrap::Write) { PortImplWrap* wrappedPortImpl = ObjectWrap::Unwrap<PortImplWrap>(info.This()); CPortImpl* portImpl = wrappedPortImpl->GetWrapped(); if ((info.Length() == 3) && info[0]->IsObject() && info[1]->IsNumber() && info[2]->IsNumber()) { // TODO: Implement wrapper for void // Convert from number value __int128_t arg1 = static_cast<__int128_t>(info[1]->NumberValue()); // Convert from number value __int128_t arg2 = static_cast<__int128_t>(info[2]->NumberValue()); // Call wrapped method portImpl->Write(arg0, arg1, arg2); // Set return value to undefined info.GetReturnValue().SetUndefined(); } }
34.141553
167
0.659489
[ "object" ]
84ab30aad4e5340bcd315e546775e4b30669f2a7
5,739
cpp
C++
Project/Source/Modules/ModuleAudio.cpp
TBD-org/RealBugEngine
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
7
2021-04-26T21:32:12.000Z
2022-02-14T13:48:53.000Z
Project/Source/Modules/ModuleAudio.cpp
TBD-org/RealBugEngine
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
66
2021-04-24T10:08:07.000Z
2021-10-05T16:52:56.000Z
Project/Source/Modules/ModuleAudio.cpp
TBD-org/Tesseract
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
1
2021-07-13T21:26:13.000Z
2021-07-13T21:26:13.000Z
#include "ModuleAudio.h" #include "Globals.h" #include "Application.h" #include "Modules/ModuleScene.h" #include "Utils/alErrors.h" #include "Utils/alcErrors.h" #include "Scene.h" #include "AL/al.h" #include "Utils/Leaks.h" bool ModuleAudio::Init() { return OpenSoundDevice(); } UpdateStatus ModuleAudio::Update() { size_t listeners = App->scene->scene->audioListenerComponents.Count(); if (listeners <= 0) { LOG("Warning: Missing audio listener in scene"); } else if (listeners > 1) { LOG("Warning: More than one audio listener in scene"); } return UpdateStatus::CONTINUE; } bool ModuleAudio::CleanUp() { return CloseSoundDevice(); } bool ModuleAudio::OpenSoundDevice(ALCchar* device) { openALDevice = alcOpenDevice(device); // Get Sound Device. nullptr = default if (!openALDevice) { LOG("ERROR: Failed to get sound device"); return false; } if (!alcCall(alcCreateContext, openALContext, openALDevice, openALDevice, nullptr) || !openALContext) { // Create Context LOG("ERROR: Could not create audio context"); return false; } if (!alcCall(alcMakeContextCurrent, contextMadeCurrent, openALDevice, openALContext) // Make Context Current || contextMadeCurrent != ALC_TRUE) { LOG("ERROR: Could not make audio context current"); return false; } const ALCchar* name = nullptr; if (alcIsExtensionPresent(openALDevice, "ALC_ENUMERATE_ALL_EXT")) { name = alcGetString(openALDevice, ALC_ALL_DEVICES_SPECIFIER); } if (!name || alcGetError(openALDevice) != AL_NO_ERROR) { name = alcGetString(openALDevice, ALC_DEVICE_SPECIFIER); } LOG("Using Sound Device: \"%s\"", name); // Generate Sources alCall(alGenSources, NUM_SOURCES, sources); return true; } bool ModuleAudio::CloseSoundDevice() { StopAllSources(); alCall(alDeleteSources, NUM_SOURCES, sources); memset(sources, 0, sizeof(sources)); alcCall(alcMakeContextCurrent, contextMadeCurrent, openALDevice, nullptr); alcCall(alcDestroyContext, openALDevice, openALContext); alcCloseDevice(openALDevice); return true; } void ModuleAudio::GetSoundDevices(std::vector<std::string>& devicesParsed) { devices.clear(); devicesParsed.clear(); ALCchar* devicesList = (ALCchar*) alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER); ALCchar* nptr; nptr = devicesList; while (*(nptr += strlen(devicesList) + 1) != 0) { devices.push_back(devicesList); devicesList = nptr; } devices.push_back(devicesList); for (std::string device : devices) { std::string newDevice = device.substr(15, device.length()); devicesParsed.push_back(newDevice.c_str()); } } const std::string ModuleAudio::GetCurrentDevice() { std::string currentDevice = alcGetString(openALDevice, ALC_ALL_DEVICES_SPECIFIER); return currentDevice.substr(15, currentDevice.length()); } void ModuleAudio::SetSoundDevice(int pos) { CloseSoundDevice(); OpenSoundDevice(devices[pos]); } unsigned ModuleAudio::GetAvailableSource(bool reverse) const { if (reverse) { for (int i = NUM_SOURCES - 1; i >= 0; --i) { if (!isActive(sources[i])) { return sources[i]; } } return 0; } else { for (int i = 0; i < NUM_SOURCES; ++i) { if (!isActive(sources[i])) { return sources[i]; } } return 0; } } void ModuleAudio::DeleteRelatedBuffer(unsigned int bufferId) { for (int i = 0; i < NUM_SOURCES; ++i) { ALint currentBuffer = 0; alGetSourcei(sources[i], AL_BUFFER, &currentBuffer); if (bufferId == currentBuffer) { alSourcei(sources[i], AL_BUFFER, NULL); } } } bool ModuleAudio::isActive(unsigned sourceId) const { ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); return (state == AL_PLAYING || state == AL_PAUSED); } bool ModuleAudio::isAvailable(unsigned sourceId) const { ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); return (state == AL_STOPPED || state == AL_INITIAL); } void ModuleAudio::Stop(unsigned sourceId) const { if (sourceId) { alSourceStop(sourceId); sourceId = 0; } } void ModuleAudio::StopAllSources() { for (int i = 0; i < NUM_SOURCES; ++i) { if (isActive(sources[i])) { Stop(sources[i]); } } } float ModuleAudio::GetGainMainChannel() { return gainMainChannel; } float ModuleAudio::GetGainMusicChannel() const { return gainMusicChannel; } float ModuleAudio::GetGainSFXChannel() const { return gainSFXChannel; } void ModuleAudio::SetGainMainChannel(float _gainMainChannel) { if (App->scene->scene->audioListenerComponents.Count() == 0) { return; } gainMainChannel = _gainMainChannel; Pool<ComponentAudioListener>::Iterator audioListener = App->scene->scene->audioListenerComponents.begin(); (*audioListener).SetAudioVolume(gainMainChannel); } void ModuleAudio::SetGainMusicChannel(float _gainMusicChannel) { gainMusicChannel = _gainMusicChannel; for (ComponentAudioSource& audioSource : App->scene->scene->audioSourceComponents) { if (audioSource.GetIsMusic()) { audioSource.SetGainMultiplier(gainMusicChannel); } } } void ModuleAudio::SetGainSFXChannel(float _gainSFXChannel) { gainSFXChannel = _gainSFXChannel; for (ComponentAudioSource& audioSource : App->scene->scene->audioSourceComponents) { if (!audioSource.GetIsMusic()) { audioSource.SetGainMultiplier(gainSFXChannel); } } } void ModuleAudio::SetGainMainChannelInternal(float _gainMainChannel) { gainMainChannel = _gainMainChannel; } void ModuleAudio::SetGainMusicChannelInternal(float _gainMusicChannel) { gainMusicChannel = _gainMusicChannel; } void ModuleAudio::SetGainSFXChannelInternal(float _gainSFXChannel) { gainSFXChannel = _gainSFXChannel; }
27.328571
123
0.708834
[ "vector" ]
84ad17e1cb0045dc344ec4791235881d63b0da64
6,742
cpp
C++
searchlib/src/vespa/searchlib/features/nativefieldmatchfeature.cpp
atveit/vespa
545898728f29a9ed7fcae223bfb0c85f24227af8
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
searchlib/src/vespa/searchlib/features/nativefieldmatchfeature.cpp
atveit/vespa
545898728f29a9ed7fcae223bfb0c85f24227af8
[ "Apache-2.0" ]
1
2021-01-21T01:37:37.000Z
2021-01-21T01:37:37.000Z
searchlib/src/vespa/searchlib/features/nativefieldmatchfeature.cpp
atveit/vespa
545898728f29a9ed7fcae223bfb0c85f24227af8
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "nativefieldmatchfeature.h" #include "valuefeature.h" #include "utils.h" #include <vespa/searchlib/fef/fieldinfo.h> #include <vespa/searchlib/fef/indexproperties.h> #include <vespa/searchlib/fef/itablemanager.h> #include <vespa/searchlib/fef/properties.h> using namespace search::fef; namespace search { namespace features { const uint32_t NativeFieldMatchParam::NOT_DEF_FIELD_LENGTH(std::numeric_limits<uint32_t>::max()); feature_t NativeFieldMatchExecutor::calculateScore(const MyQueryTerm &qt, uint32_t docId) { feature_t termScore = 0; for (size_t i = 0; i < qt.handles().size(); ++i) { TermFieldHandle tfh = qt.handles()[i]; const TermFieldMatchData *tfmd = _md->resolveTermField(tfh); const NativeFieldMatchParam & param = _params.vector[tfmd->getFieldId()]; if (tfmd->getDocId() == docId) { // do we have a hit FieldPositionsIterator pos = tfmd->getIterator(); if (pos.valid()) { uint32_t fieldLength = getFieldLength(param, pos.getFieldLength()); termScore += ((getFirstOccBoost(param, pos.getPosition(), fieldLength) * param.firstOccImportance) + (getNumOccBoost(param, pos.size(), fieldLength) * (1 - param.firstOccImportance))) * param.fieldWeight / param.maxTableSum; } } } termScore *= (qt.significance() * qt.termData()->getWeight().percent()); return termScore; } NativeFieldMatchExecutor::NativeFieldMatchExecutor(const IQueryEnvironment & env, const NativeFieldMatchParams & params) : FeatureExecutor(), _params(params), _queryTerms(), _totalTermWeight(0), _divisor(0), _md(nullptr) { for (uint32_t i = 0; i < env.getNumTerms(); ++i) { MyQueryTerm qt(QueryTermFactory::create(env, i)); if (qt.termData()->getWeight().percent() != 0) // only consider query terms with contribution { typedef search::fef::ITermFieldRangeAdapter FRA; uint32_t totalFieldWeight = 0; for (FRA iter(*qt.termData()); iter.valid(); iter.next()) { const ITermFieldData& tfd = iter.get(); uint32_t fieldId = tfd.getFieldId(); if (_params.considerField(fieldId)) { // only consider fields with contribution totalFieldWeight += _params.vector[fieldId].fieldWeight; qt.handles().push_back(tfd.getHandle()); } } if (!qt.handles().empty()) { _queryTerms.push_back(qt); _divisor += (qt.significance() * qt.termData()->getWeight().percent() * totalFieldWeight); } } } } void NativeFieldMatchExecutor::execute(uint32_t docId) { feature_t score = 0; for (size_t i = 0; i < _queryTerms.size(); ++i) { score += calculateScore(_queryTerms[i], docId); } if (_divisor > 0) { score /= _divisor; } outputs().set_number(0, score); } void NativeFieldMatchExecutor::handle_bind_match_data(const fef::MatchData &md) { _md = &md; } NativeFieldMatchBlueprint::NativeFieldMatchBlueprint() : Blueprint("nativeFieldMatch"), _params(), _defaultFirstOcc("expdecay(8000,12.50)"), _defaultNumOcc("loggrowth(1500,4000,19)") { } NativeFieldMatchBlueprint::~NativeFieldMatchBlueprint() { } void NativeFieldMatchBlueprint::visitDumpFeatures(const IIndexEnvironment & env, IDumpFeatureVisitor & visitor) const { (void) env; visitor.visitDumpFeature(getBaseName()); } Blueprint::UP NativeFieldMatchBlueprint::createInstance() const { return Blueprint::UP(new NativeFieldMatchBlueprint()); } bool NativeFieldMatchBlueprint::setup(const IIndexEnvironment & env, const ParameterList & params) { _params.resize(env.getNumFields()); FieldWrapper fields(env, params, FieldType::INDEX); vespalib::string defaultFirstOccImportance = env.getProperties().lookup(getBaseName(), "firstOccurrenceImportance").get("0.5"); for (uint32_t i = 0; i < fields.getNumFields(); ++i) { const FieldInfo * info = fields.getField(i); uint32_t fieldId = info->id(); NativeFieldMatchParam & param = _params.vector[fieldId]; param.field = true; if ((param.firstOccTable = util::lookupTable(env, getBaseName(), "firstOccurrenceTable", info->name(), _defaultFirstOcc)) == NULL) { return false; } if ((param.numOccTable = util::lookupTable(env, getBaseName(), "occurrenceCountTable", info->name(), _defaultNumOcc)) == NULL) { return false; } param.fieldWeight = indexproperties::FieldWeight::lookup(env.getProperties(), info->name()); if (param.fieldWeight == 0 || info->isFilter()) { param.field = false; } Property afl = env.getProperties().lookup(getBaseName(), "averageFieldLength", info->name()); if (afl.found()) { param.averageFieldLength = util::strToNum<uint32_t>(afl.get()); } param.firstOccImportance = util::strToNum<feature_t> (env.getProperties().lookup(getBaseName(), "firstOccurrenceImportance", info->name()). get(defaultFirstOccImportance)); if (NativeRankBlueprint::useTableNormalization(env)) { const Table * fo = param.firstOccTable; const Table * no = param.numOccTable; if (fo != NULL && no != NULL) { double value = (fo->max() * param.firstOccImportance) + (no->max() * (1 - param.firstOccImportance)); _params.setMaxTableSums(fieldId, value); } } if (param.field) { env.hintFieldAccess(fieldId); } } _params.minFieldLength = util::strToNum<uint32_t>(env.getProperties().lookup (getBaseName(), "minFieldLength").get("6")); describeOutput("score", "The native field match score"); return true; } FeatureExecutor & NativeFieldMatchBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const { NativeFieldMatchExecutor &native = stash.create<NativeFieldMatchExecutor>(env, _params); if (native.empty()) { return stash.create<ValueExecutor>(std::vector<feature_t>(1, 0.0)); } else { return native; } } } // namespace features } // namespace search
36.053476
131
0.617621
[ "vector" ]
84ad62759e4a78ea687183651aeba3dbc339e04e
5,543
hpp
C++
apps/opencs/view/settings/view.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/settings/view.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/settings/view.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef CSVSETTINGS_VIEW_HPP #define CSVSETTINGS_VIEW_HPP #include <QWidget> #include <QList> #include "frame.hpp" #include "../../model/settings/support.hpp" class QGroupBox; class QStringList; class QStandardItem; class QItemSelection; class QAbstractItemModel; class QItemSelectionModel; namespace CSMSettings { class Setting; } namespace CSVSettings { class Page; class View : public Frame { Q_OBJECT ///Pointer to the owning Page instance Page *mParentPage; ///Pointer to the selection model for the view QItemSelectionModel *mSelectionModel; ///Pointer to the data model for the view's selection model QAbstractItemModel *mDataModel; ///State indicating whether or not the setting has a pre-defined list ///of values, limiting possible definitions bool mHasFixedValues; ///State indicating whether the view will allow multiple values bool mIsMultiValue; ///'pagename.settingname' form of the view's id QString mViewKey; ///indicates whether or not the setting is written to file bool mSerializable; public: explicit View (CSMSettings::Setting *setting, Page *parent); ///Returns the index / row of the passed value, -1 if not found. int currentIndex () const; ///Returns the number of rows in the view's data model int rowCount() const; ///Returns bool indicating the data in this view should / should not ///be serialized to a config file bool serializable() const { return mSerializable; } ///Returns a pointer to the view's owning parent page const Page *parentPage() const { return mParentPage; } ///Returns the selected items in the selection model as a QStringList QStringList selectedValues() const; ///Sets the selected items in the selection model based on passed list. ///Bools allow opt-out of updating the view ///or signaling the view was updatedto avoid viscious cylcing. void setSelectedValues (const QStringList &values, bool updateView = true, bool signalUpdate = true) const; void setSelectedValue (const QString &value, bool updateView = true, bool signalUpdate = true); ///Returns the value of the data model at the specified row QString value (int row) const; QString viewKey() const { return mViewKey; } protected: /// Returns the model which provides data for the selection model QAbstractItemModel *dataModel() { return mDataModel; } ///Accessor function for subclasses bool isMultiValue() { return mIsMultiValue; } ///Returns the view selection model QItemSelectionModel *selectionModel() { return mSelectionModel;} ///Global callback for basic view initialization void showEvent ( QShowEvent * event ); ///Virtual for updating a specific View subclass ///bool indicates whether viewUpdated() signal is emitted virtual void updateView (bool signalUpdate = true) const; ///Returns the pixel width corresponding to the specified number of ///characters. int widgetWidth(int characterCount) const; private: ///Constructs the view layout void buildView(); ///Constructs the data and selection models void buildModel (const CSMSettings::Setting *setting); ///In cases where the view has a pre-defined list of possible values, ///a QStringListModel is created using those values. ///View changes operate on the selection model only. void buildFixedValueModel (const QStringList &definitions); ///In cases where the view does not have a pre-defined list of possible ///values, a QStandardItemModel is created, containing the actual ///setting definitions. View changes first update the data in the ///model to match the data in the view. The selection model always ///selects all values. void buildUpdatableValueModel (const QStringList &definitions); ///Refreshes the view void refresh() const; ///Convenince function for selection model's select() method. Also ///clears out the model beforehand to ensure complete selection. void select (const QItemSelection &selection) const; ///Compares two string lists "loosely", ensuring that all values in ///one list are contained entirely in the other, and that neither list ///has more values than the other. List order is not considered. bool stringListsMatch (const QStringList &list1, const QStringList &list2) const; ///Converts a string list to a list of QStandardItem pointers. QList <QStandardItem *> toStandardItemList(const QStringList &) const; signals: ///Signals that the view has been changed. void viewUpdated(const QString &, const QStringList &) const; }; class IViewFactory { public: ///Creation interface for view factories virtual View *createView (CSMSettings::Setting *setting, Page *parent) = 0; }; } #endif // CSVSETTINGS_VIEW_HPP
34.428571
79
0.639185
[ "model" ]
84af15cfd3bbfac9a5791ecd6ed14d8b958ac9db
11,211
cpp
C++
Reverb/Windows/Reverb/Source/PluginProcessor.cpp
landonviator/Reverb
ac37ea100e595dd246de571ec47c9a9271562fbb
[ "MIT" ]
null
null
null
Reverb/Windows/Reverb/Source/PluginProcessor.cpp
landonviator/Reverb
ac37ea100e595dd246de571ec47c9a9271562fbb
[ "MIT" ]
null
null
null
Reverb/Windows/Reverb/Source/PluginProcessor.cpp
landonviator/Reverb
ac37ea100e595dd246de571ec47c9a9271562fbb
[ "MIT" ]
null
null
null
/* ============================================================================== This file contains the basic framework code for a JUCE plugin processor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== ReverbAudioProcessor::ReverbAudioProcessor() #ifndef JucePlugin_PreferredChannelConfigurations : AudioProcessor (BusesProperties() #if ! JucePlugin_IsMidiEffect #if ! JucePlugin_IsSynth .withInput ("Input", juce::AudioChannelSet::stereo(), false) #endif .withOutput ("Output", juce::AudioChannelSet::stereo(), false) #endif ), treeState (*this, nullptr, "PARAMETER", createParameterLayout()) #endif { treeState.addParameterListener (filterEngageId, this); treeState.addParameterListener (filterModeId, this); treeState.addParameterListener (cutoffSliderId, this); treeState.addParameterListener (resonanceSliderId, this); treeState.addParameterListener (driveSliderId, this); treeState.addParameterListener (roomSizeSliderId, this); treeState.addParameterListener (dampingSliderId, this); treeState.addParameterListener (widthSliderId, this); treeState.addParameterListener (drySliderId, this); treeState.addParameterListener (wetSliderId, this); } ReverbAudioProcessor::~ReverbAudioProcessor() { treeState.removeParameterListener (filterEngageId, this); treeState.removeParameterListener (filterModeId, this); treeState.removeParameterListener (cutoffSliderId, this); treeState.removeParameterListener (resonanceSliderId, this); treeState.removeParameterListener (driveSliderId, this); treeState.removeParameterListener (roomSizeSliderId, this); treeState.removeParameterListener (dampingSliderId, this); treeState.removeParameterListener (widthSliderId, this); treeState.removeParameterListener (drySliderId, this); treeState.removeParameterListener (wetSliderId, this); } //============================================================================== const juce::String ReverbAudioProcessor::getName() const { return JucePlugin_Name; } bool ReverbAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool ReverbAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } bool ReverbAudioProcessor::isMidiEffect() const { #if JucePlugin_IsMidiEffect return true; #else return false; #endif } double ReverbAudioProcessor::getTailLengthSeconds() const { return 0.0; } int ReverbAudioProcessor::getNumPrograms() { return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs, // so this should be at least 1, even if you're not really implementing programs. } int ReverbAudioProcessor::getCurrentProgram() { return 0; } void ReverbAudioProcessor::setCurrentProgram (int index) { } const juce::String ReverbAudioProcessor::getProgramName (int index) { return {}; } void ReverbAudioProcessor::changeProgramName (int index, const juce::String& newName) { } //============================================================================== void ReverbAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock) { juce::dsp::ProcessSpec spec; spec.maximumBlockSize = samplesPerBlock; spec.sampleRate = sampleRate; spec.numChannels = getTotalNumOutputChannels(); ladderProcessor.prepare(spec); ladderProcessor.reset(); ladderProcessor.setCutoffFrequencyHz(*treeState.getRawParameterValue(cutoffSliderId)); ladderProcessor.setResonance(*treeState.getRawParameterValue(resonanceSliderId) * 0.01); ladderProcessor.setDrive(pow(10, *treeState.getRawParameterValue(driveSliderId) / 20)); if (*treeState.getRawParameterValue(filterEngageId) == 0){ ladderProcessor.setEnabled(false); } else { ladderProcessor.setEnabled(true); } if (*treeState.getRawParameterValue(filterModeId) == 0){ ladderProcessor.setMode(juce::dsp::LadderFilterMode::LPF12); } else { ladderProcessor.setMode(juce::dsp::LadderFilterMode::LPF24); } reverbProcessor.prepare(spec); reverbProcessor.reset(); reverbParams.roomSize = *treeState.getRawParameterValue(roomSizeSliderId) * .01; reverbParams.damping = *treeState.getRawParameterValue(dampingSliderId) * .01; reverbParams.width = *treeState.getRawParameterValue(widthSliderId) * .01; reverbParams.dryLevel = *treeState.getRawParameterValue(drySliderId) * .01; reverbParams.wetLevel = *treeState.getRawParameterValue(wetSliderId) * .01; reverbProcessor.setParameters(reverbParams); } void ReverbAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. } #ifndef JucePlugin_PreferredChannelConfigurations bool ReverbAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const { #if JucePlugin_IsMidiEffect juce::ignoreUnused (layouts); return true; #else // This is the place where you check if the layout is supported. // In this template code we only support mono or stereo. // Some plugin hosts, such as certain GarageBand versions, will only // load plugins that support stereo bus layouts. if (layouts.getMainOutputChannelSet() != juce::AudioChannelSet::mono() && layouts.getMainOutputChannelSet() != juce::AudioChannelSet::stereo()) return false; // This checks if the input layout matches the output layout #if ! JucePlugin_IsSynth if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet()) return false; #endif return true; #endif } #endif void ReverbAudioProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages) { juce::ScopedNoDenormals noDenormals; auto totalNumInputChannels = getTotalNumInputChannels(); auto totalNumOutputChannels = getTotalNumOutputChannels(); for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) buffer.clear (i, 0, buffer.getNumSamples()); juce::dsp::AudioBlock<float> audioBlock {buffer}; ladderProcessor.process(juce::dsp::ProcessContextReplacing<float>(audioBlock)); reverbProcessor.process(juce::dsp::ProcessContextReplacing<float>(audioBlock)); } //============================================================================== bool ReverbAudioProcessor::hasEditor() const { return true; // (change this to false if you choose to not supply an editor) } juce::AudioProcessorEditor* ReverbAudioProcessor::createEditor() { return new ReverbAudioProcessorEditor (*this); } //============================================================================== void ReverbAudioProcessor::getStateInformation (juce::MemoryBlock& destData) { juce::MemoryOutputStream stream(destData, false); treeState.state.writeToStream (stream); } void ReverbAudioProcessor::setStateInformation (const void* data, int sizeInBytes) { juce::ValueTree tree = juce::ValueTree::readFromData (data, size_t (sizeInBytes)); if (tree.isValid()) { treeState.state = tree; } } void ReverbAudioProcessor::parameterChanged(const juce::String &parameterID, float newValue){ if (parameterID == cutoffSliderId){ ladderProcessor.setCutoffFrequencyHz(newValue); } else if (parameterID == resonanceSliderId){ ladderProcessor.setResonance(newValue * 0.01); } else if (parameterID == driveSliderId){ ladderProcessor.setDrive(pow(10, newValue / 20)); } else if (parameterID == filterEngageId){ if (newValue == 0){ ladderProcessor.setEnabled(false); } else { ladderProcessor.setEnabled(true); } } else if (parameterID == filterModeId){ if (newValue == 0){ ladderProcessor.setMode(juce::dsp::LadderFilterMode::LPF12); } else { ladderProcessor.setMode(juce::dsp::LadderFilterMode::LPF24); } } else if (parameterID == wetSliderId){ reverbParams.wetLevel = newValue * 0.01; reverbProcessor.setParameters(reverbParams); } else if (parameterID == drySliderId){ reverbParams.dryLevel = newValue * 0.01; reverbProcessor.setParameters(reverbParams); } else if (parameterID == roomSizeSliderId){ reverbParams.roomSize = newValue * 0.01; reverbProcessor.setParameters(reverbParams); } else if (parameterID == dampingSliderId){ reverbParams.damping = newValue * 0.01; reverbProcessor.setParameters(reverbParams); } else { reverbParams.width = newValue * 0.01; reverbProcessor.setParameters(reverbParams); } } juce::AudioProcessorValueTreeState::ParameterLayout ReverbAudioProcessor::createParameterLayout() { std::vector <std::unique_ptr<juce::RangedAudioParameter>> params; params.reserve(10); auto filterEngageParam = std::make_unique<juce::AudioParameterInt>(filterEngageId, filterEngageName, 0, 1, 1); auto filterModeParam = std::make_unique<juce::AudioParameterInt>(filterModeId, filterModeName, 0, 1, 0); auto cutoffParam = std::make_unique<juce::AudioParameterInt>(cutoffSliderId, cutoffSliderName, 20, 20000, 1200); auto resonanceParam = std::make_unique<juce::AudioParameterInt>(resonanceSliderId, resonanceSliderName, 0, 100, 0); auto driveParam = std::make_unique<juce::AudioParameterFloat>(driveSliderId, driveSliderName, 0.0f, 24.0f, 0.0f); auto roomSizeParam = std::make_unique<juce::AudioParameterInt>(roomSizeSliderId, roomSizeSliderName, 0, 100, 50); auto dampingParam = std::make_unique<juce::AudioParameterInt>(dampingSliderId, dampingSliderName, 0, 100, 50); auto widthParam = std::make_unique<juce::AudioParameterInt>(widthSliderId, widthSliderName, 0, 100, 100); auto dryParam = std::make_unique<juce::AudioParameterInt>(drySliderId, drySliderName, 0, 100, 0); auto wetParam = std::make_unique<juce::AudioParameterInt>(wetSliderId, wetSliderName, 0, 100, 50); params.push_back(std::move(filterEngageParam)); params.push_back(std::move(filterModeParam)); params.push_back(std::move(cutoffParam)); params.push_back(std::move(resonanceParam)); params.push_back(std::move(driveParam)); params.push_back(std::move(roomSizeParam)); params.push_back(std::move(dampingParam)); params.push_back(std::move(widthParam)); params.push_back(std::move(dryParam)); params.push_back(std::move(wetParam)); return { params.begin(), params.end() }; } //============================================================================== // This creates new instances of the plugin.. juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new ReverbAudioProcessor(); }
37.245847
119
0.678173
[ "vector" ]
84af18b2993cfc597370649c73d334dbfdebb227
14,135
hpp
C++
vendor/mapbox-gl-native/vendor/mapbox-base/mapbox/supercluster.hpp/include/supercluster.hpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/mapbox/supercluster.hpp/include/supercluster.hpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/mapbox/supercluster.hpp/include/supercluster.hpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#pragma once #include <kdbush.hpp> #include <mapbox/feature.hpp> #include <mapbox/geometry/point_arithmetic.hpp> #include <algorithm> #include <cmath> #include <cstdint> #include <functional> #include <iomanip> #include <memory> #include <sstream> #include <vector> #ifdef DEBUG_TIMER #include <chrono> #include <iostream> #endif namespace mapbox { namespace supercluster { using namespace mapbox::geometry; using namespace mapbox::feature; struct Cluster { const point<double> pos; const std::uint32_t num_points; std::uint32_t id; std::uint32_t parent_id = 0; bool visited = false; std::unique_ptr<property_map> properties{ nullptr }; Cluster(const point<double> pos_, const std::uint32_t num_points_, const std::uint32_t id_) : pos(pos_), num_points(num_points_), id(id_) { } Cluster(const point<double> pos_, const std::uint32_t num_points_, const std::uint32_t id_, const property_map &properties_) : pos(pos_), num_points(num_points_), id(id_) { if (!properties_.empty()) { properties = std::make_unique<property_map>(properties_); } } mapbox::feature::feature<double> toGeoJSON() const { const double x = (pos.x - 0.5) * 360.0; const double y = 360.0 * std::atan(std::exp((180.0 - pos.y * 360.0) * M_PI / 180)) / M_PI - 90.0; return { point<double>{ x, y }, getProperties(), identifier(static_cast<std::uint64_t>(id)) }; } property_map getProperties() const { property_map result{ { "cluster", true }, { "cluster_id", static_cast<std::uint64_t>(id) }, { "point_count", static_cast<std::uint64_t>(num_points) } }; std::stringstream ss; if (num_points >= 1000) { ss << std::fixed; if (num_points < 10000) { ss << std::setprecision(1); } ss << double(num_points) / 1000 << "k"; } else { ss << num_points; } result.emplace("point_count_abbreviated", ss.str()); if (properties) { for (const auto &property : *properties) { result.emplace(property); } } return result; } }; } // namespace supercluster } // namespace mapbox namespace kdbush { using Cluster = mapbox::supercluster::Cluster; template <> struct nth<0, Cluster> { inline static double get(const Cluster &c) { return c.pos.x; }; }; template <> struct nth<1, Cluster> { inline static double get(const Cluster &c) { return c.pos.y; }; }; } // namespace kdbush namespace mapbox { namespace supercluster { #ifdef DEBUG_TIMER class Timer { public: std::chrono::high_resolution_clock::time_point started; Timer() { started = std::chrono::high_resolution_clock::now(); } void operator()(std::string msg) { const auto now = std::chrono::high_resolution_clock::now(); const auto ms = std::chrono::duration_cast<std::chrono::microseconds>(now - started); std::cerr << msg << ": " << double(ms.count()) / 1000 << "ms\n"; started = now; } }; #endif struct Options { std::uint8_t minZoom = 0; // min zoom to generate clusters on std::uint8_t maxZoom = 16; // max zoom level to cluster the points on std::uint16_t radius = 40; // cluster radius in pixels std::uint16_t extent = 512; // tile extent (radius is calculated relative to it) std::function<property_map(const property_map &)> map = [](const property_map &p) -> property_map { return p; }; std::function<void(property_map &, const property_map &)> reduce{ nullptr }; }; class Supercluster { using GeoJSONPoint = point<double>; using GeoJSONFeature = mapbox::feature::feature<double>; using GeoJSONFeatures = feature_collection<double>; using TilePoint = point<std::int16_t>; using TileFeature = mapbox::feature::feature<std::int16_t>; using TileFeatures = feature_collection<std::int16_t>; public: const GeoJSONFeatures features; const Options options; Supercluster(const GeoJSONFeatures &features_, const Options options_ = Options()) : features(features_), options(options_) { #ifdef DEBUG_TIMER Timer timer; #endif // convert and index initial points zooms.emplace(options.maxZoom + 1, Zoom(features, options)); #ifdef DEBUG_TIMER timer(std::to_string(features.size()) + " initial points"); #endif for (int z = options.maxZoom; z >= options.minZoom; z--) { // cluster points from the previous zoom level const double r = options.radius / (options.extent * std::pow(2, z)); zooms.emplace(z, Zoom(zooms[z + 1], r, z, options)); #ifdef DEBUG_TIMER timer(std::to_string(zooms[z].clusters.size()) + " clusters"); #endif } } TileFeatures getTile(const std::uint8_t z, const std::uint32_t x_, const std::uint32_t y) const { TileFeatures result; const auto zoom_iter = zooms.find(limitZoom(z)); assert(zoom_iter != zooms.end()); const auto &zoom = zoom_iter->second; std::uint32_t z2 = std::pow(2, z); const double r = static_cast<double>(options.radius) / options.extent; std::int32_t x = x_; const auto visitor = [&, this](const auto &id) { assert(id < zoom.clusters.size()); const auto &c = zoom.clusters[id]; const TilePoint point(::round(this->options.extent * (c.pos.x * z2 - x)), ::round(this->options.extent * (c.pos.y * z2 - y))); if (c.num_points == 1) { const auto &original_feature = this->features[c.id]; result.emplace_back(point, original_feature.properties, original_feature.id); } else { result.emplace_back(point, c.getProperties(), identifier(static_cast<std::uint64_t>(c.id))); } }; const double top = (y - r) / z2; const double bottom = (y + 1 + r) / z2; zoom.tree.range((x - r) / z2, top, (x + 1 + r) / z2, bottom, visitor); if (x_ == 0) { x = z2; zoom.tree.range(1 - r / z2, top, 1, bottom, visitor); } if (x_ == z2 - 1) { x = -1; zoom.tree.range(0, top, r / z2, bottom, visitor); } return result; } GeoJSONFeatures getChildren(const std::uint32_t cluster_id) const { GeoJSONFeatures children; eachChild(cluster_id, [&, this](const auto &c) { children.push_back(this->clusterToGeoJSON(c)); }); return children; } GeoJSONFeatures getLeaves(const std::uint32_t cluster_id, const std::uint32_t limit = 10, const std::uint32_t offset = 0) const { GeoJSONFeatures leaves; std::uint32_t skipped = 0; std::uint32_t limit_ = limit; eachLeaf(cluster_id, limit_, offset, skipped, [&, this](const auto &c) { leaves.push_back(this->clusterToGeoJSON(c)); }); return leaves; } std::uint8_t getClusterExpansionZoom(std::uint32_t cluster_id) const { auto cluster_zoom = (cluster_id % 32) - 1; while (cluster_zoom <= options.maxZoom) { std::uint32_t num_children = 0; eachChild(cluster_id, [&](const auto &c) { num_children++; cluster_id = c.id; }); cluster_zoom++; if (num_children != 1) break; } return cluster_zoom; } private: struct Zoom { kdbush::KDBush<Cluster, std::uint32_t> tree; std::vector<Cluster> clusters; Zoom() = default; Zoom(const GeoJSONFeatures &features_, const Options &options_) { // generate a cluster object for each point std::uint32_t i = 0; clusters.reserve(features_.size()); for (const auto &f : features_) { if (options_.reduce) { const auto clusterProperties = options_.map(f.properties); clusters.emplace_back(project(f.geometry.get<GeoJSONPoint>()), 1, i++, clusterProperties); } else { clusters.emplace_back(project(f.geometry.get<GeoJSONPoint>()), 1, i++); } } tree.fill(clusters); } Zoom(Zoom &previous, const double r, const std::uint8_t zoom, const Options &options_) { // The zoom parameter is restricted to [minZoom, maxZoom] by caller assert(((zoom + 1) & 0b11111) == (zoom + 1)); // Since point index is encoded in the upper 27 bits, clamp the count of clusters const auto previous_clusters_size = std::min( previous.clusters.size(), static_cast<std::vector<Cluster>::size_type>(0x7ffffff)); for (std::size_t i = 0; i < previous_clusters_size; i++) { auto &p = previous.clusters[i]; if (p.visited) { continue; } p.visited = true; auto num_points = p.num_points; point<double> weight = p.pos * double(num_points); auto clusterProperties = p.properties ? *p.properties : property_map{}; std::uint32_t id = static_cast<std::uint32_t>((i << 5) + (zoom + 1)); // find all nearby points previous.tree.within(p.pos.x, p.pos.y, r, [&](const auto &neighbor_id) { assert(neighbor_id < previous.clusters.size()); auto &b = previous.clusters[neighbor_id]; // filter out neighbors that are already processed if (b.visited) { return; } b.visited = true; b.parent_id = id; // accumulate coordinates for calculating weighted center weight += b.pos * double(b.num_points); num_points += b.num_points; if (options_.reduce && b.properties) { // apply reduce function to update clusterProperites options_.reduce(clusterProperties, *b.properties); } }); if (num_points == 1) { clusters.emplace_back(weight, 1, p.id, clusterProperties); } else { p.parent_id = id; clusters.emplace_back(weight / double(num_points), num_points, id, clusterProperties); } } tree.fill(clusters); } }; std::unordered_map<std::uint8_t, Zoom> zooms; std::uint8_t limitZoom(const std::uint8_t z) const { if (z < options.minZoom) return options.minZoom; if (z > options.maxZoom + 1) return options.maxZoom + 1; return z; } template <typename TVisitor> void eachChild(const std::uint32_t cluster_id, const TVisitor &visitor) const { const auto origin_id = cluster_id >> 5; const auto origin_zoom = cluster_id % 32; const auto zoom_iter = zooms.find(origin_zoom); if (zoom_iter == zooms.end()) { throw std::runtime_error("No cluster with the specified id."); } auto &zoom = zoom_iter->second; if (origin_id >= zoom.clusters.size()) { throw std::runtime_error("No cluster with the specified id."); } const double r = options.radius / (double(options.extent) * std::pow(2, origin_zoom - 1)); const auto &origin = zoom.clusters[origin_id]; bool hasChildren = false; zoom.tree.within(origin.pos.x, origin.pos.y, r, [&](const auto &id) { assert(id < zoom.clusters.size()); const auto &cluster_child = zoom.clusters[id]; if (cluster_child.parent_id == cluster_id) { visitor(cluster_child); hasChildren = true; } }); if (!hasChildren) { throw std::runtime_error("No cluster with the specified id."); } } template <typename TVisitor> void eachLeaf(const std::uint32_t cluster_id, std::uint32_t &limit, const std::uint32_t offset, std::uint32_t &skipped, const TVisitor &visitor) const { eachChild(cluster_id, [&, this](const auto &cluster_leaf) { if (limit == 0) return; if (cluster_leaf.num_points > 1) { if (skipped + cluster_leaf.num_points <= offset) { // skip the whole cluster skipped += cluster_leaf.num_points; } else { // enter the cluster this->eachLeaf(cluster_leaf.id, limit, offset, skipped, visitor); // exit the cluster } } else if (skipped < offset) { // skip a single point skipped++; } else { // visit a single point visitor(cluster_leaf); limit--; } }); } GeoJSONFeature clusterToGeoJSON(const Cluster &c) const { return c.num_points == 1 ? features[c.id] : c.toGeoJSON(); } static point<double> project(const GeoJSONPoint &p) { const auto lngX = p.x / 360 + 0.5; const double sine = std::sin(p.y * M_PI / 180); const double y = 0.5 - 0.25 * std::log((1 + sine) / (1 - sine)) / M_PI; const auto latY = std::min(std::max(y, 0.0), 1.0); return { lngX, latY }; } }; } // namespace supercluster } // namespace mapbox
33.654762
99
0.549982
[ "geometry", "object", "vector" ]
84b073d9f949a8807ebd04073015b71a68f840e9
1,171
cpp
C++
src/string-compression.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/string-compression.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/string-compression.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: string int2str(int x) { string ans; while (x != 0) { ans = char(x%10 + '0') + ans; x /= 10; } return ans; } int compress(vector<char>& chars) { vector<char> ansc; vector<int> ansi; int ch = chars[0]; int num = 1; for (int i=1;i <chars.size(); ++i) { if (chars[i] != ch) { ansc.push_back(ch); ansi.push_back(num); ch = chars[i]; num = 1; } else { ++num; } } ansc.push_back(ch); ansi.push_back(num); vector<char> chars_ans; for (int i=0; i<ansc.size(); ++i) { if (ansi[i] == 1) chars_ans.push_back(ansc[i]); else { chars_ans.push_back(ansc[i]); string tmp = int2str(ansi[i]); for (int j=0; j<tmp.size(); ++j) chars_ans.push_back(tmp[j]); } } chars = chars_ans; return chars_ans.size(); } }; int main () { Solution sol; vector<char> in = {'a', 'a', 'b', 'b', 'b','c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c','c'}; cout << sol.compress(in); for (auto i:in) cout << i << ' '; cout<< endl; return 0; }
22.09434
119
0.502989
[ "vector" ]
84b2b6dfb401e961e77eb9c23ea8eb90251d53f3
35,862
cpp
C++
src/bkMath/fft/fft.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
4
2018-12-08T15:35:38.000Z
2021-08-06T03:23:06.000Z
src/bkMath/fft/fft.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
src/bkMath/fft/fft.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
/* * This FFT implementation is based on the one by Paul Bourke, which was * published in 1993 and can be freely used. * * http://paulbourke.net/miscellaneous/dft/ * http://paulbourke.net/miscellaneous/ * * "The contents of this web site are © Copyright Paul Bourke or a third party * contributor where indicated. You may print or save an electronic copy of * parts of this web site for your own personal use. Permission must be sought * for any other use. Any source code found here may be freely used provided * credits are given to the author. Purchase of credit free licenses of material * found on this site can be negotiated with the author. The author can also * quote for unique variations and/or higher resolution versions of the images * found on this site." * * ----------------------------------------------------- * * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * 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 <bkMath/fft/fft.h> #include <array> #include <cmath> #include <utility> namespace bk { //==================================================================================================== //===== HELPERS //==================================================================================================== namespace details { bool power_of_2(unsigned int N, unsigned int& exponent_of_two, unsigned int& two_pow_exponent) { exponent_of_two = 0; two_pow_exponent = 1; while (two_pow_exponent < N) { ++exponent_of_two; two_pow_exponent <<= 1; } return two_pow_exponent == N; } bool is_power_of_2(unsigned int N) { unsigned int exponent_of_two = 0; unsigned int two_pow_exponent = 0; return power_of_2(N, exponent_of_two, two_pow_exponent); } /* * - inplace complex-to-complex FFT * - dir = 1 -> forward * - dir = -1 -> backward * - 2^m points required */ void inplace_FFT(int dir, unsigned int exponent_of_two, double* x, double* y, bool normalization) { const unsigned int nn = 1 << exponent_of_two; const unsigned int i2 = nn >> 1; unsigned int j = 0; for (unsigned int i = 0; i < nn - 1; ++i) { if (i < j) { std::swap(x[i], x[j]); std::swap(y[i], y[j]); } unsigned int k = i2; for (; k <= j; k >>= 1) { j -= k; } j += k; } double c1 = -1.0; double c2 = 0.0; unsigned int l2 = 1; for (unsigned int l = 0; l < exponent_of_two; ++l) { const unsigned int l1 = l2; l2 <<= 1; double u1 = 1.0; double u2 = 0.0; for (j = 0; j < l1; ++j) { for (unsigned int i = j; i < nn; i += l2) { const unsigned int i1 = i + l1; const double t1 = u1 * x[i1] - u2 * y[i1]; const double t2 = u1 * y[i1] + u2 * x[i1]; x[i1] = x[i] - t1; y[i1] = y[i] - t2; x[i] += t1; y[i] += t2; } const double z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = -dir * std::sqrt(0.5 * (1.0 - c1)); c1 = std::sqrt(0.5 * (1.0 + c1)); } if (normalization && dir == 1) { for (int i = 0; i < static_cast<int>(nn); ++i) { x[i] /= nn; y[i] /= nn; } } } void inplace_FFT(int dir, unsigned int exponent_of_two, std::complex<double>* c, bool normalization) { const unsigned int nn = 1 << exponent_of_two; const unsigned int i2 = nn >> 1; unsigned int j = 0; for (unsigned int i = 0; i < nn - 1; ++i) { if (i < j) { std::swap(c[i], c[j]); } unsigned int k = i2; for (; k <= j; k >>= 1) { j -= k; } j += k; } double c1 = -1.0; double c2 = 0.0; unsigned int l2 = 1; for (unsigned int l = 0; l < exponent_of_two; ++l) { const unsigned int l1 = l2; l2 <<= 1; double u1 = 1.0; double u2 = 0.0; for (j = 0; j < l1; ++j) { for (unsigned int i = j; i < nn; i += l2) { const unsigned int i1 = i + l1; const double t1 = u1 * c[i1].real() - u2 * c[i1].imag(); const double t2 = u1 * c[i1].imag() + u2 * c[i1].real(); c[i1].real(c[i].real() - t1); c[i1].imag(c[i].imag() - t2); c[i].real(c[i].real() + t1); c[i].imag(c[i].imag() + t2); } const double z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = -dir * std::sqrt(0.5 * (1.0 - c1)); c1 = std::sqrt(0.5 * (1.0 + c1)); } if (normalization && dir == 1) { for (int i = 0; i < static_cast<int>(nn); ++i) { c[i].real(c[i].real() / nn); c[i].imag(c[i].imag() / nn); } } } } // namespace details //==================================================================================================== //===== 1D //==================================================================================================== namespace details { bool FFT1D(std::complex<double>* c, unsigned int size, int dir, bool normalization) { unsigned int two_pow_exponent = 0; unsigned int exponent_of_two = 0; if (!details::power_of_2(size, exponent_of_two, two_pow_exponent) || two_pow_exponent != size) { return false; } details::inplace_FFT(dir, exponent_of_two, c, normalization); return true; } } // namespace details bool FFT1D(std::complex<double>* c, unsigned int size, bool normalization) { return details::FFT1D(c, size, 1, normalization); } bool IFFT1D(std::complex<double>* c, unsigned int size) { return details::FFT1D(c, size, -1); } //==================================================================================================== //===== 2D //==================================================================================================== namespace details { bool FFT2D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, int dir, bool normalization) { unsigned int two_pow_exponent = 0; unsigned int exponent_of_two_x = 0; if (!details::power_of_2(sizex, exponent_of_two_x, two_pow_exponent) || two_pow_exponent != sizex) { return false; } unsigned int exponent_of_two_y = 0; if (!details::power_of_2(sizey, exponent_of_two_y, two_pow_exponent) || two_pow_exponent != sizey) { return false; } const std::array<unsigned int,2> size{{sizex, sizey}}; /* * transform rows */ #pragma omp parallel for for (int j_ = 0; j_ < static_cast<int>(sizey); ++j_) { const unsigned int j = static_cast<unsigned int>(j_); std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int i = 0; i < sizex; ++i) { const unsigned int lid = grid_to_list_id(size, i, j); real[i] = c[lid].real(); imag[i] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); for (unsigned int i = 0; i < sizex; ++i) { const unsigned int lid = grid_to_list_id(size, i, j); c[lid].real(real[i]); c[lid].imag(imag[i]); } } /* * transform columns */ #pragma omp parallel for for (int i_ = 0; i_ < static_cast<int>(sizex); ++i_) { const unsigned int i = static_cast<unsigned int>(i_); std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int j = 0; j < sizey; ++j) { const unsigned int lid = grid_to_list_id(size, i, j); real[j] = c[lid].real(); imag[j] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); for (unsigned int j = 0; j < sizey; ++j) { const unsigned int lid = grid_to_list_id(size, i, j); c[lid].real(real[j]); c[lid].imag(imag[j]); } } return true; } } // namespace details bool FFT2D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, bool normalization) { return details::FFT2D(c, sizex, sizey, 1, normalization); } bool IFFT2D(std::complex<double>* c, unsigned int sizex, unsigned int sizey) { return details::FFT2D(c, sizex, sizey, -1); } //==================================================================================================== //===== 3D //==================================================================================================== namespace details { bool FFT3D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez, int dir, bool normalization) { unsigned int two_pow_exponent = 0; unsigned int exponent_of_two_x = 0; if (!details::power_of_2(sizex, exponent_of_two_x, two_pow_exponent) || two_pow_exponent != sizex) { return false; } unsigned int exponent_of_two_y = 0; if (!details::power_of_2(sizey, exponent_of_two_y, two_pow_exponent) || two_pow_exponent != sizey) { return false; } unsigned int exponent_of_two_z = 0; if (!details::power_of_2(sizez, exponent_of_two_z, two_pow_exponent) || two_pow_exponent != sizez) { return false; } const std::array<unsigned int,3> size{{sizex, sizey, sizez}}; /* * transform x */ if (sizey >= sizez) { #pragma omp parallel for for (int y_ = 0; y_ < static_cast<int>(sizey); ++y_) { const unsigned int y = static_cast<unsigned int>(y_); std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[x] = c[lid].real(); imag[x] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[x]); c[lid].imag(imag[x]); } } } } else // if (sizez > sizey) { #pragma omp parallel for for (int z_ = 0; z_ < static_cast<int>(sizez); ++z_) { const unsigned int z = static_cast<unsigned int>(z_); std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int y = 0; y < sizey; ++y) { for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[x] = c[lid].real(); imag[x] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[x]); c[lid].imag(imag[x]); } } } } /* * transform y */ if (sizex >= sizez) { #pragma omp parallel for for (int x_ = 0; x_ < static_cast<int>(sizex); ++x_) { const unsigned int x = static_cast<unsigned int>(x_); std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[y] = c[lid].real(); imag[y] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[y]); c[lid].imag(imag[y]); } } } } else // if (sizez > sizex) { #pragma omp parallel for for (int z_ = 0; z_ < static_cast<int>(sizez); ++z_) { const unsigned int z = static_cast<unsigned int>(z_); std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[y] = c[lid].real(); imag[y] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[y]); c[lid].imag(imag[y]); } } } } /* * transform z */ if (sizex >= sizey) { #pragma omp parallel for for (int x_ = 0; x_ < static_cast<int>(sizex); ++x_) { const unsigned int x = static_cast<unsigned int>(x_); std::vector<double> real(sizez); std::vector<double> imag(sizez); for (unsigned int y = 0; y < sizey; ++y) { for (unsigned int z = 0; z < sizez; ++z) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[z] = c[lid].real(); imag[z] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_z, real.data(), imag.data(), normalization); for (unsigned int z = 0; z < sizez; ++z) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[z]); c[lid].imag(imag[z]); } } } } else // if (sizey > sizex) { #pragma omp parallel for for (int y_ = 0; y_ < static_cast<int>(sizey); ++y_) { const unsigned int y = static_cast<unsigned int>(y_); std::vector<double> real(sizez); std::vector<double> imag(sizez); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int z = 0; z < sizez; ++z) { const unsigned int lid = grid_to_list_id(size, x, y, z); real[z] = c[lid].real(); imag[z] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_z, real.data(), imag.data(), normalization); for (unsigned int z = 0; z < sizez; ++z) { const unsigned int lid = grid_to_list_id(size, x, y, z); c[lid].real(real[z]); c[lid].imag(imag[z]); } } } } return true; } } // namespace details bool FFT3D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez, bool normalization) { return details::FFT3D(c, sizex, sizey, sizez, 1, normalization); } bool IFFT3D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez) { return details::FFT3D(c, sizex, sizey, sizez, -1); } //==================================================================================================== //===== 4D //==================================================================================================== namespace details { bool FFT4D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez, unsigned int sizet, int dir, bool normalization) { unsigned int two_pow_exponent = 0; unsigned int exponent_of_two_x = 0; if (!details::power_of_2(sizex, exponent_of_two_x, two_pow_exponent) || two_pow_exponent != sizex) { return false; } unsigned int exponent_of_two_y = 0; if (!details::power_of_2(sizey, exponent_of_two_y, two_pow_exponent) || two_pow_exponent != sizey) { return false; } unsigned int exponent_of_two_z = 0; if (!details::power_of_2(sizez, exponent_of_two_z, two_pow_exponent) || two_pow_exponent != sizez) { return false; } unsigned int exponent_of_two_t = 0; if (!details::power_of_2(sizet, exponent_of_two_t, two_pow_exponent) || two_pow_exponent != sizet) { return false; } const std::array<unsigned int,4> size{{sizex, sizey, sizez, sizet}}; const unsigned int stride_x = stride_of_dim(size, 0, 4); const unsigned int stride_y = stride_of_dim(size, 1, 4); const unsigned int stride_z = stride_of_dim(size, 2, 4); const unsigned int stride_t = stride_of_dim(size, 3, 4); /* * transform x */ if (sizey >= sizez && sizey >= sizet) { #pragma omp parallel for for (int y = 0; y < static_cast<int>(sizey); ++y) { std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int t = 0; t < sizet; ++t) { const unsigned int lid0 = grid_to_list_id(size, 0, y, z, t); unsigned int lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { real[x] = c[lid].real(); imag[x] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { c[lid].real(real[x]); c[lid].imag(imag[x]); } } } } } else if (sizez >= sizey && sizez >= sizet) { #pragma omp parallel for for (int z = 0; z < static_cast<int>(sizez); ++z) { std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int t = 0; t < sizet; ++t) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, 0, y, z, t); unsigned int lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { real[x] = c[lid].real(); imag[x] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { c[lid].real(real[x]); c[lid].imag(imag[x]); } } } } } else if (sizet >= sizey && sizet >= sizez) { #pragma omp parallel for for (int t = 0; t < static_cast<int>(sizet); ++t) { std::vector<double> real(sizex); std::vector<double> imag(sizex); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, 0, y, z, t); unsigned int lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { real[x] = c[lid].real(); imag[x] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_x, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int x = 0; x < sizex; ++x, lid += stride_x) { c[lid].real(real[x]); c[lid].imag(imag[x]); } } } } } /* * transform y */ if (sizex >= sizez && sizex >= sizet) { #pragma omp parallel for for (int x = 0; x < static_cast<int>(sizex); ++x) { std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int t = 0; t < sizet; ++t) { const unsigned int lid0 = grid_to_list_id(size, x, 0, z, t); unsigned int lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { real[y] = c[lid].real(); imag[y] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { c[lid].real(real[y]); c[lid].imag(imag[y]); } } } } } else if (sizez >= sizex && sizez >= sizet) { #pragma omp parallel for for (int z = 0; z < static_cast<int>(sizez); ++z) { std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int t = 0; t < sizet; ++t) { for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid0 = grid_to_list_id(size, x, 0, z, t); unsigned int lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { real[y] = c[lid].real(); imag[y] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { c[lid].real(real[y]); c[lid].imag(imag[y]); } } } } } else if (sizet >= sizex && sizet >= sizez) { #pragma omp parallel for for (int t = 0; t < static_cast<int>(sizet); ++t) { std::vector<double> real(sizey); std::vector<double> imag(sizey); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int x = 0; x < sizex; ++x) { const unsigned int lid0 = grid_to_list_id(size, x, 0, z, t); unsigned int lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { real[y] = c[lid].real(); imag[y] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_y, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int y = 0; y < sizey; ++y, lid += stride_y) { c[lid].real(real[y]); c[lid].imag(imag[y]); } } } } } /* * transform z */ if (sizex >= sizey && sizex >= sizet) { #pragma omp parallel for for (int x = 0; x < static_cast<int>(sizex); ++x) { std::vector<double> real(sizez); std::vector<double> imag(sizez); for (unsigned int t = 0; t < sizet; ++t) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, x, y, 0, t); unsigned int lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { real[z] = c[lid].real(); imag[z] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_z, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { c[lid].real(real[z]); c[lid].imag(imag[z]); } } } } } else if (sizey >= sizex && sizey >= sizet) { #pragma omp parallel for for (int y = 0; y < static_cast<int>(sizey); ++y) { std::vector<double> real(sizez); std::vector<double> imag(sizez); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int t = 0; t < sizet; ++t) { const unsigned int lid0 = grid_to_list_id(size, x, y, 0, t); unsigned int lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { real[z] = c[lid].real(); imag[z] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_z, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { c[lid].real(real[z]); c[lid].imag(imag[z]); } } } } } else if (sizet >= sizex && sizet >= sizey) { #pragma omp parallel for for (int t = 0; t < static_cast<int>(sizet); ++t) { std::vector<double> real(sizez); std::vector<double> imag(sizez); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, x, y, 0, t); unsigned int lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { real[z] = c[lid].real(); imag[z] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_z, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int z = 0; z < sizez; ++z, lid += stride_z) { c[lid].real(real[z]); c[lid].imag(imag[z]); } } } } } /* * transform t */ if (sizex >= sizey && sizex >= sizez) { #pragma omp parallel for for (int x = 0; x < static_cast<int>(sizex); ++x) { std::vector<double> real(sizet); std::vector<double> imag(sizet); for (unsigned int z = 0; z < sizez; ++z) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, x, y, z, 0); unsigned int lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { real[t] = c[lid].real(); imag[t] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_t, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { c[lid].real(real[t]); c[lid].imag(imag[t]); } } } } } else if (sizey >= sizex && sizey >= sizez) { #pragma omp parallel for for (int y = 0; y < static_cast<int>(sizey); ++y) { std::vector<double> real(sizet); std::vector<double> imag(sizet); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int z = 0; z < sizez; ++z) { const unsigned int lid0 = grid_to_list_id(size, x, y, z, 0); unsigned int lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { real[t] = c[lid].real(); imag[t] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_t, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { c[lid].real(real[t]); c[lid].imag(imag[t]); } } } } } else if (sizez >= sizex && sizez >= sizey) { #pragma omp parallel for for (int z = 0; z < static_cast<int>(sizez); ++z) { std::vector<double> real(sizet); std::vector<double> imag(sizet); for (unsigned int x = 0; x < sizex; ++x) { for (unsigned int y = 0; y < sizey; ++y) { const unsigned int lid0 = grid_to_list_id(size, x, y, z, 0); unsigned int lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { real[t] = c[lid].real(); imag[t] = c[lid].imag(); } details::inplace_FFT(dir, exponent_of_two_t, real.data(), imag.data(), normalization); lid = lid0; for (unsigned int t = 0; t < sizet; ++t, lid += stride_t) { c[lid].real(real[t]); c[lid].imag(imag[t]); } } } } } return true; } } // namespace details bool FFT4D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez, unsigned int sizet, bool normalization) { return details::FFT4D(c, sizex, sizey, sizez, sizet, 1, normalization); } bool IFFT4D(std::complex<double>* c, unsigned int sizex, unsigned int sizey, unsigned int sizez, unsigned int sizet) { return details::FFT4D(c, sizex, sizey, sizez, sizet, -1); } } // namespace bk
35.933868
148
0.410908
[ "vector", "transform", "3d" ]
84b33e41e23b05c32d47da2893d2d92e9972b460
43,367
cpp
C++
src/drivers/Aura4/Aura4.cpp
jarilq/aura-core
7880ed265396bf8c89b783835853328e6d7d1589
[ "MIT", "BSD-2-Clause-FreeBSD" ]
1
2020-04-04T23:49:36.000Z
2020-04-04T23:49:36.000Z
src/drivers/Aura4/Aura4.cpp
jarilq/aura-core
7880ed265396bf8c89b783835853328e6d7d1589
[ "MIT", "BSD-2-Clause-FreeBSD" ]
null
null
null
src/drivers/Aura4/Aura4.cpp
jarilq/aura-core
7880ed265396bf8c89b783835853328e6d7d1589
[ "MIT", "BSD-2-Clause-FreeBSD" ]
null
null
null
// // FILE: Aura4.cpp // DESCRIPTION: interact with Aura4 FMU // // TODO: // - (for now ok) straighten out what I'm doing with imu timestamp dance // - (for now ok) straighten out what I'm doing with skipped frames // - (for now ok) gps age? // - (ok) send ekf config // - (ok) figure out how to deal with accel/mag calibration if ekf is remote // - (ok) parse ekf packet // - (ok) write actuators // - (ok--for now) deal with how to arbitrate output path enumeration in property tree // - (ok) need to log cal and nocal imu values #include <pyprops.h> #include <stdarg.h> #include <stdlib.h> // exit() #include <string> #include <sstream> using std::string; using std::ostringstream; #include "comms/display.h" #include "init/globals.h" #include "util/props_helper.h" #include "util/timing.h" #include "Aura4.h" void Aura4_t::info( const char *format, ... ) { if ( display_on ) { printf("Aura4: "); va_list args; va_start(args, format); vprintf(format, args); va_end(args); printf("\n"); } } void Aura4_t::hard_fail( const char *format, ... ) { printf("Aura4 hard error: "); va_list args; va_start(args, format); vprintf(format, args); va_end(args); printf("\n"); printf("Cannot continue."); exit(-1); } void Aura4_t::init( pyPropertyNode *config ) { // bind main property nodes aura4_node = pyGetNode("/sensors/Aura4", true); power_node = pyGetNode("/sensors/power", true); status_node = pyGetNode("/status", true); aura4_config = *config; if ( true ) { // fixme: move or delete printf("warning the next code needs to be fixed!!!\n"); if ( config->hasChild("pitot_calibrate_factor") ) { pitot_calibrate = aura4_config.getDouble("pitot_calibrate_factor"); } pyPropertyNode specs_node = pyGetNode("/config/specs", true); if ( specs_node.hasChild("battery_cells") ) { battery_cells = specs_node.getLong("battery_cells"); } if ( battery_cells < 1 ) { battery_cells = 1; } } if ( config->hasChild("board") ) { pyPropertyNode board_config = config->getChild("board"); open( &board_config ); } else { hard_fail("no board defined\n"); } if ( config->hasChild("airdata") ) { pyPropertyNode airdata_config = config->getChild("airdata"); init_airdata( &airdata_config ); } else { hard_fail("no airdata configuration\n"); } if ( config->hasChild("ekf") ) { pyPropertyNode ekf_config = config->getChild("ekf"); init_ekf( &ekf_config ); } else { hard_fail("no ekf configuration\n"); } if ( config->hasChild("gps") ) { pyPropertyNode gps_config = config->getChild("gps"); init_gps( &gps_config ); } else { hard_fail("no gps configuration\n"); } if ( config->hasChild("imu") ) { pyPropertyNode imu_config = config->getChild("imu"); init_imu( &imu_config ); } else { hard_fail("no imu configuration\n"); } if ( config->hasChild("pilot_input") ) { pyPropertyNode pilot_config = config->getChild("pilot_input"); init_pilot( &pilot_config ); } else { hard_fail("no pilot configuration\n"); } // fixme: should we have a config section to trigger this init_actuators(NULL); sleep(1); } bool Aura4_t::open( pyPropertyNode *config ) { if ( config->hasChild("device") ) { device_name = config->getString("device"); } if ( config->hasChild("baud") ) { baud = config->getLong("baud"); } if ( serial.is_open() ) { info("device already open"); return true; } else { info("device on %s @ %d baud", device_name.c_str(), baud); } bool result = serial.open( baud, device_name.c_str() ); if ( !result ) { hard_fail("Error opening serial link to Aura4 device"); } return true; } void Aura4_t::init_airdata( pyPropertyNode *config ) { string output_path = get_next_path("/sensors", "airdata", true); airdata_node = pyGetNode(output_path.c_str(), true); } void Aura4_t::init_ekf( pyPropertyNode *config ) { if ( config->hasChild("select") ) { string val = config->getString("select"); if ( val == "nav15" or val == "nav15_mag" ) { string output_path = get_next_path("/filters", "filter", true); ekf_node = pyGetNode(output_path.c_str(), true); } else if ( val == "none" ) { ekf_node = aura4_node.getChild("aura4_ekf_disabled", true); } else { hard_fail("bad nav/ekf selection: %s", val.c_str()); } } else { ekf_node = aura4_node.getChild("aura4_ekf_disabled", true); } } void Aura4_t::init_gps( pyPropertyNode *config ) { string output_path = get_next_path("/sensors", "gps", true); gps_node = pyGetNode(output_path.c_str(), true); } void Aura4_t::init_imu( pyPropertyNode *config ) { string output_path = get_next_path("/sensors", "imu", true); imu_node = pyGetNode(output_path.c_str(), true); if ( config->hasChild("calibration") ) { pyPropertyNode cal = config->getChild("calibration"); // save the imu calibration parameters with the data file so that // later the original raw sensor values can be derived. write_imu_calibration( &cal ); } } void Aura4_t::init_pilot( pyPropertyNode *config ) { string output_path = get_next_path("/sensors", "pilot_input", true); pilot_node = pyGetNode(output_path.c_str(), true); if ( config->hasChild("channel") ) { for ( int i = 0; i < message::sbus_channels; i++ ) { pilot_mapping[i] = config->getString("channel", i); printf("pilot input: channel %d maps to %s\n", i, pilot_mapping[i].c_str()); } } pilot_node.setLen("channel", message::sbus_channels, 0.0); } void Aura4_t::init_actuators( pyPropertyNode *config ) { act_node = pyGetNode("/actuators", true); } bool Aura4_t::update_imu( message::imu_t *imu ) { imu_timestamp = get_Time(); // pulled from aura-sensors/src/imu.cpp const float _pi = 3.14159265358979323846; const float _g = 9.807; const float _d2r = _pi / 180.0; // -500 to +500 spread across 65535 const float _gyro_lsb_per_dps = 32767.5 / 500; const float gyroScale = _d2r / _gyro_lsb_per_dps; // -4g to +4g spread across 65535 const float _accel_lsb_per_dps = 32767.5 / 8; const float accelScale = _g / _accel_lsb_per_dps; const float magScale = 0.01; const float tempScale = 0.01; float ax_nocal = (float)imu->nocal[0] * accelScale; float ay_nocal = (float)imu->nocal[1] * accelScale; float az_nocal = (float)imu->nocal[2] * accelScale; float hx_nocal = (float)imu->nocal[3] * magScale; float hy_nocal = (float)imu->nocal[4] * magScale; float hz_nocal = (float)imu->nocal[5] * magScale; float ax_cal = (float)imu->cal[0] * accelScale; float ay_cal = (float)imu->cal[1] * accelScale; float az_cal = (float)imu->cal[2] * accelScale; float p_cal = (float)imu->cal[3] * gyroScale; float q_cal = (float)imu->cal[4] * gyroScale; float r_cal = (float)imu->cal[5] * gyroScale; float hx_cal = (float)imu->cal[6] * magScale; float hy_cal = (float)imu->cal[7] * magScale; float hz_cal = (float)imu->cal[8] * magScale; float temp_C = (float)imu->cal[9] * tempScale; // timestamp dance: this is a little jig that I do to make a // more consistent time stamp that still is in the host // reference frame. Assumes the Aura4 clock drifts relative to // host clock. Assumes the Aura4 imu stamp dt is very stable. // Assumes the host system is not-real time and there may be // momentary external disruptions to execution. The code // estimates the error (difference) between Aura4 clock and // host clock. Then builds a real time linear fit of Aura4 // clock versus difference with the host. This linear fit is // used to estimate the current error (smoothly), add that to // the Aura4 clock and derive a more regular/stable IMU time // stamp (versus just sampling current host time.) // imu->micros &= 0xffffff; // 24 bits = 16.7 microseconds roll over // imu->micros &= 0xffffff; // 24 bits = 16.7 microseconds roll over double imu_remote_sec = (double)imu->millis / 1000.0; double diff = imu_timestamp - imu_remote_sec; if ( last_imu_millis > imu->millis ) { events->log("Aura4", "millis() rolled over\n"); imu_offset.reset(); } imu_offset.update(imu_remote_sec, diff); double fit_diff = imu_offset.get_value(imu_remote_sec); // printf("fit_diff = %.6f diff = %.6f ts = %.6f\n", // fit_diff, diff, imu_remote_sec + fit_diff ); last_imu_millis = imu->millis; imu_node.setDouble( "timestamp", imu_remote_sec + fit_diff ); imu_node.setLong( "imu_millis", imu->millis ); imu_node.setDouble( "imu_sec", (double)imu->millis / 1000.0 ); imu_node.setDouble( "p_rad_sec", p_cal ); imu_node.setDouble( "q_rad_sec", q_cal ); imu_node.setDouble( "r_rad_sec", r_cal ); imu_node.setDouble( "ax_mps_sec", ax_cal ); imu_node.setDouble( "ay_mps_sec", ay_cal ); imu_node.setDouble( "az_mps_sec", az_cal ); imu_node.setDouble( "hx", hx_cal ); imu_node.setDouble( "hy", hy_cal ); imu_node.setDouble( "hz", hz_cal ); imu_node.setDouble( "ax_nocal", ax_nocal ); imu_node.setDouble( "ay_nocal", ay_nocal ); imu_node.setDouble( "az_nocal", az_nocal ); imu_node.setDouble( "hx_nocal", hx_nocal ); imu_node.setDouble( "hy_nocal", hy_nocal ); imu_node.setDouble( "hz_nocal", hz_nocal ); imu_node.setDouble( "temp_C", temp_C ); return true; } bool Aura4_t::parse( uint8_t pkt_id, uint8_t pkt_len, uint8_t *payload ) { bool new_data = false; if ( pkt_id == message::command_ack_id ) { message::command_ack_t ack; ack.unpack(payload, pkt_len); if ( pkt_len == ack.len ) { last_ack_id = ack.command_id; last_ack_subid = ack.subcommand_id; info("Received ACK = %d %d", ack.command_id, ack.subcommand_id); } else { printf("Aura4: packet size mismatch in ACK\n"); } } else if ( pkt_id == message::airdata_id ) { message::airdata_t airdata; airdata.unpack(payload, pkt_len); if ( pkt_len == airdata.len ) { update_airdata(&airdata); airdata_packet_counter++; aura4_node.setLong( "airdata_packet_count", airdata_packet_counter ); new_data = true; } else { info("packet size mismatch in airdata packet"); } } else if ( pkt_id == message::ekf_id ) { message::ekf_t ekf; ekf.unpack(payload, pkt_len); if ( pkt_len == ekf.len ) { update_ekf(&ekf); ekf_packet_counter++; aura4_node.setLong( "ekf_packet_count", ekf_packet_counter ); new_data = true; } else { info("packet size mismatch in ekf packet"); } } else if ( pkt_id == message::aura_nav_pvt_id ) { message::aura_nav_pvt_t nav_pvt; nav_pvt.unpack(payload, pkt_len); if ( pkt_len == nav_pvt.len ) { update_gps(&nav_pvt); gps_packet_counter++; aura4_node.setLong( "gps_packet_count", gps_packet_counter ); new_data = true; } else { info("packet size mismatch in gps packet"); info("got %d, expected %d", pkt_len, nav_pvt.len); } } else if ( pkt_id == message::imu_id ) { message::imu_t imu; imu.unpack(payload, pkt_len); if ( pkt_len == imu.len ) { update_imu(&imu); imu_packet_counter++; aura4_node.setLong( "imu_packet_count", imu_packet_counter ); new_data = true; } else { info("packet size mismatch in imu packet"); } } else if ( pkt_id == message::pilot_id ) { message::pilot_t pilot; pilot.unpack(payload, pkt_len); if ( pkt_len == pilot.len ) { update_pilot( &pilot ); pilot_packet_counter++; aura4_node.setLong( "pilot_packet_count", pilot_packet_counter ); new_data = true; } else { info("packet size mismatch in pilot input packet"); } } else if ( pkt_id == message::power_id ) { message::power_t power; power.unpack(payload, pkt_len); if ( pkt_len == power.len ) { // we anticipate a 0.01 sec dt value int_main_vcc_filt.update((float)power.int_main_v, 0.01); ext_main_vcc_filt.update((float)power.ext_main_v, 0.01); avionics_vcc_filt.update((float)power.avionics_v, 0.01); power_node.setDouble( "main_vcc", int_main_vcc_filt.get_value() ); power_node.setDouble( "ext_main_vcc", ext_main_vcc_filt.get_value() ); power_node.setDouble( "avionics_vcc", avionics_vcc_filt.get_value() ); float cell_volt = int_main_vcc_filt.get_value() / (float)battery_cells; float ext_cell_volt = ext_main_vcc_filt.get_value() / (float)battery_cells; power_node.setDouble( "cell_vcc", cell_volt ); power_node.setDouble( "ext_cell_vcc", ext_cell_volt ); power_node.setDouble( "main_amps", (float)power.ext_main_amp); } else { info("packet size mismatch in power packet"); } } else if ( pkt_id == message::status_id ) { message::status_t msg; msg.unpack(payload, pkt_len); if ( pkt_len == msg.len ) { aura4_node.setLong( "serial_number", msg.serial_number ); aura4_node.setLong( "firmware_rev", msg.firmware_rev ); aura4_node.setLong( "master_hz", msg.master_hz ); aura4_node.setLong( "baud_rate", msg.baud ); aura4_node.setLong( "byte_rate_sec", msg.byte_rate ); status_node.setLong( "fmu_timer_misses", msg.timer_misses ); if ( first_status_message ) { // log the data to events.txt first_status_message = false; char buf[128]; snprintf( buf, 32, "Serial Number = %d", msg.serial_number ); events->log("Aura4", buf ); snprintf( buf, 32, "Firmware Revision = %d", msg.firmware_rev ); events->log("Aura4", buf ); snprintf( buf, 32, "Master Hz = %d", msg.master_hz ); events->log("Aura4", buf ); snprintf( buf, 32, "Baud Rate = %d", msg.baud ); events->log("Aura4", buf ); } } else { info("packet size mismatch in status packet"); } } else { info("unknown packet id = %d", pkt_id); } return new_data; } bool Aura4_t::wait_for_ack(uint8_t id) { double timeout = 0.5; double start_time = get_Time(); last_ack_id = 0; while ( (last_ack_id != id) ) { if ( serial.update() ) { parse( serial.pkt_id, serial.pkt_len, serial.payload ); } if ( get_Time() > start_time + timeout ) { info("timeout waiting for ack..."); return false; } } return true; } bool Aura4_t::write_config_message(int id, uint8_t *payload, int len) { serial.write_packet( id, payload, len ); return wait_for_ack(id); } bool Aura4_t::write_command_zero_gyros() { message::command_zero_gyros_t cmd; cmd.pack(); serial.write_packet( cmd.id, cmd.payload, cmd.len ); return wait_for_ack(cmd.id); } bool Aura4_t::write_command_reset_ekf() { message::command_reset_ekf_t cmd; cmd.pack(); serial.write_packet( cmd.id, cmd.payload, cmd.len ); return wait_for_ack(cmd.id); } bool Aura4_t::write_command_cycle_inceptors() { message::command_cycle_inceptors_t cmd; cmd.pack(); serial.write_packet( cmd.id, cmd.payload, cmd.len ); return wait_for_ack(cmd.id); } // reset airdata to startup defaults static void airdata_defaults( message::config_airdata_t *config_airdata ) { config_airdata->barometer = 0; config_airdata->pitot = 0; config_airdata->swift_baro_addr = 0; config_airdata->swift_pitot_addr = 0; } // master board selector defaults static void board_defaults( message::config_board_t *config_board ) { config_board->board = 0; config_board->led_pin = 0; } // ekf defaults static void ekf_defaults( message::config_ekf_t *config_ekf ) { config_ekf->select = message::enum_nav::none; config_ekf->sig_w_accel = 0.05; config_ekf->sig_w_gyro = 0.00175; config_ekf->sig_a_d = 0.01; config_ekf->tau_a = 100.0; config_ekf->sig_g_d = 0.00025; config_ekf->tau_g = 50.0; config_ekf->sig_gps_p_ne = 3.0; config_ekf->sig_gps_p_d = 6.0; config_ekf->sig_gps_v_ne = 1.0; config_ekf->sig_gps_v_d = 3.0; config_ekf->sig_mag = 0.3; } // Setup imu defaults: // Marmot v1 has mpu9250 on SPI CS line 24 // Aura v2 has mpu9250 on I2C Addr 0x68 static void imu_defaults( message::config_imu_t *config_imu ) { config_imu->interface = 0; // SPI config_imu->pin_or_address = 24; // CS pin float ident[] = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; for ( int i = 0; i < 9; i++ ) { config_imu->orientation[i] = ident[i]; } config_imu->min_temp = 27.0; config_imu->max_temp = 27.0; for ( int i = 0; i < 3; i++ ) { config_imu->ax_coeff[i] = 0.0; } float mag_affine[] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; for ( int i = 0; i < 16; i++ ) { config_imu->mag_affine[i] = mag_affine[i]; } } // reset pwm output rates to safe startup defaults static void pwm_defaults( message::config_pwm_t *config_pwm ) { for ( int i = 0; i < message::pwm_channels; i++ ) { config_pwm->pwm_hz = 50; config_pwm->act_gain[i] = 1.0; } } // reset mixing parameters to startup defaults static void mixer_defaults( message::config_mixer_t *config_mixer ) { config_mixer->mix_autocoord = false; config_mixer->mix_throttle_trim = false; config_mixer->mix_flap_trim = false; config_mixer->mix_elevon = false; config_mixer->mix_flaperon = false; config_mixer->mix_vtail = false; config_mixer->mix_diff_thrust = false; config_mixer->mix_Gac = 0.5; // aileron gain for autocoordination config_mixer->mix_Get = -0.1; // elevator trim w/ throttle gain config_mixer->mix_Gef = 0.1; // elevator trim w/ flap gain config_mixer->mix_Gea = 1.0; // aileron gain for elevons config_mixer->mix_Gee = 1.0; // elevator gain for elevons config_mixer->mix_Gfa = 1.0; // aileron gain for flaperons config_mixer->mix_Gff = 1.0; // flaps gain for flaperons config_mixer->mix_Gve = 1.0; // elevator gain for vtail config_mixer->mix_Gvr = 1.0; // rudder gain for vtail config_mixer->mix_Gtt = 1.0; // throttle gain for diff thrust config_mixer->mix_Gtr = 0.1; // rudder gain for diff thrust }; static void power_defaults( message::config_power_t *config_power ) { config_power->have_attopilot = false; } // reset sas parameters to startup defaults static void stability_defaults( message::config_stability_damping_t *config_stab ) { config_stab->sas_rollaxis = false; config_stab->sas_pitchaxis = false; config_stab->sas_yawaxis = false; config_stab->sas_tune = false; config_stab->sas_rollgain = 0.0; config_stab->sas_pitchgain = 0.0; config_stab->sas_yawgain = 0.0; config_stab->sas_max_gain = 2.0; }; // send a full configuration to Aura4 and return true only when all // parameters are acknowledged. bool Aura4_t::send_config() { message::config_airdata_t config_airdata; message::config_board_t config_board; message::config_ekf_t config_ekf; message::config_imu_t config_imu; message::config_mixer_t config_mixer; message::config_power_t config_power; message::config_pwm_t config_pwm; message::config_stability_damping_t config_stab; info("building config structure."); vector<string> children; // set all message parameters to defaults airdata_defaults(&config_airdata); board_defaults(&config_board); ekf_defaults(&config_ekf); imu_defaults(&config_imu); pwm_defaults(&config_pwm); mixer_defaults(&config_mixer); power_defaults(&config_power); stability_defaults(&config_stab); int count; pyPropertyNode board_node = aura4_config.getChild("board", true); string name = board_node.getString("name"); if ( name == "marmot_v1" ) { config_board.board = 0; } else if ( name == "aura_v2" ) { config_board.board = 1; } else { printf("Warning: no valid PWM pin layout defined.\n"); } if ( board_node.hasChild("led_pin") ) { config_board.led_pin = board_node.getLong("led_pin"); } pyPropertyNode power_node = aura4_config.getChild("power", true); if ( power_node.hasChild("have_attopilot") ) { config_power.have_attopilot = power_node.getBool("have_attopilot"); } pyPropertyNode imu_node = aura4_config.getChild("imu", true); if ( imu_node.hasChild("orientation") ) { int len = imu_node.getLen("orientation"); if ( len == 9 ) { for ( int i = 0; i < len; i++ ) { config_imu.orientation[i] = imu_node.getDouble("orientation", i); } } else { printf("WARNING: imu orienation improper matrix size\n"); } if ( imu_node.hasChild("calibration") ) { pyPropertyNode cal = imu_node.getChild("calibration"); if ( cal.hasChild("min_temp_C") ) { config_imu.min_temp = cal.getDouble("min_temp_C"); } if ( cal.hasChild("max_temp_C") ) { config_imu.max_temp = cal.getDouble("max_temp_C"); } if ( cal.getLen("ax_calib") == 3 ) { for ( int i = 0; i < 3; i++ ) { config_imu.ax_coeff[i] = cal.getDouble("ax_calib", i); } } if ( cal.getLen("ay_calib") == 3 ) { for ( int i = 0; i < 3; i++ ) { config_imu.ay_coeff[i] = cal.getDouble("ay_calib", i); } } if ( cal.getLen("az_calib") == 3 ) { for ( int i = 0; i < 3; i++ ) { config_imu.az_coeff[i] = cal.getDouble("az_calib", i); } } if ( cal.getLen("mag_affine") == 16 ) { for ( unsigned int i = 0; i < 16; i++ ) { config_imu.mag_affine[i] = cal.getDouble("mag_affine", i); //printf("mag: %.4f\n", config_imu.mag_affine[i]); } } else { info("ERROR: wrong number of elements for mag_cal affine matrix!\n"); } } } else { printf("Note: no imu orientation defined, default is identity matrix\n"); } if ( imu_node.hasChild("interface") ) { string interface = imu_node.getString("interface"); if ( interface == "spi" ) { config_imu.interface = 0; config_imu.pin_or_address = imu_node.getLong("cs_pin"); } else if ( interface == "i2c" ) { config_imu.interface = 1; } else { printf("Warning: unknown IMU interface = %s\n", interface.c_str()); } } pyPropertyNode pwm_node = aura4_config.getChild("pwm", true); config_pwm.pwm_hz = pwm_node.getLong("pwm_hz"); info("pwm_hz = %d", config_pwm.pwm_hz); count = pwm_node.getLen("gains"); for ( int i = 0; i < count; i++ ) { config_pwm.act_gain[i] = pwm_node.getDouble("gains", i); info("act_gain[%d] = %.2f", i, config_pwm.act_gain[i]); } pyPropertyNode mixer_node = aura4_config.getChild("mixer"); count = mixer_node.getLen("mix"); if ( count ) { for ( int i = 0; i < count; i++ ) { string mode = ""; bool enable = false; float gain1 = 0.0; float gain2 = 0.0; pyPropertyNode mix_node = mixer_node.getChild("mix", i, true); if ( mix_node.hasChild("enable") ) { enable = mix_node.getBool("enable"); } if ( mix_node.hasChild("gain1") ) { gain1 = mix_node.getDouble("gain1"); } if ( mix_node.hasChild("gain2") ) { gain2 = mix_node.getDouble("gain2"); } if ( mix_node.hasChild("mode") ) { mode = mix_node.getString("mode"); if ( mode == "auto_coordination" ) { config_mixer.mix_autocoord = enable; config_mixer.mix_Gac = gain1; } else if ( mode == "throttle_trim" ) { config_mixer.mix_throttle_trim = enable; config_mixer.mix_Get = gain1; } else if ( mode == "flap_trim" ) { config_mixer.mix_flap_trim = enable; config_mixer.mix_Gef = gain1; } else if ( mode == "elevon" ) { config_mixer.mix_elevon = enable; config_mixer.mix_Gea = gain1; config_mixer.mix_Gee = gain2; } else if ( mode == "flaperon" ) { config_mixer.mix_flaperon = enable; config_mixer.mix_Gfa = gain1; config_mixer.mix_Gff = gain2; } else if ( mode == "vtail" ) { config_mixer.mix_vtail = enable; config_mixer.mix_Gve = gain1; config_mixer.mix_Gvr = gain2; } else if ( mode == "diff_thrust" ) { config_mixer.mix_diff_thrust = enable; config_mixer.mix_Gtt = gain1; config_mixer.mix_Gtr = gain2; } } info("mix: %s %d %.2f %.2f", mode.c_str(), enable, gain1, gain2); } } pyPropertyNode stab_node = aura4_config.getChild("stability_damper"); children = stab_node.getChildren(false); count = (int)children.size(); for ( int i = 0; i < count; ++i ) { string mode = ""; bool enable = false; float gain = 0.0; if ( children[i] == "axis" ) { for ( int j = 0; j < stab_node.getLen("axis"); j++ ) { pyPropertyNode stab_section = stab_node.getChild("axis", j); if ( stab_section.hasChild("enable") ) { enable = stab_section.getBool("enable"); } if ( stab_section.hasChild("gain") ) { gain = stab_section.getDouble("gain"); } if ( stab_section.hasChild("mode") ) { mode = stab_section.getString("mode"); if ( mode == "roll" ) { config_stab.sas_rollaxis = enable; config_stab.sas_rollgain = gain; } else if ( mode == "pitch" ) { config_stab.sas_pitchaxis = enable; config_stab.sas_pitchgain = gain; } else if ( mode == "yaw" ) { config_stab.sas_yawaxis = enable; config_stab.sas_yawgain = gain; } } info("sas: %s %d %.2f", mode.c_str(), enable, gain); } } else if ( children[i] == "pilot_tune" ) { pyPropertyNode stab_section = stab_node.getChild("pilot_tune"); if ( stab_section.hasChild("enable") ) { config_stab.sas_tune = stab_section.getBool("enable"); } info("sas global tune %d", config_stab.sas_tune); } } pyPropertyNode airdata_node = aura4_config.getChild("airdata"); if ( airdata_node.hasChild("barometer") ) { string baro = airdata_node.getString("barometer"); if ( baro == "bme280" ) { config_airdata.barometer = 0; } else if ( baro == "bmp280" ) { config_airdata.barometer = 1; } else if ( baro == "swift" ) { config_airdata.barometer = 2; config_airdata.swift_baro_addr = airdata_node.getLong("swift_baro_addr"); } } if ( airdata_node.hasChild("pitot") ) { string pitot = airdata_node.getString("pitot"); if ( pitot == "ms4525" ) { config_airdata.pitot = 0; } else if ( pitot == "ms5525" ) { config_airdata.pitot = 1; } else if ( pitot == "swift" ) { config_airdata.pitot = 2; config_airdata.swift_pitot_addr = airdata_node.getLong("swift_pitot_addr"); } } if ( aura4_config.hasChild("ekf") ) { pyPropertyNode ekf_node = aura4_config.getChild("ekf"); if ( ekf_node.hasChild("select") ) { string val = ekf_node.getString("select"); if ( val == "none" ) { config_ekf.select = message::enum_nav::none; info("ekf selected: none"); } else if ( val == "nav15" ) { config_ekf.select = message::enum_nav::nav15; info("ekf selected: nav15"); } else if ( val == "nav15_mag" ) { config_ekf.select = message::enum_nav::nav15_mag; info("ekf selected: nav15_mag"); } else { hard_fail("bad nav/ekf selection: %s", val.c_str()); } } if ( ekf_node.hasChild("sig_w_accel") ) { config_ekf.sig_w_accel = ekf_node.getDouble("sig_w_accel"); } if ( ekf_node.hasChild("sig_w_gyro") ) { config_ekf.sig_w_gyro = ekf_node.getDouble("sig_w_gyro"); } if ( ekf_node.hasChild("sig_a_d") ) { config_ekf.sig_a_d = ekf_node.getDouble("sig_a_d"); } if ( ekf_node.hasChild("tau_a") ) { config_ekf.tau_a = ekf_node.getDouble("tau_a"); } if ( ekf_node.hasChild("sig_g_d") ) { config_ekf.sig_g_d = ekf_node.getDouble("sig_g_d"); } if ( ekf_node.hasChild("tau_g") ) { config_ekf.tau_g = ekf_node.getDouble("tau_g"); } if ( ekf_node.hasChild("sig_gps_p_ne") ) { config_ekf.sig_gps_p_ne = ekf_node.getDouble("sig_gps_p_ne"); } if ( ekf_node.hasChild("sig_gps_p_d") ) { config_ekf.sig_gps_p_d = ekf_node.getDouble("sig_gps_p_d"); } if ( ekf_node.hasChild("sig_gps_v_ne") ) { config_ekf.sig_gps_v_ne = ekf_node.getDouble("sig_gps_v_ne"); } if ( ekf_node.hasChild("sig_gps_v_d") ) { config_ekf.sig_gps_v_d = ekf_node.getDouble("sig_gps_v_d"); } if ( ekf_node.hasChild("sig_mag") ) { config_ekf.sig_mag = ekf_node.getDouble("sig_mag"); } } info("transmitting airdata config ..."); config_airdata.pack(); if ( !write_config_message(config_airdata.id, config_airdata.payload, config_airdata.len ) ) { return false; } info("transmitting board config ..."); config_board.pack(); if ( !write_config_message(config_board.id, config_board.payload, config_board.len) ) { return false; } info("transmitting ekf config ..."); config_ekf.pack(); if ( !write_config_message(config_ekf.id, config_ekf.payload, config_ekf.len) ) { return false; } info("transmitting imu config ..."); config_imu.pack(); if ( !write_config_message(config_imu.id, config_imu.payload, config_imu.len) ) { return false; } info("transmitting mixer config ..."); config_mixer.pack(); if ( !write_config_message(config_mixer.id, config_mixer.payload, config_mixer.len) ) { return false; } info("transmitting power config ..."); config_power.pack(); if ( !write_config_message(config_power.id, config_power.payload, config_power.len) ) { return false; } info("transmitting pwm config ..."); config_pwm.pack(); if ( !write_config_message(config_pwm.id, config_pwm.payload, config_pwm.len) ) { return false; } info("transmitting stability damping config ..."); config_stab.pack(); if ( !write_config_message(config_stab.id, config_stab.payload, config_stab.len) ) { return false; } info("send_config() finished"); return true; } // Read Aura4 packets using IMU packet as the main timing reference. // Returns the dt from the IMU perspective, not the localhost // perspective. This should generally be far more accurate and // consistent. float Aura4_t::read() { // read packets until we receive an IMU packet and the uart buffer // is mostly empty. The IMU packet (combined with being caught up // reading the uart buffer is our signal to run an interation of // the main loop. double last_time = imu_node.getDouble( "timestamp" ); // try sending the configuration if not yet successful if ( !configuration_sent ) { configuration_sent = send_config(); } while ( true ) { if ( serial.update() ) { parse( serial.pkt_id, serial.pkt_len, serial.payload ); if ( serial.pkt_id == message::imu_id ) { if ( serial.bytes_available() < 256 ) { // a smaller value here means more skipping ahead and // less catching up. break; } else { skipped_frames++; } } } } // track communication errors from FMU aura4_node.setLong("parse_errors", parse_errors); aura4_node.setLong("skipped_frames", skipped_frames); // relay optional zero gyros command back to FMU upon request string command = aura4_node.getString( "command" ); if ( command.length() ) { if ( command == "zero_gyros" ) { if ( write_command_zero_gyros() ) { aura4_node.setString( "command", "" ); aura4_node.setString( "command_result", "success: " + command ); } } else if ( command == "reset_ekf" ) { if ( write_command_reset_ekf() ) { aura4_node.setString( "command", "" ); aura4_node.setString( "command_result", "success: " + command ); } } else { // unknown command aura4_node.setString( "command", "" ); aura4_node.setString( "command_result", "unknown command: " + command ); } } double cur_time = imu_node.getDouble( "timestamp" ); float dt = cur_time - last_time; return dt; } bool Aura4_t::update_ekf( message::ekf_t *ekf ) { const double R2D = 180 / M_PI; const double F2M = 0.3048; const double M2F = 1 / F2M; // do a little dance to estimate the ekf timestamp in seconds long int imu_millis = imu_node.getLong("imu_millis"); long int diff_millis = ekf->millis - imu_millis; if ( diff_millis < 0 ) { diff_millis = 0; } // don't puke on wraparound double timestamp = imu_node.getDouble("timestamp") + (float)diff_millis / 1000.0; ekf_node.setDouble( "timestamp", timestamp ); ekf_node.setLong( "ekf_millis", ekf->millis ); ekf_node.setDouble( "latitude_deg", ekf->lat_rad * R2D ); ekf_node.setDouble( "longitude_deg", ekf->lon_rad * R2D ); ekf_node.setDouble( "altitude_m", ekf->altitude_m ); ekf_node.setDouble( "vn_ms", ekf->vn_ms ); ekf_node.setDouble( "ve_ms", ekf->ve_ms ); ekf_node.setDouble( "vd_ms", ekf->vd_ms ); ekf_node.setDouble( "phi_rad", ekf->phi_rad ); ekf_node.setDouble( "the_rad", ekf->the_rad ); ekf_node.setDouble( "psi_rad", ekf->psi_rad ); ekf_node.setDouble( "roll_deg", ekf->phi_rad * R2D ); ekf_node.setDouble( "pitch_deg", ekf->the_rad * R2D ); ekf_node.setDouble( "heading_deg", ekf->psi_rad * R2D ); ekf_node.setDouble( "p_bias", ekf->p_bias ); ekf_node.setDouble( "q_bias", ekf->q_bias ); ekf_node.setDouble( "r_bias", ekf->r_bias ); ekf_node.setDouble( "ax_bias", ekf->ax_bias ); ekf_node.setDouble( "ay_bias", ekf->ay_bias ); ekf_node.setDouble( "az_bias", ekf->az_bias ); ekf_node.setDouble( "max_pos_cov", ekf->max_pos_cov ); ekf_node.setDouble( "max_vel_cov", ekf->max_vel_cov ); ekf_node.setDouble( "max_att_cov", ekf->max_att_cov ); ekf_node.setLong("status", ekf->status ); /*FIXME:move the following to filter_mgr?*/ ekf_node.setDouble( "altitude_ft", ekf->altitude_m * M2F ); ekf_node.setDouble( "groundtrack_deg", 90 - atan2(ekf->vn_ms, ekf->ve_ms) * R2D ); double gs_ms = sqrt(ekf->vn_ms * ekf->vn_ms + ekf->ve_ms * ekf->ve_ms); ekf_node.setDouble( "groundspeed_ms", gs_ms ); ekf_node.setDouble( "groundspeed_kt", gs_ms * SG_MPS_TO_KT ); ekf_node.setDouble( "vertical_speed_fps", -ekf->vd_ms * M2F ); return true; } bool Aura4_t::update_gps( message::aura_nav_pvt_t *nav_pvt ) { gps_node.setDouble( "timestamp", get_Time() ); gps_node.setLong( "year", nav_pvt->year ); gps_node.setLong( "month", nav_pvt->month ); gps_node.setLong( "day", nav_pvt->day ); gps_node.setLong( "hour", nav_pvt->hour ); gps_node.setLong( "min", nav_pvt->min ); gps_node.setLong( "sec", nav_pvt->sec ); gps_node.setDouble( "latitude_deg", nav_pvt->lat / 10000000.0 ); gps_node.setDouble( "longitude_deg", nav_pvt->lon / 10000000.0 ); gps_node.setDouble( "altitude_m", nav_pvt->hMSL / 1000.0 ); gps_node.setDouble( "horiz_accuracy_m", nav_pvt->hAcc / 1000.0 ); gps_node.setDouble( "vert_accuracy_m", nav_pvt->vAcc / 1000.0 ); gps_node.setDouble( "vn_ms", nav_pvt->velN / 1000.0 ); gps_node.setDouble( "ve_ms", nav_pvt->velE / 1000.0 ); gps_node.setDouble( "vd_ms", nav_pvt->velD / 1000.0 ); gps_node.setLong( "satellites", nav_pvt->numSV); gps_node.setDouble( "pdop", nav_pvt->pDOP / 100.0 ); gps_node.setLong( "fixType", nav_pvt->fixType ); // backwards compatibility if ( nav_pvt->fixType == 0 ) { gps_node.setLong( "status", 0 ); } else if ( nav_pvt->fixType == 1 || nav_pvt->fixType == 2 ) { gps_node.setLong( "status", 1 ); } else if ( nav_pvt->fixType == 3 ) { gps_node.setLong( "status", 2 ); } struct tm gps_time; gps_time.tm_sec = nav_pvt->sec; gps_time.tm_min = nav_pvt->min; gps_time.tm_hour = nav_pvt->hour; gps_time.tm_mday = nav_pvt->day; gps_time.tm_mon = nav_pvt->month - 1; gps_time.tm_year = nav_pvt->year - 1900; double unix_sec = (double)mktime( &gps_time ) - timezone; unix_sec += nav_pvt->nano / 1000000000.0; gps_node.setDouble( "unix_time_sec", unix_sec ); return true; } bool Aura4_t::update_airdata( message::airdata_t *airdata ) { bool fresh_data = false; float pitot_butter = pitot_filter.update(airdata->ext_diff_press_pa); if ( ! airspeed_inited ) { if ( airspeed_zero_start_time > 0.0 ) { pitot_sum += airdata->ext_diff_press_pa; pitot_count++; pitot_offset = pitot_sum / (double)pitot_count; /* printf("a1 raw=%.1f filt=%.1f a1 off=%.1f a1 sum=%.1f a1 count=%d\n", analog[0], pitot_filt.get_value(), pitot_offset, pitot_sum, pitot_count); */ } else { airspeed_zero_start_time = get_Time(); pitot_sum = 0.0; pitot_count = 0; } if ( imu_timestamp > airspeed_zero_start_time + 10.0 ) { //printf("pitot_offset = %.2f\n", pitot_offset); airspeed_inited = true; } } airdata_node.setDouble( "timestamp", imu_timestamp ); // basic pressure to airspeed formula: v = sqrt((2/p) * q) // where v = velocity, q = dynamic pressure (pitot tube sensor // value), and p = air density. // if p is specified in kg/m^3 (value = 1.225) and if q is // specified in Pa (N/m^2) where 1 psi == 6900 Pa, then the // velocity will be in meters per second. // The MPXV5004DP has a full scale span of 3.9V, Maximum // pressure reading is 0.57psi (4000Pa) // Example (Aura4): With a 10bit ADC (Aura4) we record a value // of 230 (0-1024) at zero velocity. The sensor saturates at // a value of about 1017 (4000psi). Thus: // Pa = (ADC - 230) * 5.083 // Airspeed(mps) = sqrt( (2/1.225) * Pa ) // This yields a theoretical maximum speed sensor reading of // about 81mps (156 kts) // choose between using raw pitot value or filtered pitot value // float pitot = airdata->diff_pres_pa; float pitot = pitot_butter; float Pa = (pitot - pitot_offset); if ( Pa < 0.0 ) { Pa = 0.0; } // avoid sqrt(neg_number) situation float airspeed_mps = sqrt( 2*Pa / 1.225 ) * pitot_calibrate; float airspeed_kt = airspeed_mps * SG_MPS_TO_KT; airdata_node.setDouble( "airspeed_mps", airspeed_mps ); airdata_node.setDouble( "airspeed_kt", airspeed_kt ); airdata_node.setDouble( "temp_C", airdata->ext_temp_C ); // publish sensor values airdata_node.setDouble( "pressure_mbar", airdata->baro_press_pa / 100.0 ); airdata_node.setDouble( "bme_temp_C", airdata->baro_temp_C ); airdata_node.setDouble( "humidity", airdata->baro_hum ); airdata_node.setDouble( "diff_pressure_pa", airdata->ext_diff_press_pa ); airdata_node.setDouble( "ext_static_press_pa", airdata->ext_static_press_pa ); airdata_node.setLong( "error_count", airdata->error_count ); fresh_data = true; return fresh_data; } // force an airspeed zero calibration (ideally with the aircraft on // the ground with the pitot tube perpendicular to the prevailing // wind.) void Aura4_t::airdata_zero_airspeed() { airspeed_inited = false; airspeed_zero_start_time = 0.0; } bool Aura4_t::update_pilot( message::pilot_t *pilot ) { float val; pilot_node.setDouble( "timestamp", get_Time() ); for ( int i = 0; i < message::sbus_channels; i++ ) { val = pilot->channel[i]; pilot_node.setDouble( pilot_mapping[i].c_str(), val ); pilot_node.setDouble( "channel", i, val ); } // sbus ch17 (channel[16]) if ( pilot->flags & 0x01 ) { pilot_node.setDouble( "channel", 16, 1.0 ); } else { pilot_node.setDouble( "channel", 16, 0.0 ); } // sbus ch18 (channel[17]) if ( pilot->flags & (1 << 1) ) { pilot_node.setDouble( "channel", 17, 1.0 ); } else { pilot_node.setDouble( "channel", 17, 0.0 ); } if ( pilot->flags & (1 << 2) ) { pilot_node.setBool( "frame_lost", true ); } else { pilot_node.setBool( "frame_lost", false ); } if ( pilot->flags & (1 << 3) ) { pilot_node.setBool( "fail_safe", true ); } else { pilot_node.setBool( "fail_safe", false ); } return true; } void Aura4_t::write() { // send actuator commands to Aura4 servo subsystem if ( message::ap_channels == 6 ) { message::command_inceptors_t act; act.channel[0] = act_node.getDouble("throttle"); act.channel[1] = act_node.getDouble("aileron"); act.channel[2] = act_node.getDouble("elevator"); act.channel[3] = act_node.getDouble("rudder"); act.channel[4] = act_node.getDouble("flaps"); act.channel[5] = act_node.getDouble("gear"); act.pack(); serial.write_packet( act.id, act.payload, act.len ); } } void Aura4_t::close() { serial.close(); } void Aura4_t::command( const char *cmd ) { if ( (string)cmd == "airdata_calibrate" ) { airdata_zero_airspeed(); } }
36.260033
98
0.606936
[ "vector" ]
84bb468b8ff2a1124e49a41d7cd5f33c085da54a
10,048
cpp
C++
iris/shader/Shader.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/shader/Shader.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/shader/Shader.cpp
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
#include "Shader.h" #include "iris/Iris.h" #include "iris/IrisGL.h" #include "iris/IrisScene.h" #include "iris/IrisLogger.h" #include "mesh/Mesh.h" #include "matrix4x4/Matrix4x4.h" #include "transform/Transform.h" #include "texture2d/Texture2D.h" #include "renderer/Renderer.h" #include "gameobject/GameObject.h" #include "vector3f/Vector3f.h" #include <string.h> namespace IrisFramework { Shader::Shader() : m_name("new_shader"), m_shaderProgramId(-1), m_vertexShaderId(-1), m_fragmentShaderId(-1), m_verticesId(-1), m_colorsId(-1), m_textureCoordId(-1), m_normalsId(-1), m_modelMatrixId(-1), m_lightPosId(-1), m_lightColorId(-1), m_lightIntensityId(-1), m_mvpId(-1), m_mainTextureId(-1) {} Shader::Shader(const char* p_name) : m_name(p_name), m_shaderProgramId(-1), m_vertexShaderId(-1), m_fragmentShaderId(-1), m_verticesId(-1), m_colorsId(-1), m_textureCoordId(-1), m_normalsId(-1), m_modelMatrixId(-1), m_lightPosId(-1), m_lightColorId(-1), m_lightIntensityId(-1), m_mvpId(-1), m_mainTextureId(-1) {} Shader::~Shader() {} void Shader::dispose() {} void Shader::loadShaderData(unsigned char* p_vertData, unsigned char* p_fragData) { #if defined(__USE_ES2__) IRIS_LOG.internalLog("[%s] VERTEX Shader Compiling ...", m_name); m_vertexShaderId = compileShaderData(GL_VERTEX_SHADER, p_vertData); IRIS_LOG.internalLog("Vertex Shader Id: %d", m_vertexShaderId); IRIS_LOG.internalLog("[%s] FRAGMENT Shader Compiling ...", m_name); m_fragmentShaderId = compileShaderData(GL_FRAGMENT_SHADER, p_fragData); IRIS_LOG.internalLog("Fragment Shader Id: %d", m_fragmentShaderId); if(m_vertexShaderId == 0 || m_fragmentShaderId == 0) { IRIS_LOG.internalLog("** Unable to read shader files"); return; } m_shaderProgramId = glCreateProgram(); IRIS_LOG.internalLog("** Shader ProgramID: %i", m_shaderProgramId); if(m_shaderProgramId == 0) { return; } GLint linkSuccess = -1; glAttachShader(m_shaderProgramId, m_vertexShaderId); glAttachShader(m_shaderProgramId, m_fragmentShaderId); glLinkProgram(m_shaderProgramId); glGetProgramiv(m_shaderProgramId, GL_LINK_STATUS, &linkSuccess); if(!linkSuccess) { GLint infoLen = 0; glGetProgramiv(m_shaderProgramId, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char *infoLog = new char[infoLen]; glGetProgramInfoLog(m_shaderProgramId, infoLen, NULL, infoLog); IRIS_LOG.internalLog("** Error linking program: \n%s", infoLog); delete[] infoLog; } glDeleteProgram(m_shaderProgramId); } m_mvpId = glGetUniformLocation(m_shaderProgramId, "u_mvp"); IRIS_LOG.internalLog("** Shader mvp ID: %i", m_mvpId); m_verticesId = glGetAttribLocation(m_shaderProgramId, "a_vertPos"); IRIS_LOG.internalLog("** Vertices ID: %i", m_verticesId); m_textureCoordId = glGetAttribLocation(m_shaderProgramId, "a_textCoord"); IRIS_LOG.internalLog("** Texture Coord ID: %i", m_textureCoordId); m_normalsId = glGetAttribLocation(m_shaderProgramId, "a_fragNormal"); IRIS_LOG.internalLog("** Normals ID: %i", m_normalsId); m_tangentId = glGetAttribLocation(m_shaderProgramId, "a_tangent"); IRIS_LOG.internalLog("** Tangent ID: %i", m_tangentId); m_bitangentId = glGetAttribLocation(m_shaderProgramId, "a_bitangent"); IRIS_LOG.internalLog("** Bitangent ID: %i", m_bitangentId); m_colorsId = glGetAttribLocation(m_shaderProgramId, "a_fragColor"); IRIS_LOG.internalLog("** Colors ID: %i", m_colorsId); m_mainTextureId = glGetUniformLocation(m_shaderProgramId, "u_mainTexture"); IRIS_LOG.internalLog("** Main Texture ID: %i", m_mainTextureId); m_normalMapId = glGetUniformLocation(m_shaderProgramId, "u_normalMap"); IRIS_LOG.internalLog("** Normal Map ID: %i", m_normalMapId); m_modelMatrixId = glGetUniformLocation(m_shaderProgramId, "u_modelMatrix"); IRIS_LOG.internalLog("** Model Matrix ID: %i", m_modelMatrixId); m_cameraInvMatrixId = glGetUniformLocation(m_shaderProgramId, "u_cameraInvMatrix"); IRIS_LOG.internalLog("** Camera Inverse Matrix ID: %i", m_cameraInvMatrixId); m_cameraPositionId = glGetUniformLocation(m_shaderProgramId, "u_cameraPosition"); IRIS_LOG.internalLog("** Camera Position ID: %i", m_cameraPositionId); m_shininessId = glGetUniformLocation(m_shaderProgramId, "u_shininess"); IRIS_LOG.internalLog("** Shininess ID: %i", m_shininessId); m_specularColorId = glGetUniformLocation(m_shaderProgramId, "u_specularColor"); IRIS_LOG.internalLog("** Specular Color ID: %i", m_specularColorId); m_lightPosId = glGetUniformLocation(m_shaderProgramId, "light1.position"); IRIS_LOG.internalLog("** Light 1 Position ID: %i", m_lightPosId); m_lightColorId = glGetUniformLocation(m_shaderProgramId, "light1.color"); IRIS_LOG.internalLog("** Light 1 Color ID: %i", m_lightColorId); m_lightIntensityId = glGetUniformLocation(m_shaderProgramId, "light1.intensity"); IRIS_LOG.internalLog("** Light 1 Intensity ID: %i", m_lightIntensityId); m_lightAttenuationId = glGetUniformLocation(m_shaderProgramId, "light1.attenuation"); IRIS_LOG.internalLog("** Light 1 Attenuation ID: %i", m_lightAttenuationId); m_lightAmbientCoefficientId = glGetUniformLocation(m_shaderProgramId, "light1.ambientCoefficient"); IRIS_LOG.internalLog("** Light 1 Ambient Coefficient ID: %i", m_lightAmbientCoefficientId); m_lightRadius = glGetUniformLocation(m_shaderProgramId, "light1.radius"); IRIS_LOG.internalLog("** Light 1 Radius ID: %i", m_lightRadius); m_light1PosId = glGetUniformLocation(m_shaderProgramId, "light2.position"); IRIS_LOG.internalLog("** Light 2 Position ID: %i", m_light1PosId); m_light1ColorId = glGetUniformLocation(m_shaderProgramId, "light2.color"); IRIS_LOG.internalLog("** Light 2 Color ID: %i", m_light1ColorId); m_light1IntensityId = glGetUniformLocation(m_shaderProgramId, "light2.intensity"); IRIS_LOG.internalLog("** Light 2 Intensity ID: %i", m_light1IntensityId); m_light1AttenuationId = glGetUniformLocation(m_shaderProgramId, "light2.attenuation"); IRIS_LOG.internalLog("** Light 2 Attenuation ID: %i", m_light1AttenuationId); m_light1AmbientCoefficientId = glGetUniformLocation(m_shaderProgramId, "light2.ambientCoefficient"); IRIS_LOG.internalLog("** Light 2 Ambient Coefficient ID: %i", m_light1AmbientCoefficientId); m_light1Radius = glGetUniformLocation(m_shaderProgramId, "light2.radius"); IRIS_LOG.internalLog("** Light 2 Radius ID: %i", m_light1Radius); IRIS_LOG.internalLog("** End of Shader Compilation **"); #endif } const char *Shader::getName() const { return m_name; } int Shader::getShaderProgramId() const { return m_shaderProgramId; } int Shader::getVertexShaderId() const { return m_vertexShaderId; } int Shader::getFragmentShaderId() const { return m_fragmentShaderId; } int Shader::getVerticesId() const { return m_verticesId; } int Shader::getColorsId() const { return m_colorsId; } int Shader::getTextureCoordId() const { return m_textureCoordId; } int Shader::getNormalsId() const { return m_normalsId; } int Shader::getTangentId() const { return m_tangentId; } int Shader::getBitangentId() const { return m_bitangentId; } int Shader::getModelMatrixId() const { return m_modelMatrixId; } int Shader::getCameraInvMatrixId() const { return m_cameraInvMatrixId; } int Shader::getCameraPositionId() const { return m_cameraPositionId; } int Shader::getShininessId() const { return m_shininessId; } int Shader::getSpecularColorId() const { return m_specularColorId; } int Shader::getLightPosId() const { return m_lightPosId; } int Shader::getLightColorId() const { return m_lightColorId; } int Shader::getLightIntensityId() const { return m_lightIntensityId; } int Shader::getLightAttenuationId() const { return m_lightAttenuationId; } int Shader::getLightAmbientCoefficientId() const { return m_lightAmbientCoefficientId; } int Shader::getLightRadius() const { return m_lightRadius; } int Shader::getLight1PosId() const { return m_light1PosId; } int Shader::getLight1ColorId() const { return m_light1ColorId; } int Shader::getLight1IntensityId() const { return m_light1IntensityId; } int Shader::getLight1AttenuationId() const { return m_light1AttenuationId; } int Shader::getLight1AmbientCoefficientId() const { return m_light1AmbientCoefficientId; } int Shader::getLight1Radius() const { return m_light1Radius; } int Shader::getMvpId() const { return m_mvpId; } int Shader::getMainTextureId() const { return m_mainTextureId; } int Shader::getNormalMapId() const { return m_normalMapId; } int Shader::compileShaderData(GLuint p_shaderType, unsigned char *p_shaderData) { #if defined(__USE_ES2__) int shaderId = glCreateShader(p_shaderType); IRIS_LOG.internalLog("Compile ProgramID: %i", shaderId); #if defined(_WIN32) char *fileBuffer = (char*)p_shaderData; glShaderSource(shaderId, 1, &fileBuffer, 0); #elif defined(_ANDROID) const char *fileBuffer = (const char*)p_shaderData; glShaderSource(shaderId, 1, &fileBuffer, 0); #endif glCompileShader(shaderId); GLint compileSuccess = 0; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileSuccess); if(!compileSuccess) { GLint infoLen = 0; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char *infoLog = new char[infoLen]; glGetShaderInfoLog(shaderId, infoLen, NULL, infoLog); IRIS_LOG.internalLog("Error compiling shader:\n%s", infoLog); delete[] infoLog; } } #if defined(_WIN32) delete[] fileBuffer; #endif return shaderId; #endif return 0; } }
26.723404
103
0.715267
[ "mesh", "model", "transform" ]
84bc4e23bec850c9e8ac5a5d9dd4a02eb8d20257
7,929
cpp
C++
be/test/util/tdigest_test.cpp
kaiker19/incubator-doris
f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be
[ "Apache-2.0" ]
3,562
2018-08-30T05:26:10.000Z
2022-03-31T10:01:56.000Z
be/test/util/tdigest_test.cpp
kaiker19/incubator-doris
f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be
[ "Apache-2.0" ]
5,199
2018-09-11T07:57:21.000Z
2022-03-31T16:17:50.000Z
be/test/util/tdigest_test.cpp
kaiker19/incubator-doris
f4c5c6ccc650012a0db7ddda8a38f4c65cc5c9be
[ "Apache-2.0" ]
1,234
2018-08-31T09:34:54.000Z
2022-03-31T06:01:02.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/tdigest.h" #include <gtest/gtest.h> #include <random> #include "test_util/test_util.h" namespace doris { class TDigestTest : public ::testing::Test { protected: // You can remove any or all of the following functions if its body // is empty. TDigestTest() { // You can do set-up work for each test here. } virtual ~TDigestTest() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } static void SetUpTestCase() { static bool initialized = false; if (!initialized) { FLAGS_logtostderr = true; google::InstallFailureSignalHandler(); google::InitGoogleLogging("testing::TDigestTest"); initialized = true; } } // Objects declared here can be used by all tests in the test case for Foo. }; static double quantile(const double q, const std::vector<double>& values) { double q1; if (values.size() == 0) { q1 = NAN; } else if (q == 1 || values.size() == 1) { q1 = values[values.size() - 1]; } else { auto index = q * values.size(); if (index < 0.5) { q1 = values[0]; } else if (values.size() - index < 0.5) { q1 = values[values.size() - 1]; } else { index -= 0.5; const int intIndex = static_cast<int>(index); q1 = values[intIndex + 1] * (index - intIndex) + values[intIndex] * (intIndex + 1 - index); } } return q1; } TEST_F(TDigestTest, CrashAfterMerge) { TDigest digest(1000); std::uniform_real_distribution<> reals(0.0, 1.0); std::random_device gen; for (int i = 0; i < LOOP_LESS_OR_MORE(100, 100000); i++) { digest.add(reals(gen)); } digest.compress(); TDigest digest2(1000); digest2.merge(&digest); digest2.quantile(0.5); } TEST_F(TDigestTest, EmptyDigest) { TDigest digest(100); EXPECT_EQ(0, digest.processed().size()); } TEST_F(TDigestTest, SingleValue) { TDigest digest(100); std::random_device gen; std::uniform_real_distribution<> dist(0, 1000); const auto value = dist(gen); digest.add(value); std::uniform_real_distribution<> dist2(0, 1.0); const double q = dist2(gen); EXPECT_NEAR(value, digest.quantile(0.0), 0.001f); EXPECT_NEAR(value, digest.quantile(q), 0.001f); EXPECT_NEAR(value, digest.quantile(1.0), 0.001f); } TEST_F(TDigestTest, FewValues) { // When there are few values in the tree, quantiles should be exact TDigest digest(1000); std::random_device gen; std::uniform_real_distribution<> reals(0.0, 100.0); std::uniform_int_distribution<> dist(0, 10); std::uniform_int_distribution<> bools(0, 1); std::uniform_real_distribution<> qvalue(0.0, 1.0); const auto length = 10; //dist(gen); std::vector<double> values; values.reserve(length); for (int i = 0; i < length; ++i) { auto const value = (i == 0 || bools(gen)) ? reals(gen) : values[i - 1]; digest.add(value); values.push_back(value); } std::sort(values.begin(), values.end()); digest.compress(); EXPECT_EQ(digest.processed().size(), values.size()); std::vector<double> testValues{0.0, 1.0e-10, qvalue(gen), 0.5, 1.0 - 1e-10, 1.0}; for (auto q : testValues) { double q1 = quantile(q, values); auto q2 = digest.quantile(q); if (std::isnan(q1)) { EXPECT_TRUE(std::isnan(q2)); } else { EXPECT_NEAR(q1, q2, 0.03) << "q = " << q; } } } TEST_F(TDigestTest, MoreThan2BValues) { TDigest digest(1000); std::random_device gen; std::uniform_real_distribution<> reals(0.0, 1.0); for (int i = 0; i < 1000; ++i) { const double next = reals(gen); digest.add(next); } for (int i = 0; i < 10; ++i) { const double next = reals(gen); const auto count = 1L << 28; digest.add(next, count); } EXPECT_EQ(static_cast<long>(1000 + float(10L * (1 << 28))), digest.totalWeight()); EXPECT_GT(digest.totalWeight(), std::numeric_limits<int32_t>::max()); std::vector<double> quantiles{0, 0.1, 0.5, 0.9, 1, reals(gen)}; std::sort(quantiles.begin(), quantiles.end()); auto prev = std::numeric_limits<double>::min(); for (double q : quantiles) { const double v = digest.quantile(q); EXPECT_GE(v, prev) << "q = " << q; prev = v; } } TEST_F(TDigestTest, MergeTest) { TDigest digest1(1000); TDigest digest2(1000); digest2.add(std::vector<const TDigest*>{&digest1}); } TEST_F(TDigestTest, TestSorted) { TDigest digest(1000); std::uniform_real_distribution<> reals(0.0, 1.0); std::uniform_int_distribution<> ints(0, 10); std::random_device gen; for (int i = 0; i < 10000; ++i) { digest.add(reals(gen), 1 + ints(gen)); } digest.compress(); Centroid previous(0, 0); for (auto centroid : digest.processed()) { if (previous.weight() != 0) { CHECK_LE(previous.mean(), centroid.mean()); } previous = centroid; } } TEST_F(TDigestTest, ExtremeQuantiles) { TDigest digest(1000); // t-digest shouldn't merge extreme nodes, but let's still test how it would // answer to extreme quantiles in that case ('extreme' in the sense that the // quantile is either before the first node or after the last one) digest.add(10, 3); digest.add(20, 1); digest.add(40, 5); // this group tree is roughly equivalent to the following sorted array: // [ ?, 10, ?, 20, ?, ?, 50, ?, ? ] // and we expect it to compute approximate missing values: // [ 5, 10, 15, 20, 30, 40, 50, 60, 70] std::vector<double> values{5.0, 10.0, 15.0, 20.0, 30.0, 35.0, 40.0, 45.0, 50.0}; std::vector<double> quantiles{1.5 / 9.0, 3.5 / 9.0, 6.5 / 9.0}; for (auto q : quantiles) { EXPECT_NEAR(quantile(q, values), digest.quantile(q), 0.01) << "q = " << q; } } TEST_F(TDigestTest, Montonicity) { TDigest digest(1000); std::uniform_real_distribution<> reals(0.0, 1.0); std::random_device gen; for (int i = 0; i < LOOP_LESS_OR_MORE(10, 100000); i++) { digest.add(reals(gen)); } double lastQuantile = -1; double lastX = -1; for (double z = 0; z <= 1; z += LOOP_LESS_OR_MORE(0.1, 1e-5)) { double x = digest.quantile(z); EXPECT_GE(x, lastX); lastX = x; double q = digest.cdf(z); EXPECT_GE(q, lastQuantile); lastQuantile = q; } } } // namespace doris int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.094118
86
0.608778
[ "vector" ]
84bd4b37b9edb2c082a32ad07b5392ad77487efe
5,497
hpp
C++
src/world/entity.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
7
2015-01-28T09:17:08.000Z
2020-04-21T13:51:16.000Z
src/world/entity.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
null
null
null
src/world/entity.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
1
2020-07-11T09:20:25.000Z
2020-07-11T09:20:25.000Z
#ifndef __ENTITY_HPP__ # define __ENTITY_HPP__ #include <world/components.hpp> #include <world/status.hpp> #include <world/brain.hpp> #include <world/work.hpp> #include <cassert> #include <cstdint> #include <memory> #include <list> using EntityId = uint16_t; using EntityType = uint16_t; class Camera; class World; class Work; class Unit; class Entity { friend class Camera; friend class World; public: Entity(const EntityType& type): id(++Entity::current_id), type(type), to_be_deleted(false), manipulable(false), brain(std::make_unique<Brain>()) { } ~Entity(); EntityId get_id() const { return this->id; } EntityType get_type() const { return this->type; } /** * Regularly update the entity. */ void tick(World*); void clear_works(); void set_work(std::unique_ptr<Work>); void queue_work(std::unique_ptr<Work>); void interrupt(); Work* get_current_work(); const Work* get_current_work() const; template <typename WorkType> WorkType* get_current_work() { return dynamic_cast<WorkType*>(this->get_current_work()); } template <typename WorkType> const WorkType* get_current_work() const { return dynamic_cast<const WorkType*>(this->get_current_work()); } template <typename ComponentClass> ComponentClass* get() const { static_assert(std::is_base_of<Component, ComponentClass>::value, "ComponentClass must be a Component."); static_assert(ComponentClass::component_type != ComponentType::Invalid, "ComponentClass must set its own type."); auto index = static_cast<std::size_t>(ComponentClass::component_type); return static_cast<ComponentClass*>(this->components[index].get()); } template <typename ComponentClass> void add_component(ComponentClass&& pointer) { auto index = static_cast<std::size_t>(ComponentClass::element_type::component_type); this->components[index] = std::move(pointer); } template <typename StatusType, typename... ArgsType> void add_status(World* world, ArgsType&&... args) { auto status = std::make_unique<StatusType>(this, world, std::forward<ArgsType>(args)...); status->apply(); this->status.push_back(std::move(status)); } template <typename BrainType, typename... ArgsType> void set_brain(World* world, ArgsType&&... args) { this->brain = std::make_unique<BrainType>(this, world, std::forward<ArgsType>(args)...); } template <typename T> const T* get_task() const { auto work = this->get_current_work(); if (!work) return nullptr; auto task = work->get_task(); if (!task) return nullptr; auto res = dynamic_cast<const T*>(task); assert(res); // TODO in non-debug build, do not use dynamic cast, use this instead: // return static_cast<const T*>(task); return res; } /** * Mark this entity to be removed from the world. */ void kill(); bool is_dead() const; /** * Unless this is called, the entity can not be selected or given orders * by any player (for example projectiles, ground AOEs etc) */ void make_manipulable(); bool is_manipulable() const; private: Entity& operator=(const Entity&) = delete; Entity& operator=(Entity&&) = delete; Entity(const Entity&) = delete; Entity(Entity&&) = delete; public: /** * Incremented each type we create a new entity, and used as Entity::id. */ static EntityId current_id; /** * An uniq id for the entity. */ EntityId id; /** * The type of the entity */ EntityType type; /** * Whether or not the entity should be deleted from the World on the next * cleanup. */ bool to_be_deleted; /** * The entity name */ std::string name; /** * Whether or not this entity can be manipulated by a player (and thus * selected) */ bool manipulable; /** * A serie of works that the entity has to execute. For example * World::do_path will add a PathWork to the entity, which contains a path * and a pointer to Unit::follow_path, receiving that PathWork structure * as an argument. World::do_build will push a PathWork (to go to the cell * to build) and a BuildWork. * * Once the Work is done (destination reached, or building complete, or * anything), we pop that work. Many works can be queued. For example if * we do a shift-move, the PathWork is added at the end of the list. If * not, it just replaces all the works in the list. * * A list is used instead of a queue, though a queue would be almost * perfect (push back, pop front only), but we need to be able to traverse * the list to check their value etc. So we just use a list and push_back * and pop_front instead. Should be almost as efficient. */ std::list<std::unique_ptr<Work>> works; /** * A map of components that define what the entity can do. Without a * component, it's basically empty and can do nothing in the world. * * For example an entity that has a world position and can move has a * PositionComponent, which tracks the position of the entity and has * methods to alter this position. */ std::array<std::unique_ptr<Component>, ComponentTypeCount> components; /** * The list of Status that currently affect this entity. */ std::vector<std::unique_ptr<Status>> status; std::unique_ptr<Brain> brain; }; #endif // __ENTITY_HPP__
28.931579
88
0.668546
[ "vector" ]
84c2ca245fc70af598e01f4720d82b7e2ed7b238
450
cpp
C++
src/materials/lambertian.cpp
Zielon/PBRenderer
66171bb741bccf14ae6d3e2120a03ab44289263b
[ "BSD-2-Clause" ]
7
2020-11-06T21:06:36.000Z
2022-02-12T01:00:16.000Z
src/materials/lambertian.cpp
Zielon/PBRenderer
66171bb741bccf14ae6d3e2120a03ab44289263b
[ "BSD-2-Clause" ]
null
null
null
src/materials/lambertian.cpp
Zielon/PBRenderer
66171bb741bccf14ae6d3e2120a03ab44289263b
[ "BSD-2-Clause" ]
null
null
null
#include "lambertian.h" #include "../geometry/triangle.h" #include "../bxdfs/lambertian_reflection.h" void pbr::LambertianMaterial::compute_BxDF(Intersection& intersection, TransportMode mode) const{ Triangle* triangle = const_cast<Triangle*>(intersection.triangle); intersection.bsdf = std::make_shared<BSDF>(intersection, triangle->scene_object); intersection.bsdf->add(std::make_shared<LambertianReflection>(kd->evaluate(intersection))); }
34.615385
97
0.786667
[ "geometry" ]
84c785fa5673cbdec058001693e3d723ced6e1d0
3,105
cpp
C++
src/polygon.cpp
simonsobs/lyrebird
027ca633876860c492270983c3880a7d4b87f14b
[ "BSD-2-Clause" ]
null
null
null
src/polygon.cpp
simonsobs/lyrebird
027ca633876860c492270983c3880a7d4b87f14b
[ "BSD-2-Clause" ]
1
2021-02-04T03:16:43.000Z
2021-02-04T16:43:09.000Z
src/polygon.cpp
simonsobs/lyrebird
027ca633876860c492270983c3880a7d4b87f14b
[ "BSD-2-Clause" ]
1
2019-03-19T01:27:11.000Z
2019-03-19T01:27:11.000Z
#include "polygon.h" #include "geometryutils.h" #include "genericutils.h" using namespace glm; using namespace std; Polygon::Polygon(std::vector<glm::vec2> points){ vector<vec2> tri_points; triangulate_polygon(points,tri_points); for (size_t i=0; i < tri_points.size(); i+=3){ tris.push_back( Triangle(tri_points[i],tri_points[i+1],tri_points[i+2])); } set_AABB(); } void Polygon::set_AABB(){ if (tris.size() <1) print_and_exit("we have an empty triangle"); vec2 min; vec2 max; tris[0].get_AABB(min_AABB, max_AABB); for (size_t i=1; i < tris.size(); i++){ tris[i].get_AABB(min, max); if (min.x < min_AABB.x) min_AABB.x = min.x; if (min.y < min_AABB.y) min_AABB.y = min.y; if (max.x > max_AABB.x) max_AABB.x = max.x; if (max.y > max_AABB.y) max_AABB.y = max.y; } } void Polygon::get_AABB(glm::vec2 & min_aabb, glm::vec2 & max_aabb){ min_aabb = min_AABB; max_aabb = max_AABB; } void Polygon::apply_transform(glm::mat4 trans){ for (size_t i = 0; i < tris.size(); i++) tris[i].apply_transform(trans); set_AABB(); } bool Polygon::is_inside(vec2 p){ //DCOUT( "Checking inside min: x" << min_AABB.x << " y"<<min_AABB.y, DEBUG_1); //DCOUT( "Checking inside max: x" << max_AABB.x << " y"<<max_AABB.y, DEBUG_1); if (!((p.x >= min_AABB.x) && (p.x <= max_AABB.x) && (p.y >= min_AABB.y) && (p.y <= max_AABB.y)) ) return false; for (size_t i=0; i < tris.size(); i++){ if (tris[i].is_inside(p)) return true; } return false; } Triangle::Triangle(vec2 p0, vec2 p1, vec2 p2){ ps[0] = (p0); ps[1] = (p1); ps[2] = (p2); /** cout<<"Instantiating triangle"<<endl; for (int i=0; i < 3; i++) cout<<"Tri point "<<i<<": x:"<<ps[i].x<<" y:"<<ps[i].y<<endl; **/ set_AABB(); } void Triangle::get_AABB(glm::vec2 & min_aabb, glm::vec2 & max_aabb){ min_aabb = min_AABB; max_aabb = max_AABB; } void Triangle::set_AABB(){ min_AABB = ps[0]; max_AABB = ps[0]; if (ps[1].x < min_AABB.x) min_AABB.x = ps[1].x; if (ps[2].x < min_AABB.x) min_AABB.x = ps[2].x; if (ps[1].y < min_AABB.y) min_AABB.y = ps[1].y; if (ps[2].y < min_AABB.y) min_AABB.y = ps[2].y; if (ps[1].x > max_AABB.x) max_AABB.x = ps[1].x; if (ps[2].x > max_AABB.x) max_AABB.x = ps[2].x; if (ps[1].y > max_AABB.y) max_AABB.y = ps[1].y; if (ps[2].y > max_AABB.y) max_AABB.y = ps[2].y; } void Triangle::apply_transform(mat4 trans){ for (int i=0; i < 3; i++) ps[i] = transform_vec2(ps[i], trans); set_AABB(); } bool Triangle::is_inside(vec2 p){ if (!((p.x >= min_AABB.x) && (p.x <= max_AABB.x) && (p.y >= min_AABB.y) && (p.y <= max_AABB.y)) ) return false; //return true; vec2 v0 = ps[2] - ps[0]; vec2 v1 = ps[1] - ps[0]; vec2 v2 = p - ps[0]; float dot00 = dot(v0, v0); float dot01 = dot(v0, v1); float dot02 = dot(v0, v2); float dot11 = dot(v1, v1); float dot12 = dot(v1, v2); float inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12) * inv_denom; float v = (dot00 * dot12 - dot01 * dot02) * inv_denom; return (u >= 0) && (v >= 0) && (u + v < 1); }
26.767241
80
0.588728
[ "vector" ]
84c7d290f91bebdd07aa4994defa99fde666d96b
665
hpp
C++
include/mh/scene/spatial.hpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
include/mh/scene/spatial.hpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
include/mh/scene/spatial.hpp
overworks/MhGameLib
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
[ "MIT" ]
null
null
null
#ifndef _MH_SCENE_SPATIAL_HPP_ #define _MH_SCENE_SPATIAL_HPP_ #include <mh/prerequisite.h> #include <mh/math.hpp> namespace Mh { class Renderer; namespace Scene { class Spatial { public: Spatial(); virtual ~Spatial() = 0; virtual void update() = 0; virtual void render(Renderer* renderer) const = 0; private: Spatial* m_parent; Vector3 m_local_scale; Quaternion m_local_rotation; Vector3 m_local_translation; Vector3 m_world_scale; Quaternion m_world_rotation; Vector3 m_world_translation; Matrix4x4 m_cached_matrix; }; } // namespace Mh::Scene } // namespace Mh #endif /* _MH_SCENE_SPATIAL_HPP_ */
16.219512
53
0.711278
[ "render" ]
84cbb3045bc3d8beadf7ef46ab850ffda5e78724
1,359
hpp
C++
ironforge/src/scene/input.hpp
m1nuz/ironforge
b6e1875a2442e48e8982cb3d622b5a1ef2af5663
[ "MIT" ]
null
null
null
ironforge/src/scene/input.hpp
m1nuz/ironforge
b6e1875a2442e48e8982cb3d622b5a1ef2af5663
[ "MIT" ]
null
null
null
ironforge/src/scene/input.hpp
m1nuz/ironforge
b6e1875a2442e48e8982cb3d622b5a1ef2af5663
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <string> #include <vector> #include <memory> #include <optional> #include <functional> #include <core/json.hpp> #include <SDL2/SDL_events.h> namespace scene { struct instance_type; typedef instance_type instance_t; struct input_action { std::string key_down; std::string key_up; std::string caxis_motion; SDL_Keycode key; SDL_GameControllerButton cbutton; SDL_GameControllerAxis caxis; }; struct input_source { std::string name; uint64_t hash; std::vector<input_action> actions; }; struct input_instance { uint32_t entity; input_source *source; std::vector<input_action> actions; }; using input_ref = std::reference_wrapper<input_instance>; [[nodiscard]] auto create_input(const uint32_t entity, const json &info, const std::unordered_map<std::string, std::vector<input_action>> &sources) -> std::optional<input_instance>; auto create_input_source(scene::instance_t &s, const std::string &name, const std::vector<input_action> &actions) -> bool; auto process_input_events(scene::instance_t &s, const SDL_Event &e) -> void; } // namespace scene
28.914894
185
0.623252
[ "vector" ]
84cfd90c5017f9fb0d1cd2317bd6ab29867aca5f
9,961
cc
C++
src/ui/a11y/lib/semantics/tests/semantic_tree_service_unittest.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/ui/a11y/lib/semantics/tests/semantic_tree_service_unittest.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
src/ui/a11y/lib/semantics/tests/semantic_tree_service_unittest.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/a11y/lib/semantics/semantic_tree_service.h" #include <fuchsia/accessibility/cpp/fidl.h> #include <fuchsia/sys/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/fd.h> #include <lib/gtest/test_loop_fixture.h> #include <lib/sys/cpp/testing/component_context_provider.h> #include <lib/syslog/cpp/macros.h> #include <lib/vfs/cpp/pseudo_dir.h> #include <lib/zx/event.h> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/ui/a11y/bin/a11y_manager/tests/util/util.h" #include "src/ui/a11y/lib/semantics/semantic_tree.h" #include "src/ui/a11y/lib/semantics/tests/semantic_tree_parser.h" #include "src/ui/a11y/lib/util/util.h" namespace accessibility_test { namespace { using fuchsia::accessibility::semantics::Node; using fuchsia::accessibility::semantics::Role; using ::testing::ElementsAre; const int kMaxLogBufferSize = 1024; class MockSemanticTree : public ::a11y::SemanticTree { public: bool Update(TreeUpdates updates) override { for (const auto& update : updates) { if (update.has_delete_node_id()) { deleted_node_ids_.push_back(update.delete_node_id()); received_updates_.emplace_back(update.delete_node_id()); } else if (update.has_node()) { Node copy1; Node copy2; update.node().Clone(&copy1); update.node().Clone(&copy2); updated_nodes_.push_back(std::move(copy1)); received_updates_.emplace_back(std::move(copy2)); } } if (reject_commit_) { return false; } return ::a11y::SemanticTree::Update(std::move(updates)); } void OnSemanticsEvent(a11y::SemanticsEventInfo event_info) override { received_events_ = true; } void WillReturnFalseOnNextCommit() { reject_commit_ = true; } void ClearMockStatus() { received_updates_.clear(); deleted_node_ids_.clear(); updated_nodes_.clear(); reject_commit_ = false; received_events_ = false; } TreeUpdates& received_updates() { return received_updates_; } std::vector<uint32_t>& deleted_node_ids() { return deleted_node_ids_; } std::vector<Node>& updated_nodes() { return updated_nodes_; } bool received_events() const { return received_events_; } private: // A copy of the updates sent to this tree. TreeUpdates received_updates_; std::vector<uint32_t> deleted_node_ids_; std::vector<Node> updated_nodes_; bool reject_commit_ = false; bool received_events_ = false; }; const std::string kSemanticTreeSingleNodePath = "/pkg/data/semantic_tree_single_node.json"; const std::string kSemanticTreeOddNodesPath = "/pkg/data/semantic_tree_odd_nodes.json"; auto NodeIdEq(uint32_t node_id) { return testing::Property(&Node::node_id, node_id); } class SemanticTreeServiceTest : public gtest::TestLoopFixture { public: SemanticTreeServiceTest() {} protected: void SetUp() override { TestLoopFixture::SetUp(); // Create View Ref. zx::eventpair a; zx::eventpair::create(0u, &a, &b_); a11y::SemanticTreeService::CloseChannelCallback close_channel_callback( [this](zx_status_t status) { this->close_channel_called_ = true; this->close_channel_status_ = status; }); auto tree = std::make_unique<MockSemanticTree>(); tree_ptr_ = tree.get(); semantic_tree_ = std::make_unique<a11y::SemanticTreeService>( std::move(tree), koid_, fuchsia::accessibility::semantics::SemanticListenerPtr() /*unused*/, debug_dir(), std::move(close_channel_callback)); semantic_tree_->EnableSemanticsUpdates(true); } std::vector<Node> BuildUpdatesFromFile(const std::string& file_path) { std::vector<Node> nodes; EXPECT_TRUE(semantic_tree_parser_.ParseSemanticTree(file_path, &nodes)); return nodes; } void InitializeTreeNodesFromFile(const std::string& file_path) { ::a11y::SemanticTree::TreeUpdates updates; std::vector<Node> nodes; EXPECT_TRUE(semantic_tree_parser_.ParseSemanticTree(file_path, &nodes)); for (auto& node : nodes) { updates.emplace_back(std::move(node)); } EXPECT_TRUE(tree_ptr_->Update(std::move(updates))); tree_ptr_->ClearMockStatus(); } vfs::PseudoDir* debug_dir() { return context_provider_.context()->outgoing()->debug_dir(); } int OpenAsFD(vfs::internal::Node* node, async_dispatcher_t* dispatcher) { zx::channel local, remote; EXPECT_EQ(ZX_OK, zx::channel::create(0, &local, &remote)); EXPECT_EQ(ZX_OK, node->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE, std::move(remote), dispatcher)); int fd = -1; EXPECT_EQ(ZX_OK, fdio_fd_create(local.release(), &fd)); return fd; } char* ReadFile(vfs::internal::Node* node, int length, char* buffer) { EXPECT_LE(length, kMaxLogBufferSize); async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread); loop.StartThread("ReadingDebugFile"); int fd = OpenAsFD(node, loop.dispatcher()); EXPECT_LE(0, fd); memset(buffer, 0, kMaxLogBufferSize); EXPECT_EQ(length, pread(fd, buffer, length, 0)); return buffer; } sys::testing::ComponentContextProvider context_provider_; std::unique_ptr<a11y::SemanticTreeService> semantic_tree_; MockSemanticTree* tree_ptr_ = nullptr; bool close_channel_called_ = false; zx_status_t close_channel_status_ = 0; zx_koid_t koid_ = 12345; SemanticTreeParser semantic_tree_parser_; // The event signaling pair member, used to invalidate the View Ref. zx::eventpair b_; }; TEST_F(SemanticTreeServiceTest, IsSameViewReturnsTrueForTreeViewRef) { EXPECT_EQ(semantic_tree_->view_ref_koid(), koid_); } TEST_F(SemanticTreeServiceTest, UpdatesAreSentOnlyAfterCommit) { auto updates = BuildUpdatesFromFile(kSemanticTreeOddNodesPath); semantic_tree_->UpdateSemanticNodes(std::move(updates)); EXPECT_TRUE(tree_ptr_->received_updates().empty()); bool commit_called = false; auto callback = [&commit_called]() { commit_called = true; }; semantic_tree_->CommitUpdates(std::move(callback)); EXPECT_TRUE(commit_called); EXPECT_THAT(tree_ptr_->updated_nodes(), ElementsAre(NodeIdEq(0), NodeIdEq(1), NodeIdEq(2), NodeIdEq(3), NodeIdEq(4), NodeIdEq(5), NodeIdEq(6))); } TEST_F(SemanticTreeServiceTest, InvalidTreeUpdatesClosesTheChannel) { auto updates = BuildUpdatesFromFile(kSemanticTreeOddNodesPath); tree_ptr_->WillReturnFalseOnNextCommit(); semantic_tree_->UpdateSemanticNodes(std::move(updates)); EXPECT_TRUE(tree_ptr_->received_updates().empty()); bool commit_called = false; auto callback = [&commit_called]() { commit_called = true; }; semantic_tree_->CommitUpdates(std::move(callback)); EXPECT_TRUE(commit_called); // This commit failed, check if the callback to close the channel was invoked. EXPECT_TRUE(close_channel_called_); EXPECT_EQ(close_channel_status_, ZX_ERR_INVALID_ARGS); } TEST_F(SemanticTreeServiceTest, DeletesAreOnlySentAfterACommit) { auto updates = BuildUpdatesFromFile(kSemanticTreeOddNodesPath); semantic_tree_->UpdateSemanticNodes(std::move(updates)); semantic_tree_->CommitUpdates([]() {}); tree_ptr_->ClearMockStatus(); semantic_tree_->DeleteSemanticNodes({5, 6}); // Update the parent. std::vector<Node> new_updates; new_updates.emplace_back(CreateTestNode(2, "updated parent")); *new_updates.back().mutable_child_ids() = std::vector<uint32_t>(); semantic_tree_->UpdateSemanticNodes(std::move(new_updates)); semantic_tree_->CommitUpdates([]() {}); EXPECT_THAT(tree_ptr_->deleted_node_ids(), ElementsAre(5, 6)); EXPECT_THAT(tree_ptr_->updated_nodes(), ElementsAre(NodeIdEq(2))); } TEST_F(SemanticTreeServiceTest, EnableSemanticsUpdatesClearsTreeOnDisable) { InitializeTreeNodesFromFile(kSemanticTreeSingleNodePath); EXPECT_EQ(semantic_tree_->Get()->Size(), 1u); // Disable semantic updates and verify that tree is cleared. semantic_tree_->EnableSemanticsUpdates(false); EXPECT_EQ(semantic_tree_->Get()->Size(), 0u); } TEST_F(SemanticTreeServiceTest, LogsSemanticTree) { auto updates = BuildUpdatesFromFile(kSemanticTreeOddNodesPath); semantic_tree_->UpdateSemanticNodes(std::move(updates)); semantic_tree_->CommitUpdates([]() {}); const std::string expected_semantic_tree_odd = "ID: 0 Label:Node-0 Location: no location Transform: no transform Role: no role Action: no " "actions\n" " ID: 1 Label:Node-1 Location: no location Transform: no transform Role: no role Action: " "no actions\n" " ID: 3 Label:Node-3 Location: no location Transform: no transform Role: no role " "Action: no actions\n" " ID: 4 Label:Node-4 Location: no location Transform: no transform Role: no role " "Action: no actions\n" " ID: 2 Label:Node-2 Location: no location Transform: no transform Role: no role Action: " "no actions\n" " ID: 5 Label:Node-5 Location: no location Transform: no transform Role: no role " "Action: no actions\n" " ID: 6 Label:Node-6 Location: no location Transform: no transform Role: no role " "Action: no actions\n"; vfs::internal::Node* node; EXPECT_EQ(ZX_OK, debug_dir()->Lookup(std::to_string(semantic_tree_->view_ref_koid()), &node)); char buffer[kMaxLogBufferSize]; ReadFile(node, expected_semantic_tree_odd.size(), buffer); EXPECT_EQ(expected_semantic_tree_odd, buffer); } TEST_F(SemanticTreeServiceTest, SemanticEventsAreSentToTheTree) { fuchsia::accessibility::semantics::SemanticEvent event; bool callback_ran = false; semantic_tree_->SendSemanticEvent(std::move(event), [&callback_ran]() { callback_ran = true; }); RunLoopUntilIdle(); EXPECT_TRUE(callback_ran); EXPECT_TRUE(tree_ptr_->received_events()); } } // namespace } // namespace accessibility_test
36.221818
100
0.726333
[ "vector", "transform" ]
84d72c14993a809229831806640bdc7b3cdb6fdf
19,319
cpp
C++
src/realm/query_engine.cpp
Jahan87/realm-core
97c8e13da5b8a791a461932047a2771f5e88a7d8
[ "Apache-2.0" ]
null
null
null
src/realm/query_engine.cpp
Jahan87/realm-core
97c8e13da5b8a791a461932047a2771f5e88a7d8
[ "Apache-2.0" ]
null
null
null
src/realm/query_engine.cpp
Jahan87/realm-core
97c8e13da5b8a791a461932047a2771f5e88a7d8
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #include <realm/query_engine.hpp> #include <realm/query_expression.hpp> #include <realm/index_string.hpp> #include <realm/db.hpp> #include <realm/utilities.hpp> using namespace realm; ParentNode::ParentNode(const ParentNode& from) : m_child(from.m_child ? from.m_child->clone() : nullptr) , m_condition_column_name(from.m_condition_column_name) , m_condition_column_key(from.m_condition_column_key) , m_dD(from.m_dD) , m_dT(from.m_dT) , m_probes(from.m_probes) , m_matches(from.m_matches) , m_table(from.m_table) { } size_t ParentNode::find_first(size_t start, size_t end) { size_t sz = m_children.size(); size_t current_cond = 0; size_t nb_cond_to_test = sz; while (REALM_LIKELY(start < end)) { size_t m = m_children[current_cond]->find_first_local(start, end); if (m != start) { // Pointer advanced - we will have to check all other conditions nb_cond_to_test = sz; start = m; } nb_cond_to_test--; // Optimized for one condition where this will be true first time if (REALM_LIKELY(nb_cond_to_test == 0)) return m; current_cond++; if (current_cond == sz) current_cond = 0; } return not_found; } bool ParentNode::match(ConstObj& obj) { auto cb = [this](const Cluster* cluster, size_t row) { set_cluster(cluster); size_t m = find_first(row, row + 1); return m != npos; }; return obj.evaluate(cb); } template <Action action> void ParentNode::aggregate_local_prepare(DataType col_id, bool nullable) { switch (col_id) { case type_Int: { if (nullable) m_column_action_specializer = &ThisType::column_action_specialization<action, ArrayIntNull>; else m_column_action_specializer = &ThisType::column_action_specialization<action, ArrayInteger>; break; } case type_Float: m_column_action_specializer = &ThisType::column_action_specialization<action, ArrayFloat>; break; case type_Double: m_column_action_specializer = &ThisType::column_action_specialization<action, ArrayDouble>; break; case type_Decimal: m_column_action_specializer = &ThisType::column_action_specialization<action, ArrayDecimal128>; break; default: REALM_ASSERT(false); break; } } void ParentNode::aggregate_local_prepare(Action TAction, DataType col_id, bool nullable) { switch (TAction) { case act_ReturnFirst: { if (nullable) m_column_action_specializer = &ThisType::column_action_specialization<act_ReturnFirst, ArrayIntNull>; else m_column_action_specializer = &ThisType::column_action_specialization<act_ReturnFirst, ArrayInteger>; break; } case act_FindAll: { // For find_all(), the column below is a dummy and the caller sets it to nullptr. Hence, no data is being // read from any column upon each query match (just matchcount++ is performed), and we pass nullable = // false simply by convention. FIXME: Clean up all this. REALM_ASSERT(!nullable); m_column_action_specializer = &ThisType::column_action_specialization<act_FindAll, ArrayInteger>; break; } case act_Count: { // For count(), the column below is a dummy and the caller sets it to nullptr. Hence, no data is being // read from any column upon each query match (just matchcount++ is performed), and we pass nullable = // false simply by convention. FIXME: Clean up all this. REALM_ASSERT(!nullable); m_column_action_specializer = &ThisType::column_action_specialization<act_Count, ArrayInteger>; break; } case act_Sum: { aggregate_local_prepare<act_Sum>(col_id, nullable); break; } case act_Min: { aggregate_local_prepare<act_Min>(col_id, nullable); break; } case act_Max: { aggregate_local_prepare<act_Max>(col_id, nullable); break; } case act_CallbackIdx: { // Future features where for each query match, you want to perform an action that only requires knowlege // about the row index, and not the payload there. Examples could be find_all(), however, this code path // below is for new features given in a callback method and not yet supported by core. if (nullable) m_column_action_specializer = &ThisType::column_action_specialization<act_CallbackIdx, ArrayIntNull>; else m_column_action_specializer = &ThisType::column_action_specialization<act_CallbackIdx, ArrayInteger>; break; } default: REALM_ASSERT(false); break; } } size_t ParentNode::aggregate_local(QueryStateBase* st, size_t start, size_t end, size_t local_limit, ArrayPayload* source_column) { // aggregate called on non-integer column type. Speed of this function is not as critical as speed of the // integer version, because find_first_local() is relatively slower here (because it's non-integers). // // Todo: Two speedups are possible. Simple: Initially test if there are no sub criterias and run // find_first_local() // in a tight loop if so (instead of testing if there are sub criterias after each match). Harder: Specialize // data type array to make array call match() directly on each match, like for integers. m_state = st; size_t local_matches = 0; size_t r = start - 1; for (;;) { if (local_matches == local_limit) { m_dD = double(r - start) / (local_matches + 1.1); return r + 1; } // Find first match in this condition node r = find_first_local(r + 1, end); if (r == not_found) { m_dD = double(r - start) / (local_matches + 1.1); return end; } local_matches++; // Find first match in remaining condition nodes size_t m = r; for (size_t c = 1; c < m_children.size(); c++) { m = m_children[c]->find_first_local(r, r + 1); if (m != r) { break; } } // If index of first match in this node equals index of first match in all remaining nodes, we have a final // match if (m == r) { bool cont = (this->*m_column_action_specializer)(st, source_column, r); if (!cont) { return static_cast<size_t>(-1); } } } } void StringNodeEqualBase::init(bool will_query_ranges) { m_dD = 10.0; StringNodeBase::init(will_query_ranges); if (m_is_string_enum) { m_dT = 1.0; } else if (m_has_search_index) { m_dT = 0.0; } else { m_dT = 10.0; } if (m_has_search_index) { // Will set m_index_matches, m_index_matches_destroy, m_results_start and m_results_end _search_index_init(); } } size_t StringNodeEqualBase::find_first_local(size_t start, size_t end) { REALM_ASSERT(m_table); if (m_has_search_index) { if (start < end) { ObjKey first_key = m_cluster->get_real_key(start); if (first_key < m_last_start_key) { // We are not advancing through the clusters. We basically don't know where we are, // so just start over from the beginning. m_results_ndx = m_results_start; m_actual_key = get_key(m_results_ndx); } m_last_start_key = first_key; // Check if we can expect to find more keys if (m_results_ndx < m_results_end) { // Check if we should advance to next key to search for while (first_key > m_actual_key) { m_results_ndx++; if (m_results_ndx == m_results_end) { return not_found; } m_actual_key = get_key(m_results_ndx); } // If actual_key is bigger than last key, it is not in this leaf ObjKey last_key = m_cluster->get_real_key(end - 1); if (m_actual_key > last_key) return not_found; // Now actual_key must be found in leaf keys return m_cluster->lower_bound_key(ObjKey(m_actual_key.value - m_cluster->get_offset())); } } return not_found; } return _find_first_local(start, end); } namespace realm { void StringNode<Equal>::_search_index_init() { FindRes fr; InternalFindResult res; m_last_start_key = ObjKey(); m_results_start = 0; if (ParentNode::m_table->get_primary_key_column() == ParentNode::m_condition_column_key) { m_actual_key = ParentNode::m_table.unchecked_ptr()->find_first(ParentNode::m_condition_column_key, StringData(StringNodeBase::m_value)); m_results_end = m_actual_key ? 1 : 0; } else { auto index = ParentNode::m_table.unchecked_ptr()->get_search_index(ParentNode::m_condition_column_key); fr = index->find_all_no_copy(StringData(StringNodeBase::m_value), res); m_index_matches.reset(); switch (fr) { case FindRes_single: m_actual_key = ObjKey(res.payload); m_results_end = 1; break; case FindRes_column: m_index_matches.reset( new IntegerColumn(m_table.unchecked_ptr()->get_alloc(), ref_type(res.payload))); // Throws m_results_start = res.start_ndx; m_results_end = res.end_ndx; m_actual_key = ObjKey(m_index_matches->get(m_results_start)); break; case FindRes_not_found: m_results_end = 0; break; } } m_results_ndx = m_results_start; } bool StringNode<Equal>::do_consume_condition(ParentNode& node) { // Don't use the search index if present since we're in a scenario where // it'd be slower m_has_search_index = false; auto& other = static_cast<StringNode<Equal>&>(node); REALM_ASSERT(m_condition_column_key == other.m_condition_column_key); REALM_ASSERT(other.m_needles.empty()); if (m_needles.empty()) { m_needles.insert(m_value ? StringData(*m_value) : StringData()); } if (auto& str = other.m_value) { m_needle_storage.push_back(std::make_unique<char[]>(str->size())); std::copy(str->data(), str->data() + str->size(), m_needle_storage.back().get()); m_needles.insert(StringData(m_needle_storage.back().get(), str->size())); } else { m_needles.emplace(); } return true; } size_t StringNode<Equal>::_find_first_local(size_t start, size_t end) { if (m_needles.empty()) { return m_leaf_ptr->find_first(m_value, start, end); } else { if (end == npos) end = m_leaf_ptr->size(); REALM_ASSERT_3(start, <=, end); return find_first_haystack<20>(*m_leaf_ptr, m_needles, start, end); } } std::string StringNode<Equal>::describe(util::serializer::SerialisationState& state) const { if (m_needles.empty()) { return StringNodeEqualBase::describe(state); } // FIXME: once the parser supports it, print something like "column IN {s1, s2, s3}" std::string desc; bool is_first = true; for (auto it : m_needles) { StringData sd(it.data(), it.size()); desc += (is_first ? "" : " or ") + state.describe_column(ParentNode::m_table, m_condition_column_key) + " " + Equal::description() + " " + util::serializer::print_value(sd); is_first = false; } if (!is_first) { desc = "(" + desc + ")"; } return desc; } void StringNode<EqualIns>::_search_index_init() { auto index = ParentNode::m_table->get_search_index(ParentNode::m_condition_column_key); m_index_matches.clear(); index->find_all(m_index_matches, StringData(StringNodeBase::m_value), true); m_results_start = 0; m_results_ndx = 0; m_results_end = m_index_matches.size(); if (m_results_start != m_results_end) { m_actual_key = m_index_matches[0]; } } size_t StringNode<EqualIns>::_find_first_local(size_t start, size_t end) { EqualIns cond; for (size_t s = start; s < end; ++s) { StringData t = get_string(s); if (cond(StringData(m_value), m_ucase.c_str(), m_lcase.c_str(), t)) return s; } return not_found; } } // namespace realm size_t NotNode::find_first_local(size_t start, size_t end) { if (start <= m_known_range_start && end >= m_known_range_end) { return find_first_covers_known(start, end); } else if (start >= m_known_range_start && end <= m_known_range_end) { return find_first_covered_by_known(start, end); } else if (start < m_known_range_start && end >= m_known_range_start) { return find_first_overlap_lower(start, end); } else if (start <= m_known_range_end && end > m_known_range_end) { return find_first_overlap_upper(start, end); } else { // start > m_known_range_end || end < m_known_range_start return find_first_no_overlap(start, end); } } bool NotNode::evaluate_at(size_t rowndx) { return m_condition->find_first(rowndx, rowndx + 1) == not_found; } void NotNode::update_known(size_t start, size_t end, size_t first) { m_known_range_start = start; m_known_range_end = end; m_first_in_known_range = first; } size_t NotNode::find_first_loop(size_t start, size_t end) { for (size_t i = start; i < end; ++i) { if (evaluate_at(i)) { return i; } } return not_found; } size_t NotNode::find_first_covers_known(size_t start, size_t end) { // CASE: start-end covers the known range // [ ###### ] REALM_ASSERT_DEBUG(start <= m_known_range_start && end >= m_known_range_end); size_t result = find_first_loop(start, m_known_range_start); if (result != not_found) { update_known(start, m_known_range_end, result); } else { if (m_first_in_known_range != not_found) { update_known(start, m_known_range_end, m_first_in_known_range); result = m_first_in_known_range; } else { result = find_first_loop(m_known_range_end, end); update_known(start, end, result); } } return result; } size_t NotNode::find_first_covered_by_known(size_t start, size_t end) { REALM_ASSERT_DEBUG(start >= m_known_range_start && end <= m_known_range_end); // CASE: the known range covers start-end // ###[#####]### if (m_first_in_known_range != not_found) { if (m_first_in_known_range > end) { return not_found; } else if (m_first_in_known_range >= start) { return m_first_in_known_range; } } // The first known match is before start, so we can't use the results to improve // heuristics. return find_first_loop(start, end); } size_t NotNode::find_first_overlap_lower(size_t start, size_t end) { REALM_ASSERT_DEBUG(start < m_known_range_start && end >= m_known_range_start && end <= m_known_range_end); static_cast<void>(end); // CASE: partial overlap, lower end // [ ###]##### size_t result; result = find_first_loop(start, m_known_range_start); if (result == not_found) { result = m_first_in_known_range; } update_known(start, m_known_range_end, result); return result < end ? result : not_found; } size_t NotNode::find_first_overlap_upper(size_t start, size_t end) { REALM_ASSERT_DEBUG(start <= m_known_range_end && start >= m_known_range_start && end > m_known_range_end); // CASE: partial overlap, upper end // ####[### ] size_t result; if (m_first_in_known_range != not_found) { if (m_first_in_known_range >= start) { result = m_first_in_known_range; update_known(m_known_range_start, end, result); } else { result = find_first_loop(start, end); update_known(m_known_range_start, end, m_first_in_known_range); } } else { result = find_first_loop(m_known_range_end, end); update_known(m_known_range_start, end, result); } return result; } size_t NotNode::find_first_no_overlap(size_t start, size_t end) { REALM_ASSERT_DEBUG((start < m_known_range_start && end < m_known_range_start) || (start > m_known_range_end && end > m_known_range_end)); // CASE: no overlap // ### [ ] or [ ] #### // if input is a larger range, discard and replace with results. size_t result = find_first_loop(start, end); if (end - start > m_known_range_end - m_known_range_start) { update_known(start, end, result); } return result; } ExpressionNode::ExpressionNode(std::unique_ptr<Expression> expression) : m_expression(std::move(expression)) { m_dD = 100.0; m_dT = 50.0; } void ExpressionNode::table_changed() { m_expression->set_base_table(m_table); } void ExpressionNode::cluster_changed() { m_expression->set_cluster(m_cluster); } void ExpressionNode::init(bool will_query_ranges) { ParentNode::init(will_query_ranges); m_dT = m_expression->init(); } std::string ExpressionNode::describe(util::serializer::SerialisationState& state) const { if (m_expression) { return m_expression->description(state); } else { return "empty expression"; } } void ExpressionNode::collect_dependencies(std::vector<TableKey>& tables) const { m_expression->collect_dependencies(tables); } size_t ExpressionNode::find_first_local(size_t start, size_t end) { return m_expression->find_first(start, end); } std::unique_ptr<ParentNode> ExpressionNode::clone() const { return std::unique_ptr<ParentNode>(new ExpressionNode(*this)); } ExpressionNode::ExpressionNode(const ExpressionNode& from) : ParentNode(from) , m_expression(from.m_expression->clone()) { }
33.023932
117
0.623635
[ "vector" ]
84db811f4ecd85290163ef47866a165722f954f8
8,289
cpp
C++
extensions/arduino/sensor/tcs3200/lib/MD_TCS230/src/MD_TCS230.cpp
Suku1989/external-resources
5d2b8fba60556d325cd31d29caa02508885910be
[ "MIT" ]
1
2019-12-27T09:41:37.000Z
2019-12-27T09:41:37.000Z
extensions/arduino/sensor/tcs3200/lib/MD_TCS230/src/MD_TCS230.cpp
Suku1989/external-resources
5d2b8fba60556d325cd31d29caa02508885910be
[ "MIT" ]
6
2022-03-08T04:11:48.000Z
2022-03-11T05:46:05.000Z
extensions/arduino/sensor/tcs3200/lib/MD_TCS230/src/MD_TCS230.cpp
Suku1989/external-resources
5d2b8fba60556d325cd31d29caa02508885910be
[ "MIT" ]
8
2022-01-19T18:15:39.000Z
2022-03-26T06:07:17.000Z
/* MD_TCS230.h - Arduino library for TCS230 Colour Sensor. Copyright (C) 2013 Marco Colli All rights reserved. See main header file for complete comments */ #include <MD_TCS230.h> /** * \file * \brief Main class definition file for the MD_TCS230 library */ #define DEBUG_TCS230 0 ///< Debug flag. Set to 1 to enable debug output to Serial. #if DEBUG_TCS230 #define DUMP(s, v) { Serial.print(F(s)); Serial.print(v); } ///< Debug label + value #define DUMPS(s) { Serial.print(F(s)); } ///< Debug label only #else #define DUMP(s, v) ///< Debug label + value #define DUMPS(s) ///< Debug label only #endif void MD_TCS230::initialise(void) // initialize all object variables { _OE = NO_PIN; _S0 = NO_PIN; _S1 = NO_PIN; _S2 = NO_PIN; _S3 = NO_PIN; _readDiv = 10; _freqSet = TCS230_FREQ_HI; for (uint8_t i=0; i<RGB_SIZE; i++) { _Fd.value[i] = 6000L; // just typical numbers read by a sensor to ensure ... _Fw.value[i] = 55000L; // ... something sensible is returned with no calibration } } MD_TCS230::MD_TCS230(uint8_t s2, uint8_t s3) { initialise(); _S2 = s2; _S3 = s3; } MD_TCS230::MD_TCS230(uint8_t s2, uint8_t s3, uint8_t oe) { initialise(); _S2 = s2; _S3 = s3; _OE = oe; } MD_TCS230::MD_TCS230(uint8_t s2, uint8_t s3, uint8_t s0, uint8_t s1) { initialise(); _S0 = s0; _S1 = s1; _S2 = s2; _S3 = s3; } MD_TCS230::MD_TCS230(uint8_t s2, uint8_t s3, uint8_t s0, uint8_t s1, uint8_t oe) { initialise(); _S0 = s0; _S1 = s1; _S2 = s2; _S3 = s3; _OE = oe; } MD_TCS230::~MD_TCS230(void) { } void MD_TCS230::begin() { if (_S0 != NO_PIN) pinMode(_S0, OUTPUT); if (_S1 != NO_PIN) pinMode(_S1, OUTPUT); if (_S2 != NO_PIN) pinMode(_S2, OUTPUT); if (_S3 != NO_PIN) pinMode(_S3, OUTPUT); if (_OE != NO_PIN) pinMode(_OE, OUTPUT); setEnable(false); setFrequency2(_freqSet); #undef SET_OUTPUT DUMPS("\nLibrary begin initialised"); } void MD_TCS230::setFilter(uint8_t f) // set the sensor color filter { if ((_S2 == NO_PIN) || (_S3 == NO_PIN)) return; DUMPS("\nsetFilter "); switch (f) { case TCS230_RGB_R: DUMPS("R"); digitalWrite(_S2, LOW); digitalWrite(_S3, LOW); break; case TCS230_RGB_G: DUMPS("G"); digitalWrite(_S2, HIGH); digitalWrite(_S3, HIGH); break; case TCS230_RGB_B: DUMPS("B"); digitalWrite(_S2, LOW); digitalWrite(_S3, HIGH); break; case TCS230_RGB_X: DUMPS("X"); digitalWrite(_S2, HIGH); digitalWrite(_S3, LOW); break; default: DUMP("Unknown filter option", f); break; } } void MD_TCS230::setFrequency2(uint8_t f) // set the sensor frequency prescaler (internal function only) { if ((_S0 == NO_PIN) || (_S1 == NO_PIN)) return; DUMPS("\nsetFrequency "); switch (f) { case TCS230_FREQ_HI: DUMPS("HI"); digitalWrite(_S0, HIGH); digitalWrite(_S1, HIGH); break; case TCS230_FREQ_MID: DUMPS("MID"); digitalWrite(_S0, HIGH); digitalWrite(_S1, LOW); break; case TCS230_FREQ_LO: DUMPS("LO"); digitalWrite(_S0, LOW); digitalWrite(_S1, HIGH); break; case TCS230_FREQ_OFF: DUMPS("OFF"); digitalWrite(_S0, LOW); digitalWrite(_S1, LOW); break; default: DUMP("Unknown freq option", f); break; } } void MD_TCS230::setFrequency(uint8_t f) // set the sensor frequency prescaler (user function) // saves the value the user sets so we can return to it { _freqSet = f; setFrequency2(f); } void MD_TCS230::setSampling(uint8_t t) // set sampling rate divisor for frequency counter { _readDiv = (t > 0 ? t : _readDiv); } void MD_TCS230::setEnable(bool b) // enable the sensor output (b=true) // can be done by toggling OE (preferred) or by setting the frequency output { if (b) DUMPS("\nEn"); else DUMPS("\nDis"); DUMPS("abling using "); if (_OE != NO_PIN) { DUMPS("OE"); digitalWrite(_OE, (b) ? LOW : HIGH); // reverse logic } else { DUMPS("FREQ"); setFrequency2((b) ? _freqSet : TCS230_FREQ_OFF); } } void MD_TCS230::setDarkCal(sensorData *d) // set dark calibration data for rgb calculations { if (d == NULL) return; DUMPS("\nsetDarkCal"); for (uint8_t i=0; i<RGB_SIZE; i++) { DUMP(" ", d->value[i]); _Fd.value[i] = d->value[i]; } } void MD_TCS230::setWhiteCal(sensorData *d) // set white calibration data for rgb calculations { if (d == NULL) return; DUMPS("\nsetWhiteCal"); for (uint8_t i=0; i<RGB_SIZE; i++) { DUMP(" ", d->value[i]); _Fw.value[i] = d->value[i]; } } void MD_TCS230::getRGB(colorData *rgb) // get the rgb value of the current reading { if (rgb == NULL) return; DUMPS("\ngetRGB"); for (uint8_t i=0; i<RGB_SIZE; i++) { rgb->value[i] = _rgb.value[i]; DUMP(" ", rgb->value[i]); } } void MD_TCS230::getRaw(sensorData *d) // get the raw data of the current reading // useful to set dark and white calibration data { if (d == NULL) return; DUMPS("\ngetRAW"); for (uint8_t i=0; i<RGB_SIZE; i++) { d->value[i] = _Fo.value[i]; DUMP(" ", d->value[i]); } } uint32_t MD_TCS230::readSingle(void) // blocking read of a single sensor value (ie, not rgb) { DUMPS("\nreadSingle"); FreqCount.begin(1000/_readDiv); // start while (!FreqCount.available()) // wait { DUMPS("."); } FreqCount.end(); // stop DUMP("VALUE ", FreqCount.read()); return(FreqCount.read() * _readDiv); } void MD_TCS230::read(void) // initiate the finite state machine for reading a value { _readState = readFSM(0); } bool MD_TCS230::available(void) // check if a value is ready. Called repeatedly until it is! { _readState = readFSM(_readState); return(_readState == 0); } uint8_t MD_TCS230::readFSM(uint8_t s) // Finite State Machine to read a value (internal function) { static const uint8_t seq[] = { TCS230_RGB_R, TCS230_RGB_G, TCS230_RGB_B }; static uint8_t currCol; // index for seq above switch(s) { case 0: // enable the hardware for reading DUMPS("\n0"); currCol = 0; // RGB_R but we don't care setEnable(true); s++; // fall through to the next state case 1: // select a filter and start a reading DUMPS("\n1"); setFilter(seq[currCol]); FreqCount.begin(1000/_readDiv); s++; break; case 2: // see if a value is available DUMPS("2"); if (FreqCount.available()) { DUMP(" VALUE ", FreqCount.read()); // read the value and save it _Fo.value[seq[currCol++]] = FreqCount.read() * _readDiv; if (currCol < RGB_SIZE) { // loop around again on next call to available() s--; } else { // end this reading session FreqCount.end(); setEnable(false); RGBTransformation(); s = 0; } } break; } return(s); } void MD_TCS230::RGBTransformation(void) // Exploiting linear relationship to remap the range { int32_t x; for (uint8_t i=0; i<RGB_SIZE; i++) { x = (_Fo.value[i] - _Fd.value[i]) * 255; x /= (_Fw.value[i] - _Fd.value[i]); // copy results back into the global structures if (x < 0) _rgb.value[i] = 0; else if (x > 255) _rgb.value[i] = 255; else _rgb.value[i] = x; } } /* void RGBTransformation(void) // complex transformation that does not seem to be // much better than the simpler one above { float v; // the results float inRGB[3]; // values read const float T[3][3] = { // transformation matrix { 0.7659, 0.7052, -0.4990 }, {-0.3140, 1.3283, -0.1367 }, { 0.0609, -0.4739, 1.0326 }}; // set up the inRGB array with the values read, adjusted by the // calibration parameters for (uint8_t i=0; i<RGB_SIZE; i++) { inRGB[i] = (float)_Fo.value[i] - (float)_Fd.value[i]; inRGB[i] /= (((float)_Fw.value[i] - (float)_Fd.value[i]) / 255.0); DUMP("\ninRGB[", i); DUMP("] = ", inRGB[i]); } // Carry out the matrix multiplication // [outRGB] = [T] . [inRGB] for (uint8_t i = 0; i < 3; i++) { v = 0.0; for (uint8_t j = 0; j < 3; j++) { v += T[i][j] * inRGB[j]; } DUMP("\nTransformed result for ", (char)SR[i].type); DUMP(" = ", v); // copy results back into the global structures if (v < 0.0) _rgb.value[i] = 0; else if (v > 255.0) _rgb.value[i] = 255; else _rgb.value[i] = trunc(v + 0.5); } } */
23.025
96
0.617083
[ "object" ]
84de1e8884620ee993206a140831be428a7ca44d
8,616
cpp
C++
compiler/locop/src/FormattedGraph.cpp
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
compiler/locop/src/FormattedGraph.cpp
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
compiler/locop/src/FormattedGraph.cpp
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "locop/FormattedGraph.h" #include "locop/FormattedTensorShape.h" #include "locop/GenericNodeSummaryBuilder.h" #include <loco/Service/TypeInference.h> #include <loco/Service/ShapeInference.h> #include <pp/Format.h> #include <stdex/Memory.h> #include <map> #include <set> #include <cassert> using locop::SymbolTable; namespace { std::string str(const loco::DataType &dtype) { switch (dtype) { case loco::DataType::Unknown: return "Unknown"; case loco::DataType::U8: return "U8"; case loco::DataType::U16: return "U16"; case loco::DataType::U32: return "U32"; case loco::DataType::U64: return "U64"; case loco::DataType::S8: return "S8"; case loco::DataType::S16: return "S16"; case loco::DataType::S32: return "S32"; case loco::DataType::S64: return "S64"; case loco::DataType::FLOAT16: return "FLOAT16"; case loco::DataType::FLOAT32: return "FLOAT32"; case loco::DataType::FLOAT64: return "FLOAT64"; default: break; }; throw std::invalid_argument{"dtype"}; } std::string str(const loco::Domain &domain) { // TODO Generate! switch (domain) { case loco::Domain::Unknown: return "Unknown"; case loco::Domain::Tensor: return "Tensor"; case loco::Domain::Feature: return "Feature"; case loco::Domain::Filter: return "Filter"; case loco::Domain::DepthwiseFilter: return "DWFilter"; case loco::Domain::Bias: return "Bias"; default: break; } throw std::invalid_argument{"domain"}; } std::string str(const loco::NodeShape &node_shape) { using namespace locop; switch (node_shape.domain()) { case loco::Domain::Tensor: { auto tensor_shape = node_shape.as<loco::TensorShape>(); return pp::fmt(locop::fmt<TensorShapeFormat::Plain>(&tensor_shape)); } // TODO Show details case loco::Domain::Feature: case loco::Domain::Filter: case loco::Domain::DepthwiseFilter: case loco::Domain::Bias: return "..."; default: break; } throw std::invalid_argument{"domain"}; } // TODO Use locop::fmt<TensorShapeFormat ...> locop::FormattedTensorShape<locop::TensorShapeFormat::Bracket> formatted_tensor_shape(const loco::TensorShape *ptr) { return locop::FormattedTensorShape<locop::TensorShapeFormat::Bracket>{ptr}; } } // namespace namespace { struct NodeDesc : public locop::NodeDesc { public: NodeDesc() = default; NodeDesc(const locop::OpName &opname) : locop::NodeDesc{opname} { // DO NOTHING } public: // DEPRECATED const locop::OpName &name(void) const { return opname(); } // DEPRECATED uint32_t arg_size(void) const { return args().count(); } // DEPRECATED const locop::ArgElem &arg(uint32_t n) const { return args().at(n); } // DEPRECATED void arg(const locop::ArgName &name, const locop::ArgValue &value) { args().append(name, value); } }; } // namespace // TODO Remove this workaround namespace locop { std::ostream &operator<<(std::ostream &os, const NodeDesc &d) { assert(d.state() != NodeDesc::State::Invalid); std::vector<std::string> values; for (uint32_t n = 0; n < d.args().count(); ++n) { values.emplace_back(d.args().at(n).first + ": " + d.args().at(n).second); } if (d.state() == NodeDesc::State::PartiallyKnown) { values.emplace_back("..."); } os << d.opname(); os << "("; if (values.size() > 0) { os << values.at(0); for (uint32_t n = 1; n < values.size(); ++n) { os << ", " << values.at(n); } } os << ")"; return os; } } // namespace locop namespace locop { std::ostream &operator<<(std::ostream &os, const FormattedGraph &fmt) { fmt.dump(os); return os; } } // namespace locop namespace locop { void FormattedGraphImpl<Formatter::LinearV1>::dump(std::ostream &os) const { struct SymbolTableImpl final : public SymbolTable { std::string lookup(const loco::Node *node) const final { if (node == nullptr) { return "(null)"; } return _content.at(node); } std::map<const loco::Node *, std::string> _content; }; SymbolTableImpl symbols; auto symbol = [&symbols](const loco::Node *node) { return symbols.lookup(node); }; for (uint32_t n = 0; n < _graph->nodes()->size(); ++n) { symbols._content[_graph->nodes()->at(n)] = pp::fmt("%", n); } // Find the disjoint node clusters // // TODO Move this implementation into loco Algorithms.h std::map<loco::Node *, loco::Node *> parents; for (auto node : loco::all_nodes(_graph)) { parents[node] = nullptr; } for (auto node : loco::all_nodes(_graph)) { for (uint32_t n = 0; n < node->arity(); ++n) { if (auto arg = node->arg(n)) { parents[arg] = node; } } } auto find = [&parents](loco::Node *node) { loco::Node *cur = node; while (parents.at(cur) != nullptr) { cur = parents.at(cur); } return cur; }; std::set<loco::Node *> roots; for (auto node : loco::all_nodes(_graph)) { roots.insert(find(node)); } std::map<loco::Node *, std::set<loco::Node *>> clusters; // Create clusters for (auto root : roots) { clusters[root] = std::set<loco::Node *>{}; } for (auto node : loco::all_nodes(_graph)) { clusters.at(find(node)).insert(node); } std::unique_ptr<locop::NodeSummaryBuilder> node_summary_builder; if (_factory) { // Use User-defined NodeSummaryBuilder if NodeSummaryBuilderFactory is present node_summary_builder = _factory->create(&symbols); } else { // Use Built-in NodeSummaryBuilder otherwise node_summary_builder = stdex::make_unique<GenericNodeSummaryBuilder>(&symbols); } // Print Graph Input(s) for (uint32_t n = 0; n < _graph->inputs()->size(); ++n) { auto input = _graph->inputs()->at(n); std::string name = input->name(); std::string shape = "?"; if (input->shape() != nullptr) { shape = pp::fmt(formatted_tensor_shape(input->shape())); } // TODO Print dtype os << pp::fmt("In #", n, " { name: ", name, ", shape: ", shape, " }") << std::endl; } // Print Graph Output(s) for (uint32_t n = 0; n < _graph->outputs()->size(); ++n) { auto output = _graph->outputs()->at(n); std::string name = output->name(); std::string shape = "?"; if (output->shape() != nullptr) { shape = pp::fmt(formatted_tensor_shape(output->shape())); } // TODO Print dtype os << pp::fmt("Out #", n, " { name: ", name, ", shape: ", shape, " }") << std::endl; } if (_graph->inputs()->size() + _graph->outputs()->size() != 0) { os << std::endl; } for (auto it = clusters.begin(); it != clusters.end(); ++it) { std::vector<loco::Node *> cluster_outputs; for (auto node : it->second) { // NOTE This is inefficient but anyway working :) if (loco::succs(node).empty()) { cluster_outputs.emplace_back(node); } } for (auto node : loco::postorder_traversal(cluster_outputs)) { locop::NodeSummary node_summary; // Build a node summary if (!node_summary_builder->build(node, node_summary)) { throw std::runtime_error{"Fail to build a node summary"}; } for (uint32_t n = 0; n < node_summary.comments().count(); ++n) { os << "; " << node_summary.comments().at(n) << std::endl; } os << symbol(node); if (loco::shape_known(node)) { auto node_shape = loco::shape_get(node); os << " : " << str(node_shape.domain()); os << "<"; os << str(node_shape); os << ", "; // Show DataType os << (loco::dtype_known(node) ? str(loco::dtype_get(node)) : std::string{"?"}); os << ">"; } os << " = " << node_summary << std::endl; } os << std::endl; } } } // namespace locop
22.035806
100
0.603296
[ "shape", "vector" ]
84df57d297dc431d66e407914e098fa558d7e45d
4,717
cpp
C++
modules/text/samples/text_recognition_cnn.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/text/samples/text_recognition_cnn.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/text/samples/text_recognition_cnn.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
#include <opencv2/text.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/dnn.hpp> #include <iostream> #include <fstream> using namespace cv; using namespace std; namespace { void printHelpStr(const string& progFname) { cout << " Demo of text recognition CNN for text detection." << endl << " Max Jaderberg et al.: Reading Text in the Wild with Convolutional Neural Networks, IJCV 2015"<<endl<<endl << " Usage: " << progFname << " <output_file> <input_image>" << endl << " Caffe Model files (textbox.prototxt, TextBoxes_icdar13.caffemodel)"<<endl << " must be in the current directory. See the documentation of text::TextDetectorCNN class to get download links." << endl << " Obtaining text recognition Caffe Model files in linux shell:" << endl << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg.caffemodel" << endl << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg_deploy.prototxt" << endl << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg_labels.txt" <<endl << endl; } bool fileExists (const string& filename) { ifstream f(filename.c_str()); return f.good(); } void textbox_draw(Mat src, std::vector<Rect>& groups, std::vector<float>& probs, std::vector<int>& indexes) { for (size_t i = 0; i < indexes.size(); i++) { if (src.type() == CV_8UC3) { Rect currrentBox = groups[indexes[i]]; rectangle(src, currrentBox, Scalar( 0, 255, 255 ), 2, LINE_AA); String label = format("%.2f", probs[indexes[i]]); std::cout << "text box: " << currrentBox << " confidence: " << probs[indexes[i]] << "\n"; int baseLine = 0; Size labelSize = getTextSize(label, FONT_HERSHEY_PLAIN, 1, 1, &baseLine); int yLeftBottom = std::max(currrentBox.y, labelSize.height); rectangle(src, Point(currrentBox.x, yLeftBottom - labelSize.height), Point(currrentBox.x + labelSize.width, yLeftBottom + baseLine), Scalar( 255, 255, 255 ), FILLED); putText(src, label, Point(currrentBox.x, yLeftBottom), FONT_HERSHEY_PLAIN, 1, Scalar( 0,0,0 ), 1, LINE_AA); } else rectangle(src, groups[i], Scalar( 255 ), 3, 8 ); } } } int main(int argc, const char * argv[]) { if (argc < 2) { printHelpStr(argv[0]); cout << "Insufiecient parameters. Aborting!" << endl; exit(1); } const string modelArch = "textbox.prototxt"; const string moddelWeights = "TextBoxes_icdar13.caffemodel"; if (!fileExists(modelArch) || !fileExists(moddelWeights)) { printHelpStr(argv[0]); cout << "Model files not found in the current directory. Aborting!" << endl; exit(1); } Mat image = imread(String(argv[1]), IMREAD_COLOR); cout << "Starting Text Box Demo" << endl; Ptr<text::TextDetectorCNN> textSpotter = text::TextDetectorCNN::create(modelArch, moddelWeights); vector<Rect> bbox; vector<float> outProbabillities; textSpotter->detect(image, bbox, outProbabillities); std::vector<int> indexes; cv::dnn::NMSBoxes(bbox, outProbabillities, 0.4f, 0.5f, indexes); Mat image_copy = image.clone(); textbox_draw(image_copy, bbox, outProbabillities, indexes); imshow("Text detection", image_copy); image_copy = image.clone(); Ptr<text::OCRHolisticWordRecognizer> wordSpotter = text::OCRHolisticWordRecognizer::create("dictnet_vgg_deploy.prototxt", "dictnet_vgg.caffemodel", "dictnet_vgg_labels.txt"); for(size_t i = 0; i < indexes.size(); i++) { Mat wordImg; cvtColor(image(bbox[indexes[i]]), wordImg, COLOR_BGR2GRAY); string word; vector<float> confs; wordSpotter->run(wordImg, word, NULL, NULL, &confs); Rect currrentBox = bbox[indexes[i]]; rectangle(image_copy, currrentBox, Scalar( 0, 255, 255 ), 2, LINE_AA); int baseLine = 0; Size labelSize = getTextSize(word, FONT_HERSHEY_PLAIN, 1, 1, &baseLine); int yLeftBottom = std::max(currrentBox.y, labelSize.height); rectangle(image_copy, Point(currrentBox.x, yLeftBottom - labelSize.height), Point(currrentBox.x + labelSize.width, yLeftBottom + baseLine), Scalar( 255, 255, 255 ), FILLED); putText(image_copy, word, Point(currrentBox.x, yLeftBottom), FONT_HERSHEY_PLAIN, 1, Scalar( 0,0,0 ), 1, LINE_AA); } imshow("Text recognition", image_copy); cout << "Recognition finished. Press any key to exit.\n"; waitKey(); return 0; }
38.349593
136
0.636845
[ "vector", "model" ]
84eca8a4dd9c8a00cbc43f890e96afad882d827b
18,899
cpp
C++
Tut 14 Textures Are Not Pictures/Material Texture.cpp
bluesrv/LM3DGP-Tutorial
5ae98629cf4e6ed62a81a8f48f6948551ba49d20
[ "MIT" ]
null
null
null
Tut 14 Textures Are Not Pictures/Material Texture.cpp
bluesrv/LM3DGP-Tutorial
5ae98629cf4e6ed62a81a8f48f6948551ba49d20
[ "MIT" ]
null
null
null
Tut 14 Textures Are Not Pictures/Material Texture.cpp
bluesrv/LM3DGP-Tutorial
5ae98629cf4e6ed62a81a8f48f6948551ba49d20
[ "MIT" ]
null
null
null
//Copyright (C) 2010-2012 by Jason L. McKesson //This file is licensed under the MIT License. #include <string> #include <vector> #include <stack> #include <memory> #include <math.h> #include <stdio.h> #include <glload/gl_3_3.h> #include <glimg/glimg.h> #include <glutil/glutil.h> #include <glimg/ImageCreatorExceptions.h> #include <GL/freeglut.h> #include "../framework/framework.h" #include "../framework/Mesh.h" #include "../framework/MousePole.h" #include "../framework/Timer.h" #include "../framework/UniformBlockArray.h" #include "../framework/directories.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #define ARRAY_COUNT( array ) (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)))) struct ProgramData { GLuint theProgram; GLuint modelToCameraMatrixUnif; GLuint normalModelToCameraMatrixUnif; }; struct UnlitProgData { GLuint theProgram; GLuint objectColorUnif; GLuint modelToCameraMatrixUnif; }; float g_fzNear = 1.0f; float g_fzFar = 1000.0f; enum ShaderMode { MODE_FIXED, MODE_TEXTURED, MODE_TEXTURED_COMPUTE, NUM_SHADER_MODES, }; ProgramData g_Programs[NUM_SHADER_MODES]; UnlitProgData g_Unlit; const int g_materialBlockIndex = 0; const int g_lightBlockIndex = 1; const int g_projectionBlockIndex = 2; const int g_gaussTexUnit = 0; const int g_shineTexUnit = 1; UnlitProgData LoadUnlitProgram(const std::string &strVertexShader, const std::string &strFragmentShader) { std::vector<GLuint> shaderList; shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, strVertexShader)); shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, strFragmentShader)); UnlitProgData data; data.theProgram = Framework::CreateProgram(shaderList); data.modelToCameraMatrixUnif = glGetUniformLocation(data.theProgram, "modelToCameraMatrix"); data.objectColorUnif = glGetUniformLocation(data.theProgram, "objectColor"); GLuint projectionBlock = glGetUniformBlockIndex(data.theProgram, "Projection"); glUniformBlockBinding(data.theProgram, projectionBlock, g_projectionBlockIndex); return data; } ProgramData LoadStandardProgram(const std::string &strVertexShader, const std::string &strFragmentShader) { std::vector<GLuint> shaderList; shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, strVertexShader)); shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, strFragmentShader)); ProgramData data; data.theProgram = Framework::CreateProgram(shaderList); data.modelToCameraMatrixUnif = glGetUniformLocation(data.theProgram, "modelToCameraMatrix"); data.normalModelToCameraMatrixUnif = glGetUniformLocation(data.theProgram, "normalModelToCameraMatrix"); GLuint materialBlock = glGetUniformBlockIndex(data.theProgram, "Material"); GLuint lightBlock = glGetUniformBlockIndex(data.theProgram, "Light"); GLuint projectionBlock = glGetUniformBlockIndex(data.theProgram, "Projection"); glUniformBlockBinding(data.theProgram, materialBlock, g_materialBlockIndex); glUniformBlockBinding(data.theProgram, lightBlock, g_lightBlockIndex); glUniformBlockBinding(data.theProgram, projectionBlock, g_projectionBlockIndex); GLuint gaussianTextureUnif = glGetUniformLocation(data.theProgram, "gaussianTexture"); GLuint shininessTextureUnif = glGetUniformLocation(data.theProgram, "shininessTexture"); glUseProgram(data.theProgram); glUniform1i(gaussianTextureUnif, g_gaussTexUnit); glUniform1i(shininessTextureUnif, g_shineTexUnit); glUseProgram(0); return data; } struct ShaderPairs { const char *vertShader; const char *fragShader; }; ShaderPairs g_shaderPairs[NUM_SHADER_MODES] = { {"PN.vert", "FixedShininess.frag"}, {"PNT.vert", "TextureShininess.frag"}, {"PNT.vert", "TextureCompute.frag"}, }; void InitializePrograms() { for(int prog = 0; prog < NUM_SHADER_MODES; prog++) { g_Programs[prog] = LoadStandardProgram(g_shaderPairs[prog].vertShader, g_shaderPairs[prog].fragShader); } g_Unlit = LoadUnlitProgram("Unlit.vert", "Unlit.frag"); } /////////////////////////////////////////////// // View/Object Setup glutil::ObjectData g_initialObjectData = { glm::vec3(0.0f, 0.5f, 0.0f), glm::fquat(1.0f, 0.0f, 0.0f, 0.0f), }; glutil::ViewData g_initialViewData = { g_initialObjectData.position, glm::fquat(0.92387953f, 0.3826834f, 0.0f, 0.0f), 10.0f, 0.0f }; glutil::ViewScale g_viewScale = { 1.5f, 70.0f, 1.5f, 0.5f, 0.0f, 0.0f, //No camera movement. 90.0f/250.0f }; glutil::ViewPole g_viewPole = glutil::ViewPole(g_initialViewData, g_viewScale, glutil::MB_LEFT_BTN); glutil::ObjectPole g_objtPole = glutil::ObjectPole(g_initialObjectData, 90.0f/250.0f, glutil::MB_RIGHT_BTN, &g_viewPole); namespace { void MouseMotion(int x, int y) { Framework::ForwardMouseMotion(g_viewPole, x, y); Framework::ForwardMouseMotion(g_objtPole, x, y); glutPostRedisplay(); } void MouseButton(int button, int state, int x, int y) { Framework::ForwardMouseButton(g_viewPole, button, state, x, y); Framework::ForwardMouseButton(g_objtPole, button, state, x, y); glutPostRedisplay(); } void MouseWheel(int wheel, int direction, int x, int y) { Framework::ForwardMouseWheel(g_viewPole, wheel, direction, x, y); Framework::ForwardMouseWheel(g_objtPole, wheel, direction, x, y); glutPostRedisplay(); } } struct ProjectionBlock { glm::mat4 cameraToClipMatrix; }; struct PerLight { glm::vec4 cameraSpaceLightPos; glm::vec4 lightIntensity; }; const int NUMBER_OF_LIGHTS = 2; struct LightBlock { glm::vec4 ambientIntensity; float lightAttenuation; float padding[3]; PerLight lights[NUMBER_OF_LIGHTS]; }; struct MaterialBlock { glm::vec4 diffuseColor; glm::vec4 specularColor; float specularShininess; float padding[3]; }; Framework::Mesh *g_pObjectMesh = NULL; Framework::Mesh *g_pCubeMesh = NULL; Framework::Mesh *g_pPlaneMesh = NULL; GLuint g_lightUniformBuffer = 0; GLuint g_projectionUniformBuffer = 0; GLuint g_materialUniformBuffer = 0; int g_materialOffset = 0; const int NUM_GAUSS_TEXTURES = 4; GLuint g_gaussTextures[NUM_GAUSS_TEXTURES]; GLuint g_textureSampler = 0; GLuint g_imposterVAO; GLuint g_imposterVBO; void BuildGaussianData(std::vector<GLubyte> &textureData, int cosAngleResolution, int shininessResolution) { textureData.resize(shininessResolution * cosAngleResolution); std::vector<unsigned char>::iterator currIt = textureData.begin(); for(int iShin = 1; iShin <= shininessResolution; iShin++) { float shininess = iShin / (float)(shininessResolution); for(int iCosAng = 0; iCosAng < cosAngleResolution; iCosAng++) { float cosAng = iCosAng / (float)(cosAngleResolution - 1); float angle = acosf(cosAng); float exponent = angle / shininess; exponent = -(exponent * exponent); float gaussianTerm = glm::exp(exponent); *currIt = (unsigned char)(gaussianTerm * 255.0f); ++currIt; } } } GLuint CreateGaussianTexture(int cosAngleResolution, int shininessResolution) { std::vector<unsigned char> textureData; BuildGaussianData(textureData, cosAngleResolution, shininessResolution); GLuint gaussTexture; glGenTextures(1, &gaussTexture); glBindTexture(GL_TEXTURE_2D, gaussTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, cosAngleResolution, shininessResolution, 0, GL_RED, GL_UNSIGNED_BYTE, &textureData[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glBindTexture(GL_TEXTURE_2D, 0); return gaussTexture; } int CalcCosAngResolution(int level) { const int cosAngleStart = 64; return cosAngleStart * ((int)pow(2.0f, level)); } void CreateGaussianTextures() { for(int loop = 0; loop < NUM_GAUSS_TEXTURES; loop++) { int cosAngleResolution = CalcCosAngResolution(loop); g_gaussTextures[loop] = CreateGaussianTexture(cosAngleResolution, 128); } glGenSamplers(1, &g_textureSampler); glSamplerParameteri(g_textureSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameteri(g_textureSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glSamplerParameteri(g_textureSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameteri(g_textureSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } GLuint g_shineTexture = 0; void CreateShininessTexture() { std::auto_ptr<glimg::ImageSet> pImageSet; try { std::string filename(LOCAL_FILE_DIR); filename.append("main.dds"); pImageSet.reset(glimg::loaders::dds::LoadFromFile(filename.c_str())); glimg::SingleImage image = pImageSet->GetImage(0, 0, 0); glimg::Dimensions dims = image.GetDimensions(); glGenTextures(1, &g_shineTexture); glBindTexture(GL_TEXTURE_2D, g_shineTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, dims.width, dims.height, 0, GL_RED, GL_UNSIGNED_BYTE, image.GetImageData()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glBindTexture(GL_TEXTURE_2D, 0); } catch(std::exception &e) { printf("%s\n", e.what()); throw; } } const int NUM_MATERIALS = 2; void SetupMaterials() { Framework::UniformBlockArray<MaterialBlock, NUM_MATERIALS> mtls; MaterialBlock mtl; mtl.diffuseColor = glm::vec4(1.0f, 0.673f, 0.043f, 1.0f); mtl.specularColor = glm::vec4(1.0f, 0.673f, 0.043f, 1.0f) * 0.4f; mtl.specularShininess = 0.125f; mtls[0] = mtl; mtl.diffuseColor = glm::vec4(0.01f, 0.01f, 0.01f, 1.0f); mtl.specularColor = glm::vec4(0.99f, 0.99f, 0.99f, 1.0f); mtl.specularShininess = 0.125f; mtls[1] = mtl; g_materialUniformBuffer = mtls.CreateBufferObject(); g_materialOffset = mtls.GetArrayOffset(); } //Called after the window and OpenGL are initialized. Called exactly once, before the main loop. void init() { InitializePrograms(); try { g_pObjectMesh = new Framework::Mesh("Infinity.xml"); g_pCubeMesh = new Framework::Mesh("UnitCube.xml"); g_pPlaneMesh = new Framework::Mesh("UnitPlane.xml"); } catch(std::exception &except) { printf("%s\n", except.what()); throw; } glutMouseFunc(MouseButton); glutMotionFunc(MouseMotion); glutMouseWheelFunc(MouseWheel); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); const float depthZNear = 0.0f; const float depthZFar = 1.0f; glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glDepthRange(depthZNear, depthZFar); glEnable(GL_DEPTH_CLAMP); //Setup our Uniform Buffers SetupMaterials(); glGenBuffers(1, &g_lightUniformBuffer); glBindBuffer(GL_UNIFORM_BUFFER, g_lightUniformBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightBlock), NULL, GL_DYNAMIC_DRAW); glGenBuffers(1, &g_projectionUniformBuffer); glBindBuffer(GL_UNIFORM_BUFFER, g_projectionUniformBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(ProjectionBlock), NULL, GL_DYNAMIC_DRAW); //Bind the static buffers. glBindBufferRange(GL_UNIFORM_BUFFER, g_lightBlockIndex, g_lightUniformBuffer, 0, sizeof(LightBlock)); glBindBufferRange(GL_UNIFORM_BUFFER, g_projectionBlockIndex, g_projectionUniformBuffer, 0, sizeof(ProjectionBlock)); glBindBufferRange(GL_UNIFORM_BUFFER, g_materialBlockIndex, g_materialUniformBuffer, 0, sizeof(MaterialBlock)); glBindBuffer(GL_UNIFORM_BUFFER, 0); CreateGaussianTextures(); CreateShininessTexture(); } bool g_bDrawCameraPos = false; bool g_bDrawLights = true; bool g_bUseInfinity = true; ShaderMode g_eMode = MODE_FIXED; int g_currTexture = NUM_GAUSS_TEXTURES - 1; int g_currMaterial = 0; Framework::Timer g_lightTimer = Framework::Timer(Framework::Timer::TT_LOOP, 6.0f); float g_lightHeight = 1.0f; float g_lightRadius = 3.0f; glm::vec4 CalcLightPosition() { const float fLoopDuration = 5.0f; const float fScale = 3.14159f * 2.0f; float timeThroughLoop = g_lightTimer.GetAlpha(); glm::vec4 ret(0.0f, g_lightHeight, 0.0f, 1.0f); ret.x = cosf(timeThroughLoop * fScale) * g_lightRadius; ret.z = sinf(timeThroughLoop * fScale) * g_lightRadius; return ret; } const float g_fHalfLightDistance = 25.0f; const float g_fLightAttenuation = 1.0f / (g_fHalfLightDistance * g_fHalfLightDistance); //Called to update the display. //You should call glutSwapBuffers after all of your rendering to display what you rendered. //If you need continuous updates of the screen, call glutPostRedisplay() at the end of the function. void display() { g_lightTimer.Update(); glClearColor(0.75f, 0.75f, 1.0f, 1.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(g_pObjectMesh && g_pCubeMesh && g_pPlaneMesh) { glutil::MatrixStack modelMatrix; modelMatrix.SetMatrix(g_viewPole.CalcMatrix()); glm::mat4 worldToCamMat = modelMatrix.Top(); LightBlock lightData; lightData.ambientIntensity = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f); lightData.lightAttenuation = g_fLightAttenuation; glm::vec3 globalLightDirection(0.707f, 0.707f, 0.0f); lightData.lights[0].cameraSpaceLightPos = worldToCamMat * glm::vec4(globalLightDirection, 0.0f); lightData.lights[0].lightIntensity = glm::vec4(0.6f, 0.6f, 0.6f, 1.0f); lightData.lights[1].cameraSpaceLightPos = worldToCamMat * CalcLightPosition(); lightData.lights[1].lightIntensity = glm::vec4(0.4f, 0.4f, 0.4f, 1.0f); glBindBuffer(GL_UNIFORM_BUFFER, g_lightUniformBuffer); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(lightData), &lightData); glBindBuffer(GL_UNIFORM_BUFFER, 0); { Framework::Mesh *pMesh = g_bUseInfinity ? g_pObjectMesh : g_pPlaneMesh; glBindBufferRange(GL_UNIFORM_BUFFER, g_materialBlockIndex, g_materialUniformBuffer, g_currMaterial * g_materialOffset, sizeof(MaterialBlock)); glutil::PushStack push(modelMatrix); modelMatrix.ApplyMatrix(g_objtPole.CalcMatrix()); modelMatrix.Scale(g_bUseInfinity ? 2.0f : 4.0f); glm::mat3 normMatrix(modelMatrix.Top()); normMatrix = glm::transpose(glm::inverse(normMatrix)); ProgramData &prog = g_Programs[g_eMode]; glUseProgram(prog.theProgram); glUniformMatrix4fv(prog.modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top())); glUniformMatrix3fv(prog.normalModelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(normMatrix)); glActiveTexture(GL_TEXTURE0 + g_gaussTexUnit); glBindTexture(GL_TEXTURE_2D, g_gaussTextures[g_currTexture]); glBindSampler(g_gaussTexUnit, g_textureSampler); glActiveTexture(GL_TEXTURE0 + g_shineTexUnit); glBindTexture(GL_TEXTURE_2D, g_shineTexture); glBindSampler(g_shineTexUnit, g_textureSampler); if(g_eMode != MODE_FIXED) pMesh->Render("lit-tex"); else pMesh->Render("lit"); glBindSampler(g_gaussTexUnit, 0); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glBindBufferBase(GL_UNIFORM_BUFFER, g_materialBlockIndex, 0); } if(g_bDrawLights) { glutil::PushStack push(modelMatrix); modelMatrix.Translate(glm::vec3(CalcLightPosition())); modelMatrix.Scale(0.25f); glUseProgram(g_Unlit.theProgram); glUniformMatrix4fv(g_Unlit.modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top())); glm::vec4 lightColor(1.0f); glUniform4fv(g_Unlit.objectColorUnif, 1, glm::value_ptr(lightColor)); g_pCubeMesh->Render("flat"); push.ResetStack(); modelMatrix.Translate(globalLightDirection * 100.0f); modelMatrix.Scale(5.0f); glUniformMatrix4fv(g_Unlit.modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top())); g_pCubeMesh->Render("flat"); glUseProgram(0); } if(g_bDrawCameraPos) { glutil::PushStack push(modelMatrix); modelMatrix.SetIdentity(); modelMatrix.Translate(glm::vec3(0.0f, 0.0f, -g_viewPole.GetView().radius)); modelMatrix.Scale(0.25f); glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glUseProgram(g_Unlit.theProgram); glUniformMatrix4fv(g_Unlit.modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top())); glUniform4f(g_Unlit.objectColorUnif, 0.25f, 0.25f, 0.25f, 1.0f); g_pCubeMesh->Render("flat"); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glUniform4f(g_Unlit.objectColorUnif, 1.0f, 1.0f, 1.0f, 1.0f); g_pCubeMesh->Render("flat"); } } glutPostRedisplay(); glutSwapBuffers(); } //Called whenever the window is resized. The new window size is given, in pixels. //This is an opportunity to call glViewport or glScissor to keep up with the change in size. void reshape (int w, int h) { glutil::MatrixStack persMatrix; persMatrix.Perspective(45.0f, (w / (float)h), g_fzNear, g_fzFar); ProjectionBlock projData; projData.cameraToClipMatrix = persMatrix.Top(); glBindBuffer(GL_UNIFORM_BUFFER, g_projectionUniformBuffer); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ProjectionBlock), &projData); glBindBuffer(GL_UNIFORM_BUFFER, 0); glViewport(0, 0, (GLsizei) w, (GLsizei) h); glutPostRedisplay(); } const char *g_shaderModeNames[NUM_SHADER_MODES] = { "Fixed Shininess with Gaussian Texture", "Texture Shininess with Gaussian Texture", "Texture Shininess with computed Gaussian", }; //Called whenever a key on the keyboard was pressed. //The key is given by the ''key'' parameter, which is in ASCII. //It's often a good idea to have the escape key (ASCII value 27) call glutLeaveMainLoop() to //exit the program. void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: delete g_pObjectMesh; delete g_pCubeMesh; delete g_pPlaneMesh; g_pObjectMesh = NULL; g_pCubeMesh = NULL; g_pPlaneMesh = NULL; glutLeaveMainLoop(); return; case 'p': g_lightTimer.TogglePause(); break; case '-': g_lightTimer.Rewind(0.5f); break; case '=': g_lightTimer.Fastforward(0.5f); break; case 't': g_bDrawCameraPos = !g_bDrawCameraPos; break; case 'g': g_bDrawLights = !g_bDrawLights; break; case 'y': g_bUseInfinity = !g_bUseInfinity; break; case 32: g_eMode = (ShaderMode)(g_eMode + 1); g_eMode = (ShaderMode)(g_eMode % NUM_SHADER_MODES); printf("%s\n", g_shaderModeNames[g_eMode]); } if(('1' <= key) && (key <= '9')) { int number = key - '1'; if(number < NUM_GAUSS_TEXTURES) { printf("Angle Resolution: %i\n", CalcCosAngResolution(number)); g_currTexture = number; } if(number >= (9 - NUM_MATERIALS)) { number = number - (9 - NUM_MATERIALS); printf("Material number %i\n", number); g_currMaterial = number; } } } unsigned int defaults(unsigned int displayMode, int &width, int &height) {return displayMode;}
29.120185
146
0.725224
[ "mesh", "render", "object", "vector" ]
84ede4bb66b52395dff4a4b1b05d25b69cfea8de
2,487
hpp
C++
Calculator.hpp
Florinacho/PocketCalculator
1bd8e93e9f69bb21825c0b0d0e6ba03129f49e24
[ "MIT" ]
null
null
null
Calculator.hpp
Florinacho/PocketCalculator
1bd8e93e9f69bb21825c0b0d0e6ba03129f49e24
[ "MIT" ]
null
null
null
Calculator.hpp
Florinacho/PocketCalculator
1bd8e93e9f69bb21825c0b0d0e6ba03129f49e24
[ "MIT" ]
null
null
null
#ifndef __CALCULATOR_HPP__ #define __CALCULATOR_HPP__ #include <string> #include <vector> struct Token { enum TokenType { END_OF_STREAM, UNKNOWN, LEFT_PARENTHESIS, RIGHT_PARENTHESIS, NUMBER, IDENTIFIER, OPERATOR_COMMA, OPERATOR_ASSIGN, OPERATOR_EQUAL, OPERATOR_LEQ, OPERATOR_LTN, OPERATOR_GEQ, OPERATOR_GTN, OPERATOR_NOT_EQUAL, OPERATOR_ADD, OPERATOR_SUB, OPERATOR_MUL, OPERATOR_DIV, OPERATOR_NOT }; TokenType type; double numberValue; char identifier[32]; Token() { type = END_OF_STREAM; numberValue = 0.0; } }; class Calculator { const char* input; int inputIndex; struct Variable { std::string identifier; double value; bool constant; Variable(const char* nidentifier, double nvalue, bool nconstant) : identifier(nidentifier), value(nvalue), constant(nconstant) { } bool setValue(double newValue) { if (constant == true) { return false; } value = newValue; return true; } double getValue() const { return value; } }; std::vector<Variable> variableList; Token token[2]; bool getToken(Token& token); bool nextToken(); bool match(unsigned int tokenType); bool matchNumber(double* output); bool matchIdentifier(double* output); // Number, Identifier bool matchPrimaryExpression(double* output); // Operators: - bool matchUnaryExpression(double* output); // Operators: *, / bool matchMulExpressionTail(double* lvalue); bool matchMulExpression(double* output); // Operators: +, - bool matchAddExpressionTail(double* lvalue); bool matchAddExpression(double* output); // Operators: <, <=, >, >= bool matchRelExpressionTail(double* output); bool matchRelExpression(double* output); // Operators: ==, != bool matchEqualExpressionTail(double* output); bool matchEqualExpression(double* output); // Operators: = bool matchAssignExpression(double* output); bool matchExpression(double* output); void error(const char* format, ...); public: bool parse(double* output, const char* input); bool setVariable(const char* identifier, double value, bool constant = false); unsigned int getVariableCount() const; bool getVariable(const char* identifier, double* output = NULL, bool* constant = NULL) const; bool getVariable(const unsigned int index, std::string* identifier = NULL, double* output = NULL, bool* constant = NULL) const; bool removeVariable(const char* identifier); void removeAllVariables(); }; #endif //__CALCULATOR_HPP__
18.699248
128
0.721753
[ "vector" ]
84ee3e8966736d2c1b5723e510719cc7e576358e
344
cpp
C++
Online-Judge-Solution/HackerRank Solutions/C++/Functions.cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/HackerRank Solutions/C++/Functions.cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/HackerRank Solutions/C++/Functions.cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int maxFunction(int a,int b,int c,int d) { vector<int>v; v.push_back(a); v.push_back(b); v.push_back(c); v.push_back(d); sort(v.begin(),v.end()); return v[3]; } int main() { int a,b,c,d,e; cin>>a>>b>>c>>d; e=maxFunction(a,b,c,d); cout<<e; return 0; }
16.380952
40
0.549419
[ "vector" ]
84ef45c546af05411ea9144e6d6582c3afa6a302
946
hpp
C++
lib/packager/BondSplicer.hpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
1
2021-07-06T14:05:20.000Z
2021-07-06T14:05:20.000Z
lib/packager/BondSplicer.hpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
1
2021-03-03T11:37:10.000Z
2021-03-03T11:37:10.000Z
lib/packager/BondSplicer.hpp
isabella232/cpp_client_telemetry
46a7d65089799c216207ae4758980158affced47
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2015-2020 Microsoft Corporation and Contributors. // SPDX-License-Identifier: Apache-2.0 // #ifndef BONDSPLICER_HPP #define BONDSPLICER_HPP #include "pal/PAL.hpp" #include "DataPackage.hpp" #include "ISplicer.hpp" #include <list> #include <vector> namespace MAT_NS_BEGIN { class BondSplicer : public ISplicer { protected: std::vector<uint8_t> m_buffer; std::vector<PackageInfo> m_packages; size_t m_overheadEstimate {}; public: BondSplicer() noexcept = default; BondSplicer(BondSplicer const&) = delete; BondSplicer& operator=(BondSplicer const&) = delete; size_t addTenantToken(std::string const& tenantToken) override; void addRecord(size_t dataPackageIndex, std::vector<uint8_t> const& recordBlob) override; size_t getSizeEstimate() const override; std::vector<uint8_t> splice() const override; void clear() override; }; } MAT_NS_END #endif
22
93
0.713531
[ "vector" ]
84f4c17579eac374da407fa19c742ac3fa74bd28
15,564
hpp
C++
contracts/eosio.system/eosio.system.hpp
ElementhFoundation/blockchain
5f63038c0e6fc90bc4bc0bc576410087785d8099
[ "MIT" ]
1
2018-05-16T07:04:50.000Z
2018-05-16T07:04:50.000Z
contracts/eosio.system/eosio.system.hpp
ElementhFoundation/blockchain
5f63038c0e6fc90bc4bc0bc576410087785d8099
[ "MIT" ]
null
null
null
contracts/eosio.system/eosio.system.hpp
ElementhFoundation/blockchain
5f63038c0e6fc90bc4bc0bc576410087785d8099
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosiolib/eosio.hpp> #include <eosiolib/token.hpp> #include <eosiolib/db.hpp> #include <eosiolib/reflect.hpp> #include <eosiolib/print.hpp> #include <eosiolib/generic_currency.hpp> #include <eosiolib/datastream.hpp> #include <eosiolib/serialize.hpp> #include <eosiolib/multi_index.hpp> #include <eosiolib/privileged.h> #include <algorithm> #include <map> namespace eosiosystem { using eosio::indexed_by; using eosio::const_mem_fun; using eosio::bytes; using std::map; using std::pair; using eosio::print; template<account_name SystemAccount> class contract { public: static const account_name system_account = SystemAccount; typedef eosio::generic_currency< eosio::token<system_account,S(4,EOS)> > currency; typedef typename currency::token_type system_token_type; struct producer_votes { account_name owner; uint64_t padding = 0; uint128_t total_votes; uint64_t primary_key()const { return owner; } uint128_t by_votes()const { return total_votes; } EOSLIB_SERIALIZE( producer_votes, (owner)(total_votes) ) }; typedef eosio::multi_index< N(producervote), producer_votes, indexed_by<N(prototalvote), const_mem_fun<producer_votes, uint128_t, &producer_votes::by_votes> > > producer_votes_index_type; struct account_votes { account_name owner; account_name proxy; uint32_t last_update; system_token_type staked; std::vector<account_name> producers; uint64_t primary_key()const { return owner; } EOSLIB_SERIALIZE( account_votes, (owner)(proxy)(last_update)(staked)(producers) ) }; typedef eosio::multi_index< N(accountvotes), account_votes> account_votes_index_type; struct producer_config { account_name owner; eosio::bytes packed_key; /// a packed public key object uint64_t primary_key()const { return owner; } EOSLIB_SERIALIZE( producer_config, (owner)(packed_key) ) }; typedef eosio::multi_index< N(producercfg), producer_config> producer_config_index_type; struct total_resources { account_name owner; typename currency::token_type total_net_weight; typename currency::token_type total_cpu_weight; uint32_t total_ram = 0; uint64_t primary_key()const { return owner; } EOSLIB_SERIALIZE( total_resources, (owner)(total_net_weight)(total_cpu_weight)(total_ram) ) }; /** * Every user 'from' has a scope/table that uses every receipient 'to' as the primary key. */ struct delegated_bandwidth { account_name from; account_name to; typename currency::token_type net_weight; typename currency::token_type cpu_weight; uint32_t start_pending_net_withdraw = 0; typename currency::token_type pending_net_withdraw; uint64_t deferred_net_withdraw_handler = 0; uint32_t start_pending_cpu_withdraw = 0; typename currency::token_type pending_cpu_withdraw; uint64_t deferred_cpu_withdraw_handler = 0; uint64_t primary_key()const { return to; } EOSLIB_SERIALIZE( delegated_bandwidth, (from)(to)(net_weight)(cpu_weight) (start_pending_net_withdraw)(pending_net_withdraw)(deferred_net_withdraw_handler) (start_pending_cpu_withdraw)(pending_cpu_withdraw)(deferred_cpu_withdraw_handler) ) }; typedef eosio::multi_index< N(totalband), total_resources> total_resources_index_type; typedef eosio::multi_index< N(delband), delegated_bandwidth> del_bandwidth_index_type; ACTION( SystemAccount, finshundel ) { account_name from; account_name to; }; ACTION( SystemAccount, regproducer ) { account_name producer; bytes producer_key; EOSLIB_SERIALIZE( regproducer, (producer)(producer_key) ) }; ACTION( SystemAccount, regproxy ) { account_name proxy_to_register; EOSLIB_SERIALIZE( regproxy, (proxy_to_register) ) }; ACTION( SystemAccount, delegatebw ) { account_name from; account_name receiver; typename currency::token_type stake_net_quantity; typename currency::token_type stake_cpu_quantity; EOSLIB_SERIALIZE( delegatebw, (from)(receiver)(stake_net_quantity)(stake_cpu_quantity) ) }; ACTION( SystemAccount, undelegatebw ) { account_name from; account_name receiver; typename currency::token_type unstake_net_quantity; typename currency::token_type unstake_cpu_quantity; EOSLIB_SERIALIZE( undelegatebw, (from)(receiver)(unstake_net_quantity)(unstake_cpu_quantity) ) }; ACTION( SystemAccount, nonce ) { eosio::string value; EOSLIB_SERIALIZE( nonce, (value) ) }; /// new id options: // 1. hash + collision // 2. incrementing count (key=> tablename static void on( const delegatebw& del ) { eosio_assert( del.stake_cpu_quantity.quantity >= 0, "must stake a positive amount" ); eosio_assert( del.stake_net_quantity.quantity >= 0, "must stake a positive amount" ); auto total_stake = del.stake_cpu_quantity + del.stake_net_quantity; eosio_assert( total_stake.quantity >= 0, "must stake a positive amount" ); require_auth( del.from ); del_bandwidth_index_type del_index( SystemAccount, del.from ); total_resources_index_type total_index( SystemAccount, del.receiver ); //eosio_assert( is_account( del.receiver ), "can only delegate resources to an existing account" ); auto itr = del_index.find( del.receiver); if( itr != del_index.end() ) { del_index.emplace( del.from, [&]( auto& dbo ){ dbo.from = del.from; dbo.to = del.receiver; dbo.net_weight = del.stake_net_quantity; dbo.cpu_weight = del.stake_cpu_quantity; }); } else { del_index.modify( itr, del.from, [&]( auto& dbo ){ dbo.net_weight = del.stake_net_quantity; dbo.cpu_weight = del.stake_cpu_quantity; }); } auto tot_itr = total_index.find( del.receiver ); if( tot_itr == total_index.end() ) { tot_itr = total_index.emplace( del.from, [&]( auto& tot ) { tot.owner = del.receiver; tot.total_net_weight += del.stake_net_quantity; tot.total_cpu_weight += del.stake_cpu_quantity; }); } else { total_index.modify( tot_itr, 0, [&]( auto& tot ) { tot.total_net_weight += del.stake_net_quantity; tot.total_cpu_weight += del.stake_cpu_quantity; }); } set_resource_limits( tot_itr->owner, tot_itr->total_ram, tot_itr->total_net_weight.quantity, tot_itr->total_cpu_weight.quantity, 0 ); currency::inline_transfer( del.from, SystemAccount, total_stake, "stake bandwidth" ); } // delegatebw static void on( const undelegatebw& del ) { eosio_assert( del.unstake_cpu_quantity.quantity >= 0, "must stake a positive amount" ); eosio_assert( del.unstake_net_quantity.quantity >= 0, "must stake a positive amount" ); auto total_stake = del.unstake_cpu_quantity + del.unstake_net_quantity; eosio_assert( total_stake.quantity >= 0, "must stake a positive amount" ); require_auth( del.from ); del_bandwidth_index_type del_index( SystemAccount, del.from ); total_resources_index_type total_index( SystemAccount, del.receiver ); //eosio_assert( is_account( del.receiver ), "can only delegate resources to an existing account" ); const auto& dbw = del_index.get(del.receiver); eosio_assert( dbw.net_weight >= del.unstake_net_quantity, "insufficient staked net bandwidth" ); eosio_assert( dbw.cpu_weight >= del.unstake_cpu_quantity, "insufficient staked cpu bandwidth" ); del_index.modify( dbw, del.from, [&]( auto& dbo ){ dbo.net_weight -= del.unstake_net_quantity; dbo.cpu_weight -= del.unstake_cpu_quantity; }); const auto& totals = total_index.get( del.receiver ); total_index.modify( totals, 0, [&]( auto& tot ) { tot.total_net_weight -= del.unstake_net_quantity; tot.total_cpu_weight -= del.unstake_cpu_quantity; }); set_resource_limits( totals.owner, totals.total_ram, totals.total_net_weight.quantity, totals.total_cpu_weight.quantity, 0 ); /// TODO: implement / enforce time delays on withdrawing currency::inline_transfer( SystemAccount, del.from, total_stake, "unstake bandwidth" ); } // undelegatebw /** * This method will create a producr_config and producer_votes object for 'producer' * * @pre producer is not already registered * @pre producer to register is an account * @pre authority of producer to register * */ static void on( const regproducer& reg ) { auto producer = reg.producer; require_auth( producer ); producer_votes_index_type votes( SystemAccount, SystemAccount ); auto existing = votes.find( producer ); eosio_assert( existing == votes.end(), "producer already registered" ); votes.emplace( producer, [&]( auto& pv ){ pv.owner = producer; pv.total_votes = 0; }); producer_config_index_type proconfig( SystemAccount, SystemAccount ); proconfig.emplace( producer, [&]( auto& pc ) { pc.owner = producer; pc.packed_key = reg.producer_key; }); } ACTION( SystemAccount, stakevote ) { account_name voter; system_token_type amount; EOSLIB_SERIALIZE( stakevote, (voter)(amount) ) }; static void on( const stakevote& sv ) { print( "on stake vote\n" ); eosio_assert( sv.amount.quantity > 0, "must stake some tokens" ); require_auth( sv.voter ); account_votes_index_type avotes( SystemAccount, SystemAccount ); auto acv = avotes.find( sv.voter ); if( acv == avotes.end() ) { acv = avotes.emplace( sv.voter, [&]( auto& av ) { av.owner = sv.voter; av.last_update = now(); av.proxy = 0; }); } uint128_t old_weight = acv->staked.quantity; uint128_t new_weight = old_weight + sv.amount.quantity; producer_votes_index_type votes( SystemAccount, SystemAccount ); for( auto p : acv->producers ) { votes.modify( votes.get( p ), 0, [&]( auto& v ) { v.total_votes -= old_weight; v.total_votes += new_weight; }); } avotes.modify( acv, 0, [&]( auto av ) { av.last_update = now(); av.staked += sv.amount; }); currency::inline_transfer( sv.voter, SystemAccount, sv.amount, "stake for voting" ); } ACTION( SystemAccount, voteproducer ) { account_name voter; account_name proxy; std::vector<account_name> producers; EOSLIB_SERIALIZE( voteproducer, (voter)(proxy)(producers) ) }; /** * @pre vp.producers must be sorted from lowest to highest * @pre if proxy is set then no producers can be voted for * @pre every listed producer or proxy must have been previously registered * @pre vp.voter must authorize this action * @pre voter must have previously staked some EOS for voting */ static void on( const voteproducer& vp ) { eosio_assert( std::is_sorted( vp.producers.begin(), vp.producers.end() ), "producer votes must be sorted" ); eosio_assert( vp.producers.size() <= 30, "attempt to vote for too many producers" ); if( vp.proxy != 0 ) eosio_assert( vp.producers.size() == 0, "cannot vote for producers and proxy at same time" ); require_auth( vp.voter ); account_votes_index_type avotes( SystemAccount, SystemAccount ); const auto& existing = avotes.get( vp.voter ); std::map<account_name, pair<uint128_t, uint128_t> > producer_vote_changes; uint128_t old_weight = existing.staked.quantity; /// old time uint128_t new_weight = old_weight; /// TODO: update for current weight for( const auto& p : existing.producers ) producer_vote_changes[p].first = old_weight; for( const auto& p : vp.producers ) producer_vote_changes[p].second = new_weight; producer_votes_index_type votes( SystemAccount, SystemAccount ); for( const auto& delta : producer_vote_changes ) { if( delta.second.first != delta.second.second ) { const auto& provote = votes.get( delta.first ); votes.modify( provote, 0, [&]( auto& pv ){ pv.total_votes -= delta.second.first; pv.total_votes += delta.second.second; }); } } avotes.modify( existing, 0, [&]( auto& av ) { av.proxy = vp.proxy; av.last_update = now(); av.producers = vp.producers; }); } static void on( const regproxy& reg ) { require_auth( reg.proxy_to_register ); } static void on( const nonce& ) { } static void apply( account_name code, action_name act ) { if( !eosio::dispatch<contract, regproducer, regproxy, delegatebw, undelegatebw, regproducer, voteproducer, stakevote, nonce>( code, act) ) { if ( !eosio::dispatch<currency, typename currency::transfer, typename currency::issue>( code, act ) ) { eosio::print("Unexpected action: ", eosio::name(act), "\n"); eosio_assert( false, "received unexpected action"); } } } /// apply }; } /// eosiosystem
38.620347
145
0.575238
[ "object", "vector" ]
84f63298ac985d440c7ced2ada39dd4ecbed8f89
18,072
cpp
C++
TTVS/HeadMovement.cpp
thuhcsi/Crystal.TTVS
9e6c86566bfacf4fc571ad7b1308bcb7382bb213
[ "Apache-2.0" ]
75
2020-08-18T03:27:13.000Z
2022-01-05T13:17:50.000Z
TTVS/HeadMovement.cpp
thuhcsi/Crystal.TTVS
9e6c86566bfacf4fc571ad7b1308bcb7382bb213
[ "Apache-2.0" ]
1
2020-11-11T09:31:06.000Z
2020-11-19T14:44:41.000Z
TTVS/HeadMovement.cpp
thuhcsi/Crystal.TTVS
9e6c86566bfacf4fc571ad7b1308bcb7382bb213
[ "Apache-2.0" ]
10
2020-08-18T04:35:29.000Z
2021-09-09T01:41:23.000Z
// Natural Head movement synthesis for Talking Avatar // Author: ShenZHANG // Date: 2007/10/09 // input1: PAD stream(for each Prosodic Word) // input2: Tone stream (for each syllable 0,1,2,3,4) // input3: Stress stream (for each syllable 0,1) // (input4): Syllable stream (pinyin,just used for viseme generation) // output: FAP stream file //input1 example //---------------------------------------------------------- // start_frame_no end_frame_no P_Value A_Value D_Value // 45 79 0 0.5 0 // 91 119 0 0 0 //---------------------------------------------------------- //input2+input3 exmaple //---------------------------------------------------------- // start_frame_no end_frame_no Tone Stress // 45 53 4 1 // 54 60 2 0 //---------------------------------------------------------- //(input4 example :not used) //---------------------------------------------------------- // pinyin start_frame end_frame // tai 45 53 // ping 54 60 //----------------------------------------------------------*/ //output example:(FAP file with head and facial movement, 8 FAP) //---------------------------------------------------------- // 2.1 LinLin::FapFile 25 1597 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // 0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 //---------------------------------------------------------- #include <stdlib.h> #include <math.h> #include <iterator> #ifndef WINCE #include <time.h> #else #include <Windows.h> // for SYSTEMTIME, there is no time() under WINCE #endif #include "HeadMovement.h" namespace CSTHead { unsigned int HeadMovement::getRandSeed() { #ifdef WINCE SYSTEMTIME sysTime; FILETIME fileTime; GetSystemTime(&sysTime); SystemTimeToFileTime( &sysTime, &fileTime ); return fileTime.dwLowDateTime; #else return (unsigned)time(NULL); #endif } void HeadMovement::generateFAPs(const std::vector<SyllableInfo>& syl_info, const std::vector<int>& pw_frm_info, std::vector< std::vector<float> >& FAP_stream) { if (syl_info.size() == 0 || pw_frm_info.size() == 0) return; const int FRAME_RATE = 25; //TODO std::vector<int> pw_info = pw_frm_info; // for PW merge purpose int pw_num = (int)pw_info.size()/2; //pw_info = (start_syl_no,end_syl_no) //step1. set the PAD value for each PW (the maximum PAD value among all the syllable) std::vector<PAD> pw_pad; //pw_pad.reserve(pw_num); for (int i=0;i<pw_num;i++) { int ii = i*2; //counter int j=pw_info[ii]; //start_syl_no PAD max_pad = syl_info[j].pad; float max_pad_sum = max_pad.P+max_pad.A+max_pad.D; for (j=pw_info[ii]+1;j<pw_info[ii+1];j++) { float tmp_pad_sum = syl_info[j].pad.P + syl_info[j].pad.A + syl_info[j].pad.D; if (tmp_pad_sum>max_pad_sum) { max_pad_sum = tmp_pad_sum; max_pad = syl_info[j].pad; } } pw_pad.push_back(max_pad); } //option:merge consecutive PW with same PAD into one PW //the average PW length is better around 5-6 syllables int last_idx = 0; PAD last_pad = pw_pad[0]; int ph_num = 0; int cnt = 0; std::vector<PAD> tmp_pad; std::vector<int> tmp_pw_info; for (int i=1;i<pw_num;i++) { PAD cur_pad = pw_pad[i]; if (cur_pad.P==last_pad.P && cur_pad.A==last_pad.A && cur_pad.D==last_pad.D && cnt<0) // original: cnt<2 { // cnt<0, do not mergy cnt++; continue; }else { cnt = 0; ph_num++; tmp_pad.push_back(last_pad); tmp_pw_info.push_back(pw_info[last_idx*2]); tmp_pw_info.push_back(pw_info[(i-1)*2+1]); last_pad = cur_pad; last_idx = i; } } tmp_pad.push_back(last_pad); tmp_pw_info.push_back(pw_info[last_idx*2]); tmp_pw_info.push_back(pw_info[(pw_num-1)*2+1]); pw_info = tmp_pw_info; pw_pad = tmp_pad; pw_num = (int)pw_info.size()/2; // step2. set the head amp and pos for each PW std::vector<float> head_pos; std::vector<float> head_amp; head_pos.reserve(pw_num); head_amp.reserve(pw_num); std::fill_n(std::back_inserter(head_pos),pw_num,0.0f); std::fill_n(std::back_inserter(head_amp),pw_num,0.0f); srand( getRandSeed() ); for (int i=0;i<pw_num;i++) { GetHeadPos(pw_pad[i],head_pos[i],head_amp[i]); } //step3. set the peak and valley point in headmovement for each PW std::vector<int> head_peak; std::vector<int> head_valley; std::vector<int> head_frm_len; std::fill_n(std::back_inserter(head_peak),pw_num,0); std::fill_n(std::back_inserter(head_valley),pw_num,0); std::fill_n(std::back_inserter(head_frm_len),pw_num,0); for (int i=0;i<pw_num;i++) { int ii = i*2; int head_frm = syl_info[pw_info[ii]].start_frame_no; int tail_frm = syl_info[pw_info[ii+1]].end_frame_no; int pw_frm_len = tail_frm - head_frm + 1; int peak_frm = 0; int valley_frm = 0; if (i==0) // the first PW(sentence initial) { peak_frm = (int)(pw_frm_len*0.2); valley_frm = (int)(pw_frm_len*0.8); //original //peak_frm = (int)(pw_frm_len*0.8); //valley_frm = (int)(pw_frm_len*0.2); }else { //GetPeakPos(pw_info[ii],pw_info[ii+1],pw_pad[i],syl_info,&peak_frm,&valley_frm); int pw_syl_num = pw_info[ii+1] - pw_info[ii] + 1; if (pw_syl_num==0) //silence { peak_frm = (int)(pw_frm_len*0.25)+ head_frm; valley_frm = (int)(pw_frm_len*0.75)+ head_frm; }else if(pw_syl_num==1) //only one syllable { int s = head_frm; int e = tail_frm; if(syl_info[pw_info[ii]].stressed==1 || syl_info[pw_info[ii]].tone==4) //stress or emphasis tone { peak_frm = (s+e)/2; valley_frm = e+(e-s)/2; } else { peak_frm = s; valley_frm = e; } } else //more than 2 syllables { bool is_set = false; for (int k=pw_info[ii];k<pw_info[ii+1];k++) //find the first stress { if (syl_info[k].stressed==1) { int s = syl_info[k].start_frame_no; int e = syl_info[k].end_frame_no; peak_frm = (s+e)/2; if(k-pw_info[ii] + 1 > pw_syl_num/2) { valley_frm = syl_info[pw_info[ii]].start_frame_no; } else { valley_frm = syl_info[pw_info[ii+1]].end_frame_no; } is_set = true; break; } } if (!is_set) //find first falling tone { for (int k=pw_info[ii];k<pw_info[ii+1];k++) { if (syl_info[k].tone == 4) { int s = syl_info[k].start_frame_no; int e = syl_info[k].end_frame_no; peak_frm = (s+e)/2; if(k - pw_info[ii] + 1> pw_syl_num/2) { valley_frm = syl_info[pw_info[ii]].start_frame_no; } else { valley_frm = syl_info[pw_info[ii+1]].end_frame_no; } is_set = true; break; } } } if (!is_set) //find other syllable on the boundary { int peak_idx = pw_info[ii]; int valley_idx = pw_info[ii+1]; if(pw_syl_num>4) { peak_idx = (int)(pw_syl_num*0.25); valley_idx = (int)(pw_syl_num*0.75); } peak_frm = syl_info[peak_idx].start_frame_no; valley_frm = syl_info[valley_idx].end_frame_no; } } peak_frm -= head_frm; valley_frm -= head_frm; } head_peak[i] = peak_frm; head_valley[i] = valley_frm; head_frm_len[i] = pw_frm_len; } //step4 interpolate the head location for each PW std::vector<float> head_y; std::vector<float> head_x; int total_len_frm = syl_info[pw_info[pw_num*2-1]].end_frame_no + 2*FRAME_RATE; head_y.reserve(total_len_frm); head_x.reserve(total_len_frm); std::fill_n(std::back_inserter(head_y),total_len_frm,0.0f); std::fill_n(std::back_inserter(head_x),total_len_frm,0.0f); const float PI = 3.1415926f; std::vector<float> y; for (int i=0;i<pw_num;i++) { y.clear(); y.reserve(head_frm_len[i]); std::fill_n(std::back_inserter(y),head_frm_len[i],0.0f); const int peak_range_L = 5; //the left part of peak point float sF = PI/(2*peak_range_L); float sA = head_amp[i]*0.75f; int s = head_peak[i] - peak_range_L; int e = head_peak[i]+1; if(s<0)s=0; if(e>head_frm_len[i])e=head_frm_len[i]; for(int x=s;x<e;x++) { y[x] = sA * sin(sF*(x-head_peak[i]) + PI/2); } int peak_left = s; const int peak_range_R = 10; // the right part of peak point sF = PI/(2*peak_range_R); sA = head_amp[i]*0.75f; s = head_peak[i]; e = head_peak[i]+peak_range_R+1; if(s<0)s=0; if(e>head_frm_len[i])e=head_frm_len[i]; for(int x=s;x<e;x++) { y[x] = sA * sin(sF*(x-head_peak[i]) + PI/2); } int peak_right = e; int valley_range = 0; if( head_valley[i]> peak_right) { valley_range = head_valley[i] - peak_right; }else if(head_valley[i]<peak_left) { valley_range = peak_left - head_valley[i]; } if(valley_range>0) { sA = -head_amp[i]*0.25f; sF = PI/(2 * valley_range); s = head_valley[i] - valley_range; e = head_valley[i] + valley_range+1; if(s<0)s=0; if(e>head_frm_len[i])e=head_frm_len[i]; for(int x=s;x<e;x++) { y[x] = sA * sin(sF*(x-head_valley[i]) + PI/2); } } for (int x=0;x<head_frm_len[i];x++) { y[x] += head_amp[i]*0.2f + head_pos[i]; } int head_frame = syl_info[pw_info[i*2]].start_frame_no; for (int x=0;x<head_frm_len[i];x++) { head_y[x+head_frame] = y[x]; } // for horizontal movement if (head_frm_len[i]>FRAME_RATE) { float sign = 1; if(rand() < (RAND_MAX/2)) sign = -1; for (int x=0;x<head_frm_len[i];x++) { head_x[x+head_frame] = sign*y[x]; } } } //step5: smooth the boundary const int t_size = 5; std::vector<float> tmp_y = head_y; for (int i=0;i<pw_num;i++) { int ii = i*2; int head_frame = syl_info[pw_info[ii]].start_frame_no; int tail_frame = syl_info[pw_info[ii+1]].end_frame_no; for (int k = head_frame - t_size;k<=head_frame+t_size;k++) { if (k<0 || k>total_len_frm) continue; int s = k-t_size;if(s<0)s=0; int e = k+t_size;if(e>=total_len_frm)e=total_len_frm-1; head_y[k] = GetMeanValue(tmp_y,s,e); } for (int k=tail_frame-t_size;k<=tail_frame+t_size;k++) { if (k<0 || k>total_len_frm)continue; int s = k-t_size;if(s<0)s=0; int e = k+t_size;if(e>=total_len_frm)e=total_len_frm-1; head_y[k] = GetMeanValue(tmp_y,s,e); } } smooth(head_x,21); smooth(head_y,5); //step6. get the FAP stream const int AU_SCALE = 50000; const float IRISD_SCALE = 20480/5.66434f; const float ENS_SCALE = 30480/25.5803f; const float AVG_HEAD = GetMeanValue(head_y,0,total_len_frm-1); FAP_stream.clear(); for (int x=0;x<total_len_frm;x++) { float delta = 0; float delta2 = 0; float delta3 = head_y[x]*100; if (head_y[x] >= AVG_HEAD*0.7) { delta = -head_y[x]*0.05f; delta2 = head_y[x]*1.5f; }else if((x%(2*FRAME_RATE))==0 && rand()<(RAND_MAX/2)) { delta = 0.5; } std::vector<float> fap_set; fap_set.reserve(68); std::fill_n(std::back_inserter(fap_set),68,0.0f); fap_set[18] = delta*IRISD_SCALE; fap_set[19] = delta*IRISD_SCALE; fap_set[32] = delta2*ENS_SCALE; fap_set[33] = delta2*ENS_SCALE; fap_set[47] = head_y[x]*AU_SCALE; fap_set[48] = delta3*100; fap_set[49] = delta3*100; FAP_stream.push_back(fap_set); } return; } void HeadMovement::GetHeadPos(const PAD pad,float &pos,float &amp) { const float AMP_AVG[] = {0.0391f, 0.0575f, 0.0587f, 0.0807f, 0.1150f, 0.0752f, 0.0778f, 0.0279f, 0.0423f}; const float AMP_STD[] = {0.0142f, 0.0249f, 0.0279f, 0.0373f, 0, 0.0525f, 0.0496f, 0.0196f, 0.0258f}; const float POS_AVG[] = {-0.0035f, -0.0248f, -0.0146f, -0.0163f, 0.0071f, -0.0042f, -0.0171f, -0.0213f, -0.0216f}; const float POS_STD[] = {0.0108f, 0.0195f, 0.0167f, 0.0214f, 0, 0.0116f, 0.0124f, 0.0183f, 0.0181f}; const float AMP_RANGE[] = { 0.0076f, 0.0294f, 0.0460f, 0.0723f, 0.1150f}; const float POS_RANGE[] = {-0.0035f, -0.0248f, -0.0146f, -0.0163f}; int t = GetPADType(pad); if(t<5) { amp = AMP_RANGE[t-1] + rand()*1.0f/RAND_MAX * (AMP_RANGE[t] - AMP_RANGE[t-1]); pos = POS_RANGE[t-1] + rand()*1.0f/RAND_MAX * 0.001f; } else { amp = 0.017f; pos = 0; } return; } inline int HeadMovement::GetPADType(const PAD pad) { const float P = pad.P; const float A = pad.A; const float D = pad.D; int type = 7; if (P==0) { if (A==0) { type = 1; }else if(A==0.5) { type = 2; }else if(A==1) { type = 5; } }else if(P==1) { if (A==0) { type = 6; }else if(A==0.5) { type = 3; }else if(A==1) { type = 4; } } return type; } // set the peak and valley point of head movement in each PW based on intra-pw-rule //void GetPeakPos(const int head,const int tail,const PAD pad,int &peak,int &valley) //{ //} float HeadMovement::GetMeanValue(const std::vector<float> data,const int s,const int e) { float mean_val = 0; for (int i=s;i<=e;i++) { mean_val += data[i]; } mean_val = mean_val/(e-s+1); return mean_val; } void HeadMovement::smooth(std::vector<float> &data,const int win_len) { std::vector<float> tmp_data = data; size_t half_win = win_len/2; for (size_t i=0; i<data.size(); i++) { size_t s = (i < half_win) ? 0 : i-half_win; size_t e = i + half_win; if (e >= data.size()) e = data.size() - 1; float mean_val = 0; for (size_t k=s; k<=e; k++) mean_val += tmp_data[k]; data[i] = mean_val / (e-s+1); } } }
36.657201
162
0.442784
[ "vector" ]
ebc98891e19d8266e3d41dc2f7e080eeb9526fcb
17,398
ipp
C++
implement/eglplus/enums/config_attrib_class.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/eglplus/enums/config_attrib_class.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/eglplus/enums/config_attrib_class.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File implement/eglplus/enums/config_attrib_class.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/eglplus/config_attrib.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // namespace enums { template <typename Base, template<ConfigAttrib> class Transform> class EnumToClass<Base, ConfigAttrib, Transform> : public Base { private: Base& _base(void) { return *this; } public: #if defined EGL_BUFFER_SIZE # if defined BufferSize # pragma push_macro("BufferSize") # undef BufferSize Transform<ConfigAttrib::BufferSize> BufferSize; # pragma pop_macro("BufferSize") # else Transform<ConfigAttrib::BufferSize> BufferSize; # endif #endif #if defined EGL_RED_SIZE # if defined RedSize # pragma push_macro("RedSize") # undef RedSize Transform<ConfigAttrib::RedSize> RedSize; # pragma pop_macro("RedSize") # else Transform<ConfigAttrib::RedSize> RedSize; # endif #endif #if defined EGL_GREEN_SIZE # if defined GreenSize # pragma push_macro("GreenSize") # undef GreenSize Transform<ConfigAttrib::GreenSize> GreenSize; # pragma pop_macro("GreenSize") # else Transform<ConfigAttrib::GreenSize> GreenSize; # endif #endif #if defined EGL_BLUE_SIZE # if defined BlueSize # pragma push_macro("BlueSize") # undef BlueSize Transform<ConfigAttrib::BlueSize> BlueSize; # pragma pop_macro("BlueSize") # else Transform<ConfigAttrib::BlueSize> BlueSize; # endif #endif #if defined EGL_LUMINANCE_SIZE # if defined LuminanceSize # pragma push_macro("LuminanceSize") # undef LuminanceSize Transform<ConfigAttrib::LuminanceSize> LuminanceSize; # pragma pop_macro("LuminanceSize") # else Transform<ConfigAttrib::LuminanceSize> LuminanceSize; # endif #endif #if defined EGL_ALPHA_SIZE # if defined AlphaSize # pragma push_macro("AlphaSize") # undef AlphaSize Transform<ConfigAttrib::AlphaSize> AlphaSize; # pragma pop_macro("AlphaSize") # else Transform<ConfigAttrib::AlphaSize> AlphaSize; # endif #endif #if defined EGL_ALPHA_MASK_SIZE # if defined AlphaMaskSize # pragma push_macro("AlphaMaskSize") # undef AlphaMaskSize Transform<ConfigAttrib::AlphaMaskSize> AlphaMaskSize; # pragma pop_macro("AlphaMaskSize") # else Transform<ConfigAttrib::AlphaMaskSize> AlphaMaskSize; # endif #endif #if defined EGL_BIND_TO_TEXTURE_RGB # if defined BindToTextureRGB # pragma push_macro("BindToTextureRGB") # undef BindToTextureRGB Transform<ConfigAttrib::BindToTextureRGB> BindToTextureRGB; # pragma pop_macro("BindToTextureRGB") # else Transform<ConfigAttrib::BindToTextureRGB> BindToTextureRGB; # endif #endif #if defined EGL_BIND_TO_TEXTURE_RGBA # if defined BindToTextureRGBA # pragma push_macro("BindToTextureRGBA") # undef BindToTextureRGBA Transform<ConfigAttrib::BindToTextureRGBA> BindToTextureRGBA; # pragma pop_macro("BindToTextureRGBA") # else Transform<ConfigAttrib::BindToTextureRGBA> BindToTextureRGBA; # endif #endif #if defined EGL_COLOR_BUFFER_TYPE # if defined ColorBufferType # pragma push_macro("ColorBufferType") # undef ColorBufferType Transform<ConfigAttrib::ColorBufferType> ColorBufferType; # pragma pop_macro("ColorBufferType") # else Transform<ConfigAttrib::ColorBufferType> ColorBufferType; # endif #endif #if defined EGL_CONFIG_CAVEAT # if defined ConfigCaveat # pragma push_macro("ConfigCaveat") # undef ConfigCaveat Transform<ConfigAttrib::ConfigCaveat> ConfigCaveat; # pragma pop_macro("ConfigCaveat") # else Transform<ConfigAttrib::ConfigCaveat> ConfigCaveat; # endif #endif #if defined EGL_CONFIG_ID # if defined ConfigId # pragma push_macro("ConfigId") # undef ConfigId Transform<ConfigAttrib::ConfigId> ConfigId; # pragma pop_macro("ConfigId") # else Transform<ConfigAttrib::ConfigId> ConfigId; # endif #endif #if defined EGL_CONFORMANT # if defined Conformant # pragma push_macro("Conformant") # undef Conformant Transform<ConfigAttrib::Conformant> Conformant; # pragma pop_macro("Conformant") # else Transform<ConfigAttrib::Conformant> Conformant; # endif #endif #if defined EGL_DEPTH_SIZE # if defined DepthSize # pragma push_macro("DepthSize") # undef DepthSize Transform<ConfigAttrib::DepthSize> DepthSize; # pragma pop_macro("DepthSize") # else Transform<ConfigAttrib::DepthSize> DepthSize; # endif #endif #if defined EGL_LEVEL # if defined Level # pragma push_macro("Level") # undef Level Transform<ConfigAttrib::Level> Level; # pragma pop_macro("Level") # else Transform<ConfigAttrib::Level> Level; # endif #endif #if defined EGL_MAX_PBUFFER_WIDTH # if defined MaxPbufferWidth # pragma push_macro("MaxPbufferWidth") # undef MaxPbufferWidth Transform<ConfigAttrib::MaxPbufferWidth> MaxPbufferWidth; # pragma pop_macro("MaxPbufferWidth") # else Transform<ConfigAttrib::MaxPbufferWidth> MaxPbufferWidth; # endif #endif #if defined EGL_MAX_PBUFFER_HEIGHT # if defined MaxPbufferHeight # pragma push_macro("MaxPbufferHeight") # undef MaxPbufferHeight Transform<ConfigAttrib::MaxPbufferHeight> MaxPbufferHeight; # pragma pop_macro("MaxPbufferHeight") # else Transform<ConfigAttrib::MaxPbufferHeight> MaxPbufferHeight; # endif #endif #if defined EGL_MAX_PBUFFER_PIXELS # if defined MaxPbufferPixels # pragma push_macro("MaxPbufferPixels") # undef MaxPbufferPixels Transform<ConfigAttrib::MaxPbufferPixels> MaxPbufferPixels; # pragma pop_macro("MaxPbufferPixels") # else Transform<ConfigAttrib::MaxPbufferPixels> MaxPbufferPixels; # endif #endif #if defined EGL_MAX_SWAP_INTERVAL # if defined MaxSwapInterval # pragma push_macro("MaxSwapInterval") # undef MaxSwapInterval Transform<ConfigAttrib::MaxSwapInterval> MaxSwapInterval; # pragma pop_macro("MaxSwapInterval") # else Transform<ConfigAttrib::MaxSwapInterval> MaxSwapInterval; # endif #endif #if defined EGL_MIN_SWAP_INTERVAL # if defined MinSwapInterval # pragma push_macro("MinSwapInterval") # undef MinSwapInterval Transform<ConfigAttrib::MinSwapInterval> MinSwapInterval; # pragma pop_macro("MinSwapInterval") # else Transform<ConfigAttrib::MinSwapInterval> MinSwapInterval; # endif #endif #if defined EGL_NATIVE_RENDERABLE # if defined NativeRenderable # pragma push_macro("NativeRenderable") # undef NativeRenderable Transform<ConfigAttrib::NativeRenderable> NativeRenderable; # pragma pop_macro("NativeRenderable") # else Transform<ConfigAttrib::NativeRenderable> NativeRenderable; # endif #endif #if defined EGL_NATIVE_VISUAL_ID # if defined NativeVisualId # pragma push_macro("NativeVisualId") # undef NativeVisualId Transform<ConfigAttrib::NativeVisualId> NativeVisualId; # pragma pop_macro("NativeVisualId") # else Transform<ConfigAttrib::NativeVisualId> NativeVisualId; # endif #endif #if defined EGL_NATIVE_VISUAL_TYPE # if defined NativeVisualType # pragma push_macro("NativeVisualType") # undef NativeVisualType Transform<ConfigAttrib::NativeVisualType> NativeVisualType; # pragma pop_macro("NativeVisualType") # else Transform<ConfigAttrib::NativeVisualType> NativeVisualType; # endif #endif #if defined EGL_RENDERABLE_TYPE # if defined RenderableType # pragma push_macro("RenderableType") # undef RenderableType Transform<ConfigAttrib::RenderableType> RenderableType; # pragma pop_macro("RenderableType") # else Transform<ConfigAttrib::RenderableType> RenderableType; # endif #endif #if defined EGL_SAMPLE_BUFFERS # if defined SampleBuffers # pragma push_macro("SampleBuffers") # undef SampleBuffers Transform<ConfigAttrib::SampleBuffers> SampleBuffers; # pragma pop_macro("SampleBuffers") # else Transform<ConfigAttrib::SampleBuffers> SampleBuffers; # endif #endif #if defined EGL_SAMPLES # if defined Samples # pragma push_macro("Samples") # undef Samples Transform<ConfigAttrib::Samples> Samples; # pragma pop_macro("Samples") # else Transform<ConfigAttrib::Samples> Samples; # endif #endif #if defined EGL_STENCIL_SIZE # if defined StencilSize # pragma push_macro("StencilSize") # undef StencilSize Transform<ConfigAttrib::StencilSize> StencilSize; # pragma pop_macro("StencilSize") # else Transform<ConfigAttrib::StencilSize> StencilSize; # endif #endif #if defined EGL_SURFACE_TYPE # if defined SurfaceType # pragma push_macro("SurfaceType") # undef SurfaceType Transform<ConfigAttrib::SurfaceType> SurfaceType; # pragma pop_macro("SurfaceType") # else Transform<ConfigAttrib::SurfaceType> SurfaceType; # endif #endif #if defined EGL_TRANSPARENT_TYPE # if defined TransparentType # pragma push_macro("TransparentType") # undef TransparentType Transform<ConfigAttrib::TransparentType> TransparentType; # pragma pop_macro("TransparentType") # else Transform<ConfigAttrib::TransparentType> TransparentType; # endif #endif #if defined EGL_TRANSPARENT_RED_VALUE # if defined TransparentRedValue # pragma push_macro("TransparentRedValue") # undef TransparentRedValue Transform<ConfigAttrib::TransparentRedValue> TransparentRedValue; # pragma pop_macro("TransparentRedValue") # else Transform<ConfigAttrib::TransparentRedValue> TransparentRedValue; # endif #endif #if defined EGL_TRANSPARENT_GREEN_VALUE # if defined TransparentGreenValue # pragma push_macro("TransparentGreenValue") # undef TransparentGreenValue Transform<ConfigAttrib::TransparentGreenValue> TransparentGreenValue; # pragma pop_macro("TransparentGreenValue") # else Transform<ConfigAttrib::TransparentGreenValue> TransparentGreenValue; # endif #endif #if defined EGL_TRANSPARENT_BLUE_VALUE # if defined TransparentBlueValue # pragma push_macro("TransparentBlueValue") # undef TransparentBlueValue Transform<ConfigAttrib::TransparentBlueValue> TransparentBlueValue; # pragma pop_macro("TransparentBlueValue") # else Transform<ConfigAttrib::TransparentBlueValue> TransparentBlueValue; # endif #endif EnumToClass(void) { } EnumToClass(Base&& base) : Base(std::move(base)) #if defined EGL_BUFFER_SIZE # if defined BufferSize # pragma push_macro("BufferSize") # undef BufferSize , BufferSize(_base()) # pragma pop_macro("BufferSize") # else , BufferSize(_base()) # endif #endif #if defined EGL_RED_SIZE # if defined RedSize # pragma push_macro("RedSize") # undef RedSize , RedSize(_base()) # pragma pop_macro("RedSize") # else , RedSize(_base()) # endif #endif #if defined EGL_GREEN_SIZE # if defined GreenSize # pragma push_macro("GreenSize") # undef GreenSize , GreenSize(_base()) # pragma pop_macro("GreenSize") # else , GreenSize(_base()) # endif #endif #if defined EGL_BLUE_SIZE # if defined BlueSize # pragma push_macro("BlueSize") # undef BlueSize , BlueSize(_base()) # pragma pop_macro("BlueSize") # else , BlueSize(_base()) # endif #endif #if defined EGL_LUMINANCE_SIZE # if defined LuminanceSize # pragma push_macro("LuminanceSize") # undef LuminanceSize , LuminanceSize(_base()) # pragma pop_macro("LuminanceSize") # else , LuminanceSize(_base()) # endif #endif #if defined EGL_ALPHA_SIZE # if defined AlphaSize # pragma push_macro("AlphaSize") # undef AlphaSize , AlphaSize(_base()) # pragma pop_macro("AlphaSize") # else , AlphaSize(_base()) # endif #endif #if defined EGL_ALPHA_MASK_SIZE # if defined AlphaMaskSize # pragma push_macro("AlphaMaskSize") # undef AlphaMaskSize , AlphaMaskSize(_base()) # pragma pop_macro("AlphaMaskSize") # else , AlphaMaskSize(_base()) # endif #endif #if defined EGL_BIND_TO_TEXTURE_RGB # if defined BindToTextureRGB # pragma push_macro("BindToTextureRGB") # undef BindToTextureRGB , BindToTextureRGB(_base()) # pragma pop_macro("BindToTextureRGB") # else , BindToTextureRGB(_base()) # endif #endif #if defined EGL_BIND_TO_TEXTURE_RGBA # if defined BindToTextureRGBA # pragma push_macro("BindToTextureRGBA") # undef BindToTextureRGBA , BindToTextureRGBA(_base()) # pragma pop_macro("BindToTextureRGBA") # else , BindToTextureRGBA(_base()) # endif #endif #if defined EGL_COLOR_BUFFER_TYPE # if defined ColorBufferType # pragma push_macro("ColorBufferType") # undef ColorBufferType , ColorBufferType(_base()) # pragma pop_macro("ColorBufferType") # else , ColorBufferType(_base()) # endif #endif #if defined EGL_CONFIG_CAVEAT # if defined ConfigCaveat # pragma push_macro("ConfigCaveat") # undef ConfigCaveat , ConfigCaveat(_base()) # pragma pop_macro("ConfigCaveat") # else , ConfigCaveat(_base()) # endif #endif #if defined EGL_CONFIG_ID # if defined ConfigId # pragma push_macro("ConfigId") # undef ConfigId , ConfigId(_base()) # pragma pop_macro("ConfigId") # else , ConfigId(_base()) # endif #endif #if defined EGL_CONFORMANT # if defined Conformant # pragma push_macro("Conformant") # undef Conformant , Conformant(_base()) # pragma pop_macro("Conformant") # else , Conformant(_base()) # endif #endif #if defined EGL_DEPTH_SIZE # if defined DepthSize # pragma push_macro("DepthSize") # undef DepthSize , DepthSize(_base()) # pragma pop_macro("DepthSize") # else , DepthSize(_base()) # endif #endif #if defined EGL_LEVEL # if defined Level # pragma push_macro("Level") # undef Level , Level(_base()) # pragma pop_macro("Level") # else , Level(_base()) # endif #endif #if defined EGL_MAX_PBUFFER_WIDTH # if defined MaxPbufferWidth # pragma push_macro("MaxPbufferWidth") # undef MaxPbufferWidth , MaxPbufferWidth(_base()) # pragma pop_macro("MaxPbufferWidth") # else , MaxPbufferWidth(_base()) # endif #endif #if defined EGL_MAX_PBUFFER_HEIGHT # if defined MaxPbufferHeight # pragma push_macro("MaxPbufferHeight") # undef MaxPbufferHeight , MaxPbufferHeight(_base()) # pragma pop_macro("MaxPbufferHeight") # else , MaxPbufferHeight(_base()) # endif #endif #if defined EGL_MAX_PBUFFER_PIXELS # if defined MaxPbufferPixels # pragma push_macro("MaxPbufferPixels") # undef MaxPbufferPixels , MaxPbufferPixels(_base()) # pragma pop_macro("MaxPbufferPixels") # else , MaxPbufferPixels(_base()) # endif #endif #if defined EGL_MAX_SWAP_INTERVAL # if defined MaxSwapInterval # pragma push_macro("MaxSwapInterval") # undef MaxSwapInterval , MaxSwapInterval(_base()) # pragma pop_macro("MaxSwapInterval") # else , MaxSwapInterval(_base()) # endif #endif #if defined EGL_MIN_SWAP_INTERVAL # if defined MinSwapInterval # pragma push_macro("MinSwapInterval") # undef MinSwapInterval , MinSwapInterval(_base()) # pragma pop_macro("MinSwapInterval") # else , MinSwapInterval(_base()) # endif #endif #if defined EGL_NATIVE_RENDERABLE # if defined NativeRenderable # pragma push_macro("NativeRenderable") # undef NativeRenderable , NativeRenderable(_base()) # pragma pop_macro("NativeRenderable") # else , NativeRenderable(_base()) # endif #endif #if defined EGL_NATIVE_VISUAL_ID # if defined NativeVisualId # pragma push_macro("NativeVisualId") # undef NativeVisualId , NativeVisualId(_base()) # pragma pop_macro("NativeVisualId") # else , NativeVisualId(_base()) # endif #endif #if defined EGL_NATIVE_VISUAL_TYPE # if defined NativeVisualType # pragma push_macro("NativeVisualType") # undef NativeVisualType , NativeVisualType(_base()) # pragma pop_macro("NativeVisualType") # else , NativeVisualType(_base()) # endif #endif #if defined EGL_RENDERABLE_TYPE # if defined RenderableType # pragma push_macro("RenderableType") # undef RenderableType , RenderableType(_base()) # pragma pop_macro("RenderableType") # else , RenderableType(_base()) # endif #endif #if defined EGL_SAMPLE_BUFFERS # if defined SampleBuffers # pragma push_macro("SampleBuffers") # undef SampleBuffers , SampleBuffers(_base()) # pragma pop_macro("SampleBuffers") # else , SampleBuffers(_base()) # endif #endif #if defined EGL_SAMPLES # if defined Samples # pragma push_macro("Samples") # undef Samples , Samples(_base()) # pragma pop_macro("Samples") # else , Samples(_base()) # endif #endif #if defined EGL_STENCIL_SIZE # if defined StencilSize # pragma push_macro("StencilSize") # undef StencilSize , StencilSize(_base()) # pragma pop_macro("StencilSize") # else , StencilSize(_base()) # endif #endif #if defined EGL_SURFACE_TYPE # if defined SurfaceType # pragma push_macro("SurfaceType") # undef SurfaceType , SurfaceType(_base()) # pragma pop_macro("SurfaceType") # else , SurfaceType(_base()) # endif #endif #if defined EGL_TRANSPARENT_TYPE # if defined TransparentType # pragma push_macro("TransparentType") # undef TransparentType , TransparentType(_base()) # pragma pop_macro("TransparentType") # else , TransparentType(_base()) # endif #endif #if defined EGL_TRANSPARENT_RED_VALUE # if defined TransparentRedValue # pragma push_macro("TransparentRedValue") # undef TransparentRedValue , TransparentRedValue(_base()) # pragma pop_macro("TransparentRedValue") # else , TransparentRedValue(_base()) # endif #endif #if defined EGL_TRANSPARENT_GREEN_VALUE # if defined TransparentGreenValue # pragma push_macro("TransparentGreenValue") # undef TransparentGreenValue , TransparentGreenValue(_base()) # pragma pop_macro("TransparentGreenValue") # else , TransparentGreenValue(_base()) # endif #endif #if defined EGL_TRANSPARENT_BLUE_VALUE # if defined TransparentBlueValue # pragma push_macro("TransparentBlueValue") # undef TransparentBlueValue , TransparentBlueValue(_base()) # pragma pop_macro("TransparentBlueValue") # else , TransparentBlueValue(_base()) # endif #endif { } }; } // namespace enums
25.967164
70
0.778653
[ "transform" ]
ebcd0a91698f73e82058c7b8d7504d76c8349fc6
20,171
cpp
C++
tests/Unit/Evolution/Systems/Cce/Test_InitializeCce.cpp
kidder/spectre
97ae95f72320f9f67895d3303824e64de6fd9077
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
tests/Unit/Evolution/Systems/Cce/Test_InitializeCce.cpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
tests/Unit/Evolution/Systems/Cce/Test_InitializeCce.cpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <cstddef> #include <limits> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/SpinWeighted.hpp" #include "DataStructures/Variables.hpp" #include "Evolution/Systems/Cce/GaugeTransformBoundaryData.hpp" #include "Evolution/Systems/Cce/Initialize/InitializeJ.hpp" #include "Evolution/Systems/Cce/Initialize/InverseCubic.hpp" #include "Evolution/Systems/Cce/Initialize/NoIncomingRadiation.hpp" #include "Evolution/Systems/Cce/Initialize/ZeroNonSmooth.hpp" #include "Evolution/Systems/Cce/LinearOperators.hpp" #include "Evolution/Systems/Cce/NewmanPenrose.hpp" #include "Evolution/Systems/Cce/OptionTags.hpp" #include "Evolution/Systems/Cce/PreSwshDerivatives.hpp" #include "Evolution/Systems/Cce/PrecomputeCceDependencies.hpp" #include "Framework/TestHelpers.hpp" #include "Helpers/DataStructures/MakeWithRandomValues.hpp" #include "Helpers/NumericalAlgorithms/Spectral/SwshTestHelpers.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" #include "NumericalAlgorithms/Spectral/SwshCollocation.hpp" #include "NumericalAlgorithms/Spectral/SwshFiltering.hpp" #include "Utilities/Gsl.hpp" namespace Cce { template <typename DbTags> void test_initialize_j_inverse_cubic( const gsl::not_null<db::DataBox<DbTags>*> box_to_initialize, const size_t l_max, const size_t number_of_radial_points) { db::mutate_apply<InitializeJ::InitializeJ<true>::mutate_tags, InitializeJ::InitializeJ<true>::argument_tags>( InitializeJ::InverseCubic<true>{}, box_to_initialize); SpinWeighted<ComplexDataVector, 2> dy_j{ number_of_radial_points * Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; SpinWeighted<ComplexDataVector, 2> dy_dy_j{ number_of_radial_points * Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; logical_partial_directional_derivative_of_complex( make_not_null(&dy_j.data()), get(db::get<Tags::BondiJ>(*box_to_initialize)).data(), Mesh<3>{{{Spectral::Swsh::number_of_swsh_theta_collocation_points(l_max), Spectral::Swsh::number_of_swsh_phi_collocation_points(l_max), number_of_radial_points}}, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}, 2); logical_partial_directional_derivative_of_complex( make_not_null(&dy_dy_j.data()), dy_j.data(), Mesh<3>{{{Spectral::Swsh::number_of_swsh_theta_collocation_points(l_max), Spectral::Swsh::number_of_swsh_phi_collocation_points(l_max), number_of_radial_points}}, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}, 2); // The goal for this initial data is that it should: // - match the value of J and its first derivative on the boundary // - have vanishing value and second derivative at scri+ ComplexDataVector mutable_j_copy = get(db::get<Tags::BondiJ>(*box_to_initialize)).data(); const auto boundary_slice_j = ComplexDataVector{ mutable_j_copy.data(), Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; const auto boundary_slice_dy_j = ComplexDataVector{ dy_j.data().data(), Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; const auto scri_slice_j = ComplexDataVector{ mutable_j_copy.data() + (number_of_radial_points - 1) * Spectral::Swsh::number_of_swsh_collocation_points(l_max), Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; const auto scri_slice_dy_dy_j = ComplexDataVector{ dy_dy_j.data().data() + (number_of_radial_points - 1) * Spectral::Swsh::number_of_swsh_collocation_points(l_max), Spectral::Swsh::number_of_swsh_collocation_points(l_max)}; Approx cce_approx = Approx::custom() .epsilon(std::numeric_limits<double>::epsilon() * 1.0e4) .scale(1.0); CHECK_ITERABLE_CUSTOM_APPROX( get(db::get<Tags::BoundaryValue<Tags::BondiJ>>(*box_to_initialize)) .data(), boundary_slice_j, cce_approx); const auto boundary_slice_dr_j = (2.0 / get(db::get<Tags::BoundaryValue<Tags::BondiR>>(*box_to_initialize)) .data()) * boundary_slice_dy_j; CHECK_ITERABLE_CUSTOM_APPROX( boundary_slice_dr_j, get(db::get<Tags::BoundaryValue<Tags::Dr<Tags::BondiJ>>>( *box_to_initialize)) .data(), cce_approx); const ComplexDataVector scri_plus_zeroes{ Spectral::Swsh::number_of_swsh_collocation_points(l_max), 0.0}; CHECK_ITERABLE_CUSTOM_APPROX(scri_slice_j, scri_plus_zeroes, cce_approx); CHECK_ITERABLE_CUSTOM_APPROX(scri_slice_dy_dy_j, scri_plus_zeroes, cce_approx); } template <typename DbTags> void test_initialize_j_zero_nonsmooth( const gsl::not_null<db::DataBox<DbTags>*> box_to_initialize, const size_t /*l_max*/, const size_t /*number_of_radial_points*/) { // The iterative procedure can reach error levels better than 1.0e-8, but it // is difficult to do so reliably and quickly for randomly generated data. db::mutate_apply<InitializeJ::InitializeJ<false>::mutate_tags, InitializeJ::InitializeJ<false>::argument_tags>( InitializeJ::ZeroNonSmooth{1.0e-8, 400}, box_to_initialize); // note we want to copy here to compare against the next version of the // computation // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) const auto initialized_j = db::get<Tags::BondiJ>(*box_to_initialize); const auto initializer = InitializeJ::ZeroNonSmooth{1.0e-8, 400}; const auto serialized_and_deserialized_initializer = serialize_and_deserialize(initializer); db::mutate_apply<InitializeJ::InitializeJ<false>::mutate_tags, InitializeJ::InitializeJ<false>::argument_tags>( serialized_and_deserialized_initializer, box_to_initialize); const auto& initialized_j_from_serialized_and_deserialized = db::get<Tags::BondiJ>(*box_to_initialize); CHECK_ITERABLE_APPROX( get(initialized_j).data(), get(initialized_j_from_serialized_and_deserialized).data()); // generate the extra gauge quantities and verify that the boundary value for // J is indeed within the tolerance. db::mutate_apply<GaugeUpdateAngularFromCartesian< Tags::CauchyAngularCoords, Tags::CauchyCartesianCoords>>( box_to_initialize); db::mutate_apply<GaugeUpdateJacobianFromCoordinates< Tags::PartiallyFlatGaugeC, Tags::PartiallyFlatGaugeD, Tags::CauchyAngularCoords, Tags::CauchyCartesianCoords>>( box_to_initialize); db::mutate_apply<GaugeUpdateInterpolator<Tags::CauchyAngularCoords>>( box_to_initialize); db::mutate_apply< GaugeUpdateOmega<Tags::PartiallyFlatGaugeC, Tags::PartiallyFlatGaugeD, Tags::PartiallyFlatGaugeOmega>>(box_to_initialize); db::mutate_apply<GaugeAdjustedBoundaryValue<Tags::BondiJ>>(box_to_initialize); const auto& gauge_adjusted_boundary_j = db::get<Tags::EvolutionGaugeBoundaryValue<Tags::BondiJ>>( *box_to_initialize); for (auto val : get(gauge_adjusted_boundary_j).data()) { CHECK(real(val) < 1.0e-8); CHECK(imag(val) < 1.0e-8); } for (auto val : get(initialized_j).data()) { CHECK(real(val) < 1.0e-8); CHECK(imag(val) < 1.0e-8); } } // [[OutputRegex, Initial data iterative angular solve]] [[noreturn]] SPECTRE_TEST_CASE( "Unit.Evolution.Systems.Cce.InitializeJ.ZeroNonSmoothError", "[Unit][Cce]") { ERROR_TEST(); MAKE_GENERATOR(generator); UniformCustomDistribution<size_t> sdist{5, 8}; const size_t l_max = sdist(generator); const size_t number_of_radial_points = sdist(generator); using boundary_variables_tag = ::Tags::Variables<InitializeJ::InverseCubic<false>::boundary_tags>; using pre_swsh_derivatives_variables_tag = ::Tags::Variables<tmpl::list<Tags::BondiJ>>; using tensor_variables_tag = ::Tags::Variables< tmpl::list<Tags::CauchyCartesianCoords, Tags::CauchyAngularCoords>>; const size_t number_of_boundary_points = Spectral::Swsh::number_of_swsh_collocation_points(l_max); const size_t number_of_volume_points = number_of_boundary_points * number_of_radial_points; auto box_to_initialize = db::create<db::AddSimpleTags< boundary_variables_tag, pre_swsh_derivatives_variables_tag, tensor_variables_tag, Tags::LMax, Tags::NumberOfRadialPoints, Spectral::Swsh::Tags::SwshInterpolator<Tags::CauchyAngularCoords>>>( typename boundary_variables_tag::type{number_of_boundary_points}, typename pre_swsh_derivatives_variables_tag::type{ number_of_volume_points}, typename tensor_variables_tag::type{number_of_boundary_points}, l_max, number_of_radial_points, Spectral::Swsh::SwshInterpolator{}); // generate some random values for the boundary data. Mode magnitudes are // roughly representative of typical strains seen in simulations, and are of a // scale that can be fully solved by the iterative procedure used in the more // elaborate initial data generators. UniformCustomDistribution<double> dist(1.0e-5, 1.0e-4); db::mutate<Tags::BoundaryValue<Tags::BondiR>, Tags::BoundaryValue<Tags::Dr<Tags::BondiJ>>, Tags::BoundaryValue<Tags::BondiJ>>( make_not_null(&box_to_initialize), [&generator, &dist, &l_max]( const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 0>>*> boundary_r, const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 2>>*> boundary_dr_j, const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 2>>*> boundary_j) { SpinWeighted<ComplexModalVector, 2> generated_modes{ Spectral::Swsh::size_of_libsharp_coefficient_vector(l_max)}; Spectral::Swsh::TestHelpers::generate_swsh_modes<2>( make_not_null(&generated_modes.data()), make_not_null(&generator), make_not_null(&dist), 1, l_max); get(*boundary_j) = Spectral::Swsh::inverse_swsh_transform(l_max, 1, generated_modes); Spectral::Swsh::filter_swsh_boundary_quantity( make_not_null(&get(*boundary_j)), l_max, l_max / 2); Spectral::Swsh::TestHelpers::generate_swsh_modes<2>( make_not_null(&generated_modes.data()), make_not_null(&generator), make_not_null(&dist), 1, l_max); get(*boundary_dr_j) = Spectral::Swsh::inverse_swsh_transform(l_max, 1, generated_modes) / 10.0; SpinWeighted<ComplexModalVector, 0> generated_r_modes{ Spectral::Swsh::size_of_libsharp_coefficient_vector(l_max)}; Spectral::Swsh::TestHelpers::generate_swsh_modes<0>( make_not_null(&generated_modes.data()), make_not_null(&generator), make_not_null(&dist), 1, l_max); get(*boundary_r) = Spectral::Swsh::inverse_swsh_transform( l_max, 1, generated_r_modes) + 10.0; Spectral::Swsh::filter_swsh_boundary_quantity( make_not_null(&get(*boundary_r)), l_max, l_max / 2); }); db::mutate_apply<InitializeJ::InitializeJ<false>::mutate_tags, InitializeJ::InitializeJ<false>::argument_tags>( InitializeJ::ZeroNonSmooth{1.0e-12, 1, true}, make_not_null(&box_to_initialize)); ERROR("Failed to trigger ERROR in an error test"); } template <typename DbTags> void test_initialize_j_no_radiation( const gsl::not_null<db::DataBox<DbTags>*> box_to_initialize, const size_t l_max, const size_t /*number_of_radial_points*/) { // The iterative procedure can reach error levels better than 1.0e-8, but it // is difficult to do so reliably and quickly for randomly generated data. db::mutate_apply<InitializeJ::InitializeJ<false>::mutate_tags, InitializeJ::InitializeJ<false>::argument_tags>( InitializeJ::NoIncomingRadiation{1.0e-8, 400}, box_to_initialize); // note we want to copy here to compare against the next version of the // computation // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) const auto initialized_j = db::get<Tags::BondiJ>(*box_to_initialize); const auto initializer = InitializeJ::NoIncomingRadiation{1.0e-8, 400}; const auto serialized_and_deserialized_initializer = serialize_and_deserialize(initializer); db::mutate_apply<InitializeJ::InitializeJ<false>::mutate_tags, InitializeJ::InitializeJ<false>::argument_tags>( serialized_and_deserialized_initializer, box_to_initialize); const auto& initialized_j_from_serialized_and_deserialized = db::get<Tags::BondiJ>(*box_to_initialize); CHECK_ITERABLE_APPROX( get(initialized_j).data(), get(initialized_j_from_serialized_and_deserialized).data()); db::mutate_apply<GaugeUpdateAngularFromCartesian< Tags::CauchyAngularCoords, Tags::CauchyCartesianCoords>>( box_to_initialize); db::mutate_apply<GaugeUpdateJacobianFromCoordinates< Tags::PartiallyFlatGaugeC, Tags::PartiallyFlatGaugeD, Tags::CauchyAngularCoords, Tags::CauchyCartesianCoords>>( box_to_initialize); db::mutate_apply<GaugeUpdateInterpolator<Tags::CauchyAngularCoords>>( box_to_initialize); db::mutate_apply< GaugeUpdateOmega<Tags::PartiallyFlatGaugeC, Tags::PartiallyFlatGaugeD, Tags::PartiallyFlatGaugeOmega>>(box_to_initialize); db::mutate_apply<PrecomputeCceDependencies<Tags::EvolutionGaugeBoundaryValue, Tags::OneMinusY>>( box_to_initialize); db::mutate_apply<GaugeAdjustedBoundaryValue<Tags::BondiJ>>(box_to_initialize); // check that the gauge-transformed boundary data matches up. const auto& boundary_gauge_j = db::get<Tags::EvolutionGaugeBoundaryValue<Tags::BondiJ>>( *box_to_initialize); for (size_t i = 0; i < Spectral::Swsh::number_of_swsh_collocation_points(l_max); ++i) { CHECK(approx(real(get(initialized_j).data()[i])) == real(get(boundary_gauge_j).data()[i])); CHECK(approx(imag(get(initialized_j).data()[i])) == imag(get(boundary_gauge_j).data()[i])); } db::mutate_apply<GaugeAdjustedBoundaryValue<Tags::BondiR>>(box_to_initialize); db::mutate_apply<PrecomputeCceDependencies<Tags::EvolutionGaugeBoundaryValue, Tags::BondiR>>(box_to_initialize); db::mutate_apply<PrecomputeCceDependencies<Tags::EvolutionGaugeBoundaryValue, Tags::BondiK>>(box_to_initialize); db::mutate_apply<PreSwshDerivatives<Tags::Dy<Tags::BondiJ>>>( box_to_initialize); db::mutate_apply<PreSwshDerivatives<Tags::Dy<Tags::Dy<Tags::BondiJ>>>>( box_to_initialize); db::mutate_apply<VolumeWeyl<Tags::Psi0>>(box_to_initialize); Approx cce_approx = Approx::custom() .epsilon(std::numeric_limits<double>::epsilon() * 1.0e5) .scale(1.0); // check that the psi_0 condition holds to acceptable precision -- note the // result of this involves multiple numerical derivatives, so needs to be // slightly loose. for (auto val : get(db::get<Tags::Psi0>(*box_to_initialize)).data()) { CHECK(cce_approx(real(val)) == 0.0); CHECK(cce_approx(imag(val)) == 0.0); } } SPECTRE_TEST_CASE("Unit.Evolution.Systems.Cce.InitializeJ", "[Unit][Cce]") { MAKE_GENERATOR(generator); UniformCustomDistribution<size_t> sdist{5, 8}; const size_t l_max = sdist(generator); const size_t number_of_radial_points = sdist(generator); using boundary_variables_tag = ::Tags::Variables<tmpl::push_back< InitializeJ::InverseCubic<true>::boundary_tags, Tags::PartiallyFlatGaugeC, Tags::PartiallyFlatGaugeD, Tags::PartiallyFlatGaugeOmega, Spectral::Swsh::Tags::Derivative<Tags::PartiallyFlatGaugeOmega, Spectral::Swsh::Tags::Eth>, Tags::EvolutionGaugeBoundaryValue<Tags::BondiJ>, Tags::EvolutionGaugeBoundaryValue<Tags::BondiR>>>; using pre_swsh_derivatives_variables_tag = ::Tags::Variables<tmpl::list< Tags::BondiJ, Tags::Dy<Tags::BondiJ>, Tags::Dy<Tags::Dy<Tags::BondiJ>>, Tags::BondiK, Tags::BondiR, Tags::OneMinusY, Tags::Psi0>>; using tensor_variables_tag = ::Tags::Variables<tmpl::list< Tags::CauchyCartesianCoords, Tags::CauchyAngularCoords, Tags::PartiallyFlatCartesianCoords, Tags::PartiallyFlatAngularCoords>>; const size_t number_of_boundary_points = Spectral::Swsh::number_of_swsh_collocation_points(l_max); const size_t number_of_volume_points = number_of_boundary_points * number_of_radial_points; auto box_to_initialize = db::create<db::AddSimpleTags< boundary_variables_tag, pre_swsh_derivatives_variables_tag, tensor_variables_tag, Tags::LMax, Tags::NumberOfRadialPoints, Spectral::Swsh::Tags::SwshInterpolator<Tags::CauchyAngularCoords>>>( typename boundary_variables_tag::type{number_of_boundary_points}, typename pre_swsh_derivatives_variables_tag::type{ number_of_volume_points}, typename tensor_variables_tag::type{number_of_boundary_points}, l_max, number_of_radial_points, Spectral::Swsh::SwshInterpolator{}); // generate some random values for the boundary data. Mode magnitudes are // roughly representative of typical strains seen in simulations, and are of a // scale that can be fully solved by the iterative procedure used in the more // elaborate initial data generators. UniformCustomDistribution<double> dist(1.0e-5, 1.0e-4); db::mutate<Tags::BoundaryValue<Tags::BondiR>, Tags::BoundaryValue<Tags::Dr<Tags::BondiJ>>, Tags::BoundaryValue<Tags::BondiJ>>( make_not_null(&box_to_initialize), [&generator, &dist, &l_max]( const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 0>>*> boundary_r, const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 2>>*> boundary_dr_j, const gsl::not_null<Scalar<SpinWeighted<ComplexDataVector, 2>>*> boundary_j) { SpinWeighted<ComplexModalVector, 2> generated_modes{ Spectral::Swsh::size_of_libsharp_coefficient_vector(l_max)}; Spectral::Swsh::TestHelpers::generate_swsh_modes<2>( make_not_null(&generated_modes.data()), make_not_null(&generator), make_not_null(&dist), 1, l_max); get(*boundary_j) = Spectral::Swsh::inverse_swsh_transform(l_max, 1, generated_modes); Spectral::Swsh::filter_swsh_boundary_quantity( make_not_null(&get(*boundary_j)), l_max, l_max / 2); SpinWeighted<ComplexModalVector, 0> generated_r_modes{ Spectral::Swsh::size_of_libsharp_coefficient_vector(l_max)}; Spectral::Swsh::TestHelpers::generate_swsh_modes<0>( make_not_null(&generated_modes.data()), make_not_null(&generator), make_not_null(&dist), 1, l_max); get(*boundary_r) = Spectral::Swsh::inverse_swsh_transform( l_max, 1, generated_r_modes) + 10.0; Spectral::Swsh::filter_swsh_boundary_quantity( make_not_null(&get(*boundary_r)), l_max, l_max / 2); get(*boundary_dr_j) = -get(*boundary_j) / get(*boundary_r); }); SECTION("Check inverse cubic initial data generator") { test_initialize_j_inverse_cubic(make_not_null(&box_to_initialize), l_max, number_of_radial_points); } SECTION("Check zero nonsmooth initial data generator") { test_initialize_j_zero_nonsmooth(make_not_null(&box_to_initialize), l_max, number_of_radial_points); } SECTION("Check no incoming radiation initial data generator") { test_initialize_j_no_radiation(make_not_null(&box_to_initialize), l_max, number_of_radial_points); } } } // namespace Cce
46.909302
80
0.70993
[ "mesh" ]
ebd3363fc58c83e3118969e140db3850845205b2
3,018
hpp
C++
src/hotspot/share/opto/replacednodes.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/opto/replacednodes.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/opto/replacednodes.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_OPTO_REPLACEDNODES_HPP #define SHARE_OPTO_REPLACEDNODES_HPP #include "opto/connode.hpp" // During parsing, when a node is "improved", // GraphKit::replace_in_map() is called to update the current map so // that the improved node is used from that point // on. GraphKit::replace_in_map() doesn't operate on the callers maps // and so some optimization opportunities may be lost. The // ReplacedNodes class addresses that problem. // // A ReplacedNodes object is a list of pair of nodes. Every // SafePointNode carries a ReplacedNodes object. Every time // GraphKit::replace_in_map() is called, a new pair of nodes is pushed // on the list of replaced nodes. When control flow paths merge, their // replaced nodes are also merged. When parsing exits a method to // return to a caller, the replaced nodes on the exit path are used to // update the caller's map. class ReplacedNodes { private: class ReplacedNode { private: Node* _initial; Node* _improved; public: ReplacedNode() : _initial(NULL), _improved(NULL) {} ReplacedNode(Node* initial, Node* improved) : _initial(initial), _improved(improved) {} Node* initial() const { return _initial; } Node* improved() const { return _improved; } bool operator==(const ReplacedNode& other) { return _initial == other._initial && _improved == other._improved; } }; GrowableArray<ReplacedNode>* _replaced_nodes; void allocate_if_necessary(); bool has_node(const ReplacedNode& r) const; bool has_target_node(Node* n) const; public: ReplacedNodes() : _replaced_nodes(NULL) {} void clone(); void record(Node* initial, Node* improved); void transfer_from(const ReplacedNodes& other, uint idx); void reset(); void apply(Node* n, uint idx); void merge_with(const ReplacedNodes& other); bool is_empty() const; void dump(outputStream *st) const; void apply(Compile* C, Node* ctl); }; #endif // SHARE_OPTO_REPLACEDNODES_HPP
36.804878
91
0.734924
[ "object" ]
ebd7cd0ee9d4279143ec844a40911a93d8f6a3fa
58,804
cpp
C++
src/nc/core/ir/cgen/DefinitionGenerator.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
6
2016-09-06T02:10:08.000Z
2021-01-19T09:02:04.000Z
src/nc/core/ir/cgen/DefinitionGenerator.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
null
null
null
src/nc/core/ir/cgen/DefinitionGenerator.cpp
treadstoneproject/tracethreat_nrml
bcf666b01c20f7da4234fed018dad3b2cf4d3d28
[ "Apache-2.0" ]
6
2015-10-02T14:11:45.000Z
2021-01-19T09:02:07.000Z
/* The file is part of Snowman decompiler. */ /* See doc/licenses.asciidoc for the licensing information. */ // // SmartDec decompiler - SmartDec is a native code to C/C++ decompiler // Copyright (C) 2015 Alexander Chernov, Katerina Troshina, Yegor Derevenets, // Alexander Fokin, Sergey Levin, Leonid Tsvetkov // // This file is part of SmartDec decompiler. // // SmartDec decompiler is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SmartDec decompiler is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SmartDec decompiler. If not, see <http://www.gnu.org/licenses/>. // #include "DefinitionGenerator.h" #include <nc/common/Foreach.h> #include <nc/common/Range.h> #include <nc/common/Unreachable.h> #include <nc/common/make_unique.h> #include <nc/core/arch/Architecture.h> #include <nc/core/arch/Instruction.h> #include <nc/core/image/Image.h> #ifdef NC_PREFER_CSTRINGS_TO_CONSTANTS #include <nc/core/image/Reader.h> #include <nc/core/image/Section.h> #endif #include <nc/core/ir/BasicBlock.h> #include <nc/core/ir/CFG.h> #include <nc/core/ir/Dominators.h> #include <nc/core/ir/Function.h> #include <nc/core/ir/Jump.h> #include <nc/core/ir/Statements.h> #include <nc/core/ir/Terms.h> #include <nc/core/ir/calling/CallHook.h> #include <nc/core/ir/calling/Hooks.h> #include <nc/core/ir/calling/EntryHook.h> #include <nc/core/ir/calling/Signatures.h> #include <nc/core/ir/calling/ReturnHook.h> #include <nc/core/ir/cflow/BasicNode.h> #include <nc/core/ir/cflow/Dfs.h> #include <nc/core/ir/cflow/Graphs.h> #include <nc/core/ir/cflow/Switch.h> #include <nc/core/ir/dflow/Dataflows.h> #include <nc/core/ir/dflow/Uses.h> #include <nc/core/ir/dflow/Utils.h> #include <nc/core/ir/dflow/Value.h> #include <nc/core/ir/liveness/Livenesses.h> #include <nc/core/ir/types/Type.h> #include <nc/core/ir/types/Types.h> #include <nc/core/ir/vars/Variables.h> #include <nc/core/likec/BinaryOperator.h> #include <nc/core/likec/Block.h> #include <nc/core/likec/Break.h> #include <nc/core/likec/CallOperator.h> #include <nc/core/likec/CaseLabel.h> #include <nc/core/likec/Continue.h> #include <nc/core/likec/DefaultLabel.h> #include <nc/core/likec/DoWhile.h> #include <nc/core/likec/ExpressionStatement.h> #include <nc/core/likec/FunctionDefinition.h> #include <nc/core/likec/FunctionIdentifier.h> #include <nc/core/likec/Goto.h> #include <nc/core/likec/If.h> #include <nc/core/likec/InlineAssembly.h> #include <nc/core/likec/IntegerConstant.h> #include <nc/core/likec/LabelIdentifier.h> #include <nc/core/likec/LabelStatement.h> #include <nc/core/likec/Return.h> #include <nc/core/likec/String.h> #include <nc/core/likec/Switch.h> #include <nc/core/likec/Tree.h> #include <nc/core/likec/Typecast.h> #include <nc/core/likec/Types.h> #include <nc/core/likec/UnaryOperator.h> #include <nc/core/likec/UndeclaredIdentifier.h> #include <nc/core/likec/VariableIdentifier.h> #include <nc/core/likec/While.h> #include "SwitchContext.h" #include "Utils.h" namespace nc { namespace core { namespace ir { namespace cgen { DefinitionGenerator::DefinitionGenerator(CodeGenerator &parent, const Function *function, const CancellationToken &canceled): DeclarationGenerator(parent, calling::CalleeId(function), parent.signatures().getSignature(function).get()), function_(function), dataflow_(*parent.dataflows().at(function)), graph_(*parent.graphs().at(function)), liveness_(*parent.livenesses().at(function)), uses_(std::make_unique<dflow::Uses>(dataflow_)), cfg_(std::make_unique<CFG>(function->basicBlocks())), dominators_(std::make_unique<Dominators>(*cfg_, canceled)), hookStatements_(getHookStatements(function, dataflow_, parent.hooks())), definition_(nullptr) { assert(function != nullptr); } DefinitionGenerator::~DefinitionGenerator() {} void DefinitionGenerator::setDefinition(likec::FunctionDefinition *definition) { assert(!definition_); definition_ = definition; setDeclaration(definition); } std::unique_ptr<likec::FunctionDefinition> DefinitionGenerator::createDefinition() { auto nameAndComment = parent().nameGenerator().getFunctionName(function_); auto functionDefinition = std::make_unique<likec::FunctionDefinition>(tree(), std::move(nameAndComment.name()), makeReturnType(), signature()->variadic()); functionDefinition->setComment(std::move(nameAndComment.comment())); setDefinition(functionDefinition.get()); if (auto entryHook = parent().hooks().getEntryHook(function_)) { foreach (const auto &argument, signature()->arguments()) { auto term = entryHook->getArgumentTerm(argument.get()); assert(term != nullptr && "Entry hook must have clones of all arguments in the signature."); assert(dataflow_.getMemoryLocation(term) && "Argument must have a memory location."); auto variable = parent().variables().getVariable(term); assert(variable != nullptr && "Each term with a memory location must belong to a variable."); if (variable->memoryLocation() == dataflow_.getMemoryLocation(term)) { auto &variableDeclaration = variableDeclarations_[variable]; assert(!variableDeclaration); variableDeclaration = makeArgumentDeclaration(term); } else { auto variableDeclaration = makeArgumentDeclaration(term); definition()->block()->addStatement(std::make_unique<likec::ExpressionStatement>( std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::ASSIGN, makeVariableAccess(term), std::make_unique<likec::VariableIdentifier>(variableDeclaration)))); } } } SwitchContext switchContext; makeStatements(graph_.root(), definition()->block().get(), nullptr, nullptr, nullptr, switchContext); return functionDefinition; } likec::VariableDeclaration *DefinitionGenerator::makeLocalVariableDeclaration(const vars::Variable *variable) { assert(variable != nullptr); assert(variable->isLocal()); likec::VariableDeclaration *&result = variableDeclarations_[variable]; if (!result) { auto nameAndComment = parent().nameGenerator().getLocalVariableName(variable->memoryLocation(), variableDeclarations_.size()); auto variableDeclaration = std::make_unique<likec::VariableDeclaration>( std::move(nameAndComment.name()), parent().makeVariableType(variable)); variableDeclaration->setComment(std::move(nameAndComment.comment())); result = variableDeclaration.get(); definition()->block()->addDeclaration(std::move(variableDeclaration)); } return result; } likec::VariableDeclaration *DefinitionGenerator::makeVariableDeclaration(const vars::Variable *variable) { assert(variable != nullptr); if (variable->isGlobal()) { return parent().makeGlobalVariableDeclaration(variable); } else { return makeLocalVariableDeclaration(variable); } } likec::LabelDeclaration *DefinitionGenerator::makeLabel(const BasicBlock *basicBlock) { likec::LabelDeclaration *&result = labels_[basicBlock]; if (!result) { auto label = std::make_unique<likec::LabelDeclaration>( basicBlock->address() ? QString("addr_0x%1_%2").arg(basicBlock->address().get(), 0, 16).arg(labels_.size()) : QString("label_%1").arg(labels_.size()) ); result = label.get(); definition()->addLabel(std::move(label)); } return result; } void DefinitionGenerator::addLabels(const BasicBlock *basicBlock, likec::Block *block, SwitchContext &switchContext) { assert(basicBlock != nullptr); assert(block != nullptr); /* Add usual label. */ block->addStatement( std::make_unique<likec::LabelStatement>(std::make_unique<likec::LabelIdentifier>(makeLabel(basicBlock)))); /* Add case labels. */ if (basicBlock->address()) { if (basicBlock == switchContext.defaultBasicBlock()) { block->addStatement(std::make_unique<likec::DefaultLabel>()); } else { foreach (ConstantValue value, switchContext.getCaseValues(*basicBlock->address())) { block->addStatement(std::make_unique<likec::CaseLabel>( std::make_unique<likec::IntegerConstant>(value, switchContext.valueType()))); } } switchContext.eraseCaseValues(*basicBlock->address()); } } void DefinitionGenerator::makeStatements(const cflow::Node *node, likec::Block *block, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB, SwitchContext &switchContext) { switch (node->nodeKind()) { case cflow::Node::BASIC: { auto basicNode = node->as<cflow::BasicNode>(); addLabels(basicNode->basicBlock(), block, switchContext); foreach (const ir::Statement *statement, basicNode->basicBlock()->statements()) { if (auto likecStatement = makeStatement(statement, nextBB, breakBB, continueBB)) { block->addStatement(std::move(likecStatement)); } } break; } case cflow::Node::REGION: { auto region = node->as<cflow::Region>(); switch (region->regionKind()) { case cflow::Region::UNKNOWN: { assert(region->nodes().size() > 0); /* * We tend to process nodes in DFS order because it is likely * to minimize the number of generated gotos. */ makeStatements(cflow::Dfs(region).preordering(), block, nextBB, breakBB, continueBB, switchContext); break; } case cflow::Region::BLOCK: { assert(region->nodes().size() > 0); makeStatements(region->nodes(), block, nextBB, breakBB, continueBB, switchContext); break; } case cflow::Region::COMPOUND_CONDITION: { assert(region->nodes().size() == 2); makeStatements(region->nodes(), block, nextBB, breakBB, continueBB, switchContext); break; } case cflow::Region::IF_THEN_ELSE: { assert(region->nodes().size() == 3); std::unique_ptr<likec::Expression> condition(makeExpression(region->nodes()[0], block, region->nodes()[1]->getEntryBasicBlock(), region->nodes()[2]->getEntryBasicBlock(), switchContext)); auto thenBlock = std::make_unique<likec::Block>(); makeStatements(region->nodes()[1], thenBlock.get(), nextBB, breakBB, continueBB, switchContext); auto elseBlock = std::make_unique<likec::Block>(); makeStatements(region->nodes()[2], elseBlock.get(), nextBB, breakBB, continueBB, switchContext); block->addStatement(std::make_unique<likec::If>(std::move(condition), std::move(thenBlock), std::move(elseBlock))); break; } case cflow::Region::IF_THEN: { assert(region->nodes().size() == 2); assert(region->exitBasicBlock() != nullptr); std::unique_ptr<likec::Expression> condition(makeExpression(region->nodes()[0], block, region->nodes()[1]->getEntryBasicBlock(), region->exitBasicBlock(), switchContext)); auto thenBlock = std::make_unique<likec::Block>(); makeStatements(region->nodes()[1], thenBlock.get(), nextBB, breakBB, continueBB, switchContext); block->addStatement(std::make_unique<likec::If>(std::move(condition), std::move(thenBlock))); break; } case cflow::Region::LOOP: { assert(region->nodes().size() > 0); auto condition = std::make_unique<likec::IntegerConstant>(1, tree().makeIntegerType(tree().intSize(), false)); cflow::Dfs dfs(region); auto body = std::make_unique<likec::Block>(); const BasicBlock *entryBB = region->entry()->getEntryBasicBlock(); makeStatements(dfs.preordering(), body.get(), entryBB, nextBB, entryBB, switchContext); block->addStatement(std::make_unique<likec::While>(std::move(condition), std::move(body))); break; } case cflow::Region::WHILE: { assert(region->nodes().size() > 0); assert(region->exitBasicBlock() != nullptr); addLabels(region->entry()->getEntryBasicBlock(), block, switchContext); auto condition = makeExpression(region->entry(), nullptr, region->entry()->uniqueSuccessor()->getEntryBasicBlock(), region->exitBasicBlock(), switchContext); cflow::Dfs dfs(region); auto &nodes = dfs.preordering(); assert(nodes.front() == region->entry()); nodes.erase(nodes.begin()); auto body = std::make_unique<likec::Block>(); const BasicBlock *conditionBB = region->entry()->getEntryBasicBlock(); makeStatements(nodes, body.get(), conditionBB, region->exitBasicBlock(), conditionBB, switchContext); block->addStatement(std::make_unique<likec::While>(std::move(condition), std::move(body))); if (auto jump = makeJump(region->exitBasicBlock(), nextBB, breakBB, continueBB)) { block->addStatement(std::move(jump)); } break; } case cflow::Region::DO_WHILE: { assert(region->nodes().size() > 0); assert(region->exitBasicBlock() != nullptr); assert(region->loopCondition() != nullptr); cflow::Dfs dfs(region); auto &nodes = dfs.preordering(); assert(nc::contains(nodes, region->loopCondition())); nodes.erase(std::find(nodes.begin(), nodes.end(), region->loopCondition())); auto body = std::make_unique<likec::Block>(); const BasicBlock *conditionBB = region->loopCondition()->getEntryBasicBlock(); makeStatements(nodes, body.get(), conditionBB, nextBB, conditionBB, switchContext); auto condition = makeExpression(region->loopCondition(), body.get(), region->entry()->getEntryBasicBlock(), region->exitBasicBlock(), switchContext); block->addStatement(std::make_unique<likec::DoWhile>(std::move(body), std::move(condition))); if (auto jump = makeJump(region->exitBasicBlock(), nextBB, breakBB, continueBB)) { block->addStatement(std::move(jump)); } break; } case cflow::Region::SWITCH: { auto witch = region->as<cflow::Switch>(); /* * Generates code for the basic block, except the code for its terminator. */ auto makeStatementsButLast = [&](const BasicBlock *basicBlock) { addLabels(basicBlock, block, switchContext); auto iend = --basicBlock->statements().end(); for (auto i = basicBlock->statements().begin(); i != iend; ++i) { /* We do not care about breakBB and others: we will not create gotos. */ if (auto likecStatement = makeStatement(*i, nullptr, nullptr, nullptr)) { block->addStatement(std::move(likecStatement)); } } }; /* Generate code for the basic block doing the bounds check. */ if (witch->boundsCheckNode()) { makeStatementsButLast(witch->boundsCheckNode()->basicBlock()); } /* Generate code for the basic block with the table-based jump. */ makeStatementsButLast(witch->switchNode()->basicBlock()); /* The jump via the jump table. */ const Jump *jump = witch->switchNode()->basicBlock()->getJump(); assert(jump != nullptr); assert(jump->isUnconditional()); /* The jump table. */ const JumpTable *jumpTable = jump->thenTarget().table(); assert(jumpTable != nullptr); /* * Make a new switch context. */ SwitchContext newSwitchContext; newSwitchContext.setValueType(tree().makeIntegerType(witch->switchTerm()->size(), true)); for (std::size_t i = 0, size = witch->jumpTableSize(); i < size; ++i) { newSwitchContext.addCaseValue((*jumpTable)[i].address(), i); } if (witch->defaultBasicBlock()) { newSwitchContext.setDefaultBasicBlock(witch->defaultBasicBlock()); } /* Exit basic block of the switch. */ const BasicBlock *exitBB = witch->exitBasicBlock(); if (!exitBB) { exitBB = nextBB; } /* * Generate the switch expression. */ auto expression = std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, newSwitchContext.valueType(), makeExpression(witch->switchTerm())); /* * Generate the body of the switch. */ cflow::Dfs dfs(region); auto &nodes = dfs.preordering(); nodes.erase( std::remove_if(nodes.begin(), nodes.end(), [witch](const cflow::Node *node){ return node == witch->boundsCheckNode() || node == witch->switchNode(); }), nodes.end()); auto body = std::make_unique<likec::Block>(); makeStatements(nodes, body.get(), exitBB, exitBB, continueBB, newSwitchContext); /* * Generate case labels that were not generated before. */ foreach (const auto &pair, newSwitchContext.caseValuesMap()) { foreach (ConstantValue value, pair.second) { body->addStatement(std::make_unique<likec::CaseLabel>( std::make_unique<likec::IntegerConstant>(value, newSwitchContext.valueType()))); } body->addStatement(std::make_unique<likec::Goto>( std::make_unique<likec::IntegerConstant>( pair.first, tree().makeIntegerType(tree().pointerSize(), true)))); } /* Generate the switch. */ block->addStatement(std::make_unique<likec::Switch>(std::move(expression), std::move(body))); /* Generate a jump to the exit basic block, if it's not the nextBB. */ if (auto jump = makeJump(exitBB, nextBB, breakBB, continueBB)) { block->addStatement(std::move(jump)); } break; } default: unreachable(); } break; } default: unreachable(); } } void DefinitionGenerator::makeStatements(const std::vector<cflow::Node *> &nodes, likec::Block *block, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB, SwitchContext &switchContext) { if (nodes.empty()) { return; } for (std::size_t i = 0, last = nodes.size() - 1; i != last; ++i) { makeStatements(nodes[i], block, nodes[i + 1]->getEntryBasicBlock(), breakBB, continueBB, switchContext); } makeStatements(nodes.back(), block, nextBB, breakBB, continueBB, switchContext); } std::unique_ptr<likec::Expression> DefinitionGenerator::makeExpression(const cflow::Node *node, likec::Block *block, const BasicBlock *thenBB, const BasicBlock *elseBB, SwitchContext &switchContext) { assert(node != nullptr); assert(thenBB != nullptr); assert(elseBB != nullptr); assert(node->isCondition() && "Can only generate expressions from condition nodes."); std::unique_ptr<likec::Expression> result; if (const cflow::BasicNode *basicNode = node->as<cflow::BasicNode>()) { if (block) { addLabels(basicNode->basicBlock(), block, switchContext); } foreach (const ir::Statement *statement, basicNode->basicBlock()->statements()) { std::unique_ptr<likec::Expression> expression; if (const Jump *jump = statement->asJump()) { assert(jump == basicNode->basicBlock()->getJump()); expression = makeExpression(jump->condition()); assert((jump->thenTarget().basicBlock() == thenBB && jump->elseTarget().basicBlock() == elseBB) || (jump->thenTarget().basicBlock() == elseBB && jump->elseTarget().basicBlock() == thenBB)); if (jump->thenTarget().basicBlock() != thenBB) { expression = std::make_unique<likec::UnaryOperator>(likec::UnaryOperator::LOGICAL_NOT, std::move(expression)); } } else if (auto stmt = makeStatement(statement, nullptr, nullptr, nullptr)) { if (block) { block->addStatement(std::move(stmt)); } else if (likec::ExpressionStatement *expressionStatement = stmt->as<likec::ExpressionStatement>()) { expression = expressionStatement->releaseExpression(); } } if (expression) { if (!result) { result = std::move(expression); } else { result = std::make_unique<likec::BinaryOperator>(likec::BinaryOperator::COMMA, std::move(result), std::move(expression)); } } } } else if (const cflow::Region *region = node->as<cflow::Region>()) { assert(region->regionKind() == cflow::Region::COMPOUND_CONDITION); assert(region->nodes().size() == 2); /* * Distinguishing AND from OR: * * if (a || b) { then } { else } * * a -> then || b * b -> then || else * * if (a && b) { then } { else } * * a -> b || else * b -> then || else */ const cflow::Node *n = region->nodes()[0]; while (const cflow::Region *r = n->as<cflow::Region>()) { assert(r->regionKind() == cflow::Region::COMPOUND_CONDITION); assert(r->nodes().size() == 2); n = r->nodes()[1]; } const cflow::BasicNode *b = n->as<cflow::BasicNode>(); assert(b != nullptr); const Jump *j = b->basicBlock()->getJump(); assert(j != nullptr); if (j->thenTarget().basicBlock() == thenBB || j->elseTarget().basicBlock() == thenBB) { auto left = makeExpression(region->nodes()[0], block, thenBB, region->nodes()[1]->getEntryBasicBlock(), switchContext); auto right = makeExpression(region->nodes()[1], nullptr, thenBB, elseBB, switchContext); result = std::make_unique<likec::BinaryOperator>(likec::BinaryOperator::LOGICAL_OR, std::move(left), std::move(right)); } else if (j->thenTarget().basicBlock() == elseBB || j->elseTarget().basicBlock() == elseBB) { auto left = makeExpression(region->nodes()[0], block, region->nodes()[1]->getEntryBasicBlock(), elseBB, switchContext); auto right = makeExpression(region->nodes()[1], nullptr, thenBB, elseBB, switchContext); result = std::make_unique<likec::BinaryOperator>(likec::BinaryOperator::LOGICAL_AND, std::move(left), std::move(right)); } else { assert(!"First component of compound condition must contain a jump to thenBB or elseBB."); } } else { assert(!"Node must be a basic block node or a region."); } assert(result != nullptr && "Something is very wrong."); return result; } std::unique_ptr<likec::Statement> DefinitionGenerator::makeStatement(const Statement *statement, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB) { assert(statement); if (nc::contains(hookStatements_, statement)) { return nullptr; } auto result = doMakeStatement(statement, nextBB, breakBB, continueBB); if (result != nullptr) { class StatementSetter { const ir::Statement *statement_; public: StatementSetter(const ir::Statement *statement): statement_(statement) { assert(statement != nullptr); } void operator()(likec::TreeNode *node) { if (auto stmt = node->as<likec::Statement>()) { if (stmt->statement() == nullptr) { stmt->setStatement(statement_); stmt->callOnChildren(*this); } } } }; StatementSetter setter(statement); setter(result.get()); } return result; } std::unique_ptr<likec::Statement> DefinitionGenerator::doMakeStatement(const Statement *statement, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB) { switch (statement->kind()) { case Statement::INLINE_ASSEMBLY: { return std::make_unique<likec::InlineAssembly>( statement->instruction() ? statement->instruction()->toString() : QString()); } case Statement::ASSIGNMENT: { const Assignment *assignment = statement->asAssignment(); if (!liveness_.isLive(assignment->left())) { return nullptr; } if (isSubstituted(assignment->left())) { return nullptr; } std::unique_ptr<likec::Expression> left(makeExpression(assignment->left())); std::unique_ptr<likec::Expression> right(makeExpression(assignment->right())); return std::make_unique<likec::ExpressionStatement>( std::make_unique<likec::BinaryOperator>(likec::BinaryOperator::ASSIGN, std::move(left), std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, parent().makeType(parent().types().getType(assignment->left())), std::move(right)))); } case Statement::JUMP: { const Jump *jump = statement->asJump(); if (jump->isConditional()) { auto thenJump = makeJump(jump, jump->thenTarget(), nextBB, breakBB, continueBB); auto elseJump = makeJump(jump, jump->elseTarget(), nextBB, breakBB, continueBB); auto condition = makeExpression(jump->condition()); if (thenJump == nullptr) { if (elseJump == nullptr) { return nullptr; } else { std::swap(thenJump, elseJump); condition = std::make_unique<likec::UnaryOperator>(likec::UnaryOperator::LOGICAL_NOT, std::move(condition)); } } return std::make_unique<likec::If>(std::move(condition), std::move(thenJump), std::move(elseJump)); } else { return makeJump(jump, jump->thenTarget(), nextBB, breakBB, continueBB); } } case Statement::CALL: { const Call *call = statement->asCall(); std::unique_ptr<likec::Expression> target; auto targetValue = dataflow_.getValue(call->target()); if (targetValue->abstractValue().isConcrete()) { if (auto functionDeclaration = parent().makeFunctionDeclaration(targetValue->abstractValue().asConcrete().value())) { target = std::make_unique<likec::FunctionIdentifier>(functionDeclaration); target->setTerm(call->target()); } } if (!target) { target = makeExpression(call->target()); } auto callOperator = std::make_unique<likec::CallOperator>(std::move(target)); if (auto callSignature = parent().signatures().getSignature(call)) { if (auto callHook = parent().hooks().getCallHook(call)) { foreach (const auto &argument, callSignature->arguments()) { callOperator->addArgument(makeExpression(callHook->getArgumentTerm(argument.get()))); } if (callSignature->returnValue()) { const Term *returnValueTerm = callHook->getReturnValueTerm(callSignature->returnValue().get()); if (liveness_.isLive(returnValueTerm)) { return std::make_unique<likec::ExpressionStatement>( std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::ASSIGN, makeExpression(returnValueTerm), std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, parent().makeType(parent().types().getType(returnValueTerm)), std::move(callOperator)))); } } } } return std::make_unique<likec::ExpressionStatement>(std::move(callOperator)); } case Statement::HALT: { return nullptr; } case Statement::TOUCH: { return nullptr; } case Statement::CALLBACK: { return nullptr; } } unreachable(); return nullptr; } std::unique_ptr<likec::Statement> DefinitionGenerator::makeJump(const BasicBlock *target, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB) { if (target == nextBB) { return nullptr; } else if (target == breakBB) { return std::make_unique<likec::Break>(); } else if (target == continueBB) { return std::make_unique<likec::Continue>(); } else { return std::make_unique<likec::Goto>( std::make_unique<likec::LabelIdentifier>(makeLabel(target))); } } std::unique_ptr<likec::Statement> DefinitionGenerator::makeJump(const Jump *jump, const JumpTarget &target, const BasicBlock *nextBB, const BasicBlock *breakBB, const BasicBlock *continueBB) { assert(jump != nullptr); if (target.basicBlock()) { return makeJump(target.basicBlock(), nextBB, breakBB, continueBB); } else if (target.address()) { if (dflow::isReturnAddress(target.address(), dataflow_)) { if (signature()->returnValue()) { if (auto returnHook = parent().hooks().getReturnHook(jump)) { return std::make_unique<likec::Return>( makeExpression(returnHook->getReturnValueTerm(signature()->returnValue().get()))); } } return std::make_unique<likec::Return>(); } return std::make_unique<likec::Goto>(makeExpression(target.address())); } else { return std::make_unique<likec::Goto>(std::make_unique<likec::String>(QLatin1String("???"))); } } std::unique_ptr<likec::Expression> DefinitionGenerator::makeExpression(const Term *term) { assert(term != nullptr); auto result = doMakeExpression(term); assert(result != nullptr); class TermSetter { const ir::Term *term_; public: TermSetter(const ir::Term *term): term_(term) { assert(term != nullptr); } void operator()(likec::TreeNode *node) { if (auto expression = node->as<likec::Expression>()) { if (expression->term() == nullptr) { expression->setTerm(term_); expression->callOnChildren(*this); } } } }; TermSetter setter(term); setter(result.get()); return result; } std::unique_ptr<likec::Expression> DefinitionGenerator::doMakeExpression(const Term *term) { #ifdef NC_PREFER_CONSTANTS_TO_EXPRESSIONS if (term->isRead()) { const dflow::Value *value = dataflow_.getValue(term); if (value->abstractValue().isConcrete()) { return makeConstant(term, value->abstractValue().asConcrete()); } } #endif if (term->isRead()) { if (const Term *substitute = getSubstitute(term)) { return makeExpression(substitute); } } if (parent().variables().getVariable(term)) { return makeVariableAccess(term); } switch (term->kind()) { case Term::INT_CONST: { return makeConstant(term, term->asConstant()->value()); } case Term::INTRINSIC: { return doMakeExpression(term->as<Intrinsic>()); } case Term::MEMORY_LOCATION_ACCESS: { assert(!"The term must belong to a variable."); return nullptr; } case Term::DEREFERENCE: { assert(!dataflow_.getMemoryLocation(term) && "The term must belong to a variable."); auto dereference = term->asDereference(); auto type = parent().types().getType(dereference); auto addressType = parent().types().getType(dereference->address()); return std::make_unique<likec::UnaryOperator>(likec::UnaryOperator::DEREFERENCE, std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makePointerType(addressType->size(), parent().makeType(type)), makeExpression(dereference->address()))); } case Term::UNARY_OPERATOR: { return doMakeExpression(term->asUnaryOperator()); } case Term::BINARY_OPERATOR: { return doMakeExpression(term->asBinaryOperator()); } default: { unreachable(); return nullptr; } } } std::unique_ptr<likec::Expression> DefinitionGenerator::doMakeExpression(const UnaryOperator *unary) { std::unique_ptr<likec::Expression> operand(makeExpression(unary->operand())); switch (unary->operatorKind()) { case UnaryOperator::NOT: { const types::Type *operandType = parent().types().getType(unary->operand()); return std::make_unique<likec::UnaryOperator>( likec::UnaryOperator::BITWISE_NOT, std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(operandType->size(), operandType->isUnsigned()), std::move(operand))); } case UnaryOperator::NEGATION: { const types::Type *operandType = parent().types().getType(unary->operand()); return std::make_unique<likec::UnaryOperator>( likec::UnaryOperator::NEGATION, std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(operandType->size(), operandType->isUnsigned()), std::move(operand))); } case UnaryOperator::SIGN_EXTEND: { return std::make_unique<likec::Typecast>( likec::Typecast::STATIC_CAST, tree().makeIntegerType(unary->size(), false), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(unary->operand()->size(), false), std::move(operand))); } case UnaryOperator::ZERO_EXTEND: { return std::make_unique<likec::Typecast>( likec::Typecast::STATIC_CAST, tree().makeIntegerType(unary->size(), true), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(unary->operand()->size(), true), std::move(operand))); } case UnaryOperator::TRUNCATE: { const types::Type *type = parent().types().getType(unary); const types::Type *operandType = parent().types().getType(unary->operand()); return std::make_unique<likec::Typecast>( likec::Typecast::STATIC_CAST, tree().makeIntegerType(unary->size(), type->isUnsigned()), std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(unary->operand()->size(), operandType->isUnsigned()), std::move(operand))); } default: unreachable(); } } std::unique_ptr<likec::Expression> DefinitionGenerator::doMakeExpression(const BinaryOperator *binary) { const types::Type *leftType = parent().types().getType(binary->left()); const types::Type *rightType = parent().types().getType(binary->right()); std::unique_ptr<likec::Expression> left(makeExpression(binary->left())); std::unique_ptr<likec::Expression> right(makeExpression(binary->right())); switch (binary->operatorKind()) { case BinaryOperator::AND: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::BITWISE_AND, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::OR: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::BITWISE_OR, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::XOR: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::BITWISE_XOR, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::SHL: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::SHL, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::SHR: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::SHR, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), true), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::SAR: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::SHR, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), false), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::ADD: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::ADD, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::SUB: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::SUB, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::MUL: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::MUL, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), leftType->isUnsigned()), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), rightType->isUnsigned()), std::move(right))); case BinaryOperator::SIGNED_DIV: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::DIV, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), false), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), false), std::move(right))); case BinaryOperator::SIGNED_REM: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::REM, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), false), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), false), std::move(right))); case BinaryOperator::UNSIGNED_DIV: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::DIV, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), true), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), true), std::move(right))); case BinaryOperator::UNSIGNED_REM: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::REM, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), true), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), true), std::move(right))); case BinaryOperator::EQUAL: return std::make_unique<likec::BinaryOperator>(likec::BinaryOperator::EQ, std::move(left), std::move(right)); case BinaryOperator::SIGNED_LESS: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::LT, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), false), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), false), std::move(right))); case BinaryOperator::SIGNED_LESS_OR_EQUAL: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::LEQ, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), false), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), false), std::move(right))); case BinaryOperator::UNSIGNED_LESS: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::LT, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), true), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), true), std::move(right))); case BinaryOperator::UNSIGNED_LESS_OR_EQUAL: return std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::LEQ, std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(leftType->size(), true), std::move(left)), std::make_unique<likec::Typecast>(likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(rightType->size(), true), std::move(right))); default: unreachable(); return nullptr; } } std::unique_ptr<likec::Expression> DefinitionGenerator::doMakeExpression(const Intrinsic *intrinsic) { switch (intrinsic->intrinsicKind()) { case Intrinsic::UNDEFINED: return makeIntrinsicCall( QLatin1String("__undefined"), parent().makeType(parent().types().getType(intrinsic))); case Intrinsic::ZERO_STACK_OFFSET: return makeIntrinsicCall( QLatin1String("__zero_stack_offset"), parent().tree().makePointerType(parent().tree().pointerSize(), parent().tree().makeVoidType())); case Intrinsic::RETURN_ADDRESS: return makeIntrinsicCall( QLatin1String("__return_address"), parent().tree().makePointerType(parent().tree().pointerSize(), parent().tree().makeVoidType())); } return makeIntrinsicCall(QLatin1String("__intrinsic"), parent().makeType(parent().types().getType(intrinsic))); } std::unique_ptr<likec::Expression> DefinitionGenerator::makeIntrinsicCall(QLatin1String name, const likec::Type *returnType) { return std::make_unique<likec::CallOperator>(std::make_unique<likec::UndeclaredIdentifier>( name, std::make_unique<likec::FunctionPointerType>(parent().tree().pointerSize(), returnType))); } std::unique_ptr<likec::Expression> DefinitionGenerator::makeConstant(const Term *term, const SizedValue &value) { const types::Type *type = parent().types().getType(term); #ifdef NC_PREFER_FUNCTIONS_TO_CONSTANTS if (auto section = parent().image().getSectionContainingAddress(value.value())) { if (section->isCode()) { if (auto functionDeclaration = parent().makeFunctionDeclaration(value.value())) { return std::make_unique<likec::FunctionIdentifier>(functionDeclaration); } } } #endif #ifdef NC_PREFER_CSTRINGS_TO_CONSTANTS if (!type->pointee() || type->pointee()->size() <= 1) { auto isAscii = [](const QString &string) -> bool { foreach (QChar c, string) { if (c >= 0x80 || (c < 0x20 && c != '\r' && c != '\n' && c != '\t')) { return false; } } return true; }; QString string = image::Reader(&parent().image()).readAsciizString(value.value(), 1024); if (!string.isEmpty() && isAscii(string)) { return std::make_unique<likec::String>(string); } } #endif #ifdef NC_PREFER_GLOBAL_VARIABLES_TO_CONSTANTS if (type->pointee() && type->pointee()->size()) { return std::make_unique<likec::UnaryOperator>( likec::UnaryOperator::REFERENCE, std::make_unique<likec::VariableIdentifier>( parent().makeGlobalVariableDeclaration( MemoryLocation(MemoryDomain::MEMORY, value.value() * CHAR_BIT, type->pointee()->size()), type))); } #endif return std::make_unique<likec::IntegerConstant>(value, tree().makeIntegerType(value.size(), type->isUnsigned())); } std::unique_ptr<likec::Expression> DefinitionGenerator::makeVariableAccess(const Term *term) { assert(term != nullptr); const auto &termLocation = dataflow_.getMemoryLocation(term); assert(termLocation); auto variable = parent().variables().getVariable(term); assert(variable != nullptr); auto identifier = std::make_unique<likec::VariableIdentifier>(makeVariableDeclaration(variable)); if (termLocation == variable->memoryLocation()) { return std::move(identifier); } else { /* * Generate pointer arithmetics to get to the right part of the variable. * * Note: this does not handle the case of non-byte-aligned locations. * However, I am not sure whether they can be reliably handled in C at all. */ auto variableAddress = std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makeIntegerType(tree().pointerSize(), false), std::make_unique<likec::UnaryOperator>( likec::UnaryOperator::REFERENCE, std::move(identifier))); std::unique_ptr<likec::Expression> termAddress; if (termLocation.addr() == variable->memoryLocation().addr()) { termAddress = std::move(variableAddress); } else { termAddress = std::make_unique<likec::BinaryOperator>( likec::BinaryOperator::ADD, std::move(variableAddress), std::make_unique<likec::IntegerConstant>( (termLocation.addr() - variable->memoryLocation().addr()) / CHAR_BIT, tree().makeIntegerType(tree().pointerSize(), false))); } return std::make_unique<likec::UnaryOperator>( likec::UnaryOperator::DEREFERENCE, std::make_unique<likec::Typecast>( likec::Typecast::REINTERPRET_CAST, tree().makePointerType(parent().makeType(parent().types().getType(term))), std::move(termAddress))); } } const Term *DefinitionGenerator::getSubstitute(const Term *read) { assert(read != nullptr); assert(read->isRead()); assert(liveness_.isLive(read)); if (auto write = getTheOnlyDefinition(read, dataflow_)) { if (isSubstituted(write)) { return write->source(); } } return nullptr; } bool DefinitionGenerator::isSubstituted(const Term *write) { assert(write != nullptr); assert(write->isWrite()); assert(liveness_.isLive(write)); auto i = isSubstituted_.find(write); if (i != isSubstituted_.end()) { /* The result is being computed? */ if (i->second == boost::none) { /* Cyclic dependency. */ i->second = false; } return *i->second; } /* Mark the result as being computed. */ isSubstituted_.emplace_hint(i, std::make_pair(write, boost::none)); auto result = computeIsSubstituted(write); auto &cached = isSubstituted_[write]; if (!cached) { cached = result; } return result; } bool DefinitionGenerator::computeIsSubstituted(const Term *write) { auto source = write->source(); if (!source) { return false; } if (nc::contains(hookStatements_, write->statement())) { return false; } const auto &memoryLocation = dataflow_.getMemoryLocation(write); if (!memoryLocation) { return false; } if (!parent().variables().getVariable(write)->isLocal()) { return false; } std::size_t nuses = 0; foreach (const auto &use, uses_->getUses(write)) { auto read = use.term(); if (liveness_.isLive(read)) { if (dataflow_.getMemoryLocation(read) != memoryLocation) { return false; } auto theOnlyDefinition = getTheOnlyDefinition(read, dataflow_); if (!theOnlyDefinition) { return false; } assert(theOnlyDefinition == write); if (!isDominating(write->statement(), read->statement(), *dominators_)) { return false; } if (!canBeMoved(source, read->statement())) { return false; } ++nuses; } } assert(nuses >= 1 && "Live write must have at least one live read."); if (nuses > 1 && (source->kind() == Term::UNARY_OPERATOR || source->kind() == Term::BINARY_OPERATOR)) { /* We do not want to substitute complex expressions multiple times. */ return false; } return true; } bool DefinitionGenerator::canBeMoved(const Term *term, const Statement *destination) { assert(term != nullptr); assert(term->isRead()); assert(destination != nullptr); assert(liveness_.isLive(term)); #ifdef NC_PREFER_CONSTANTS_TO_EXPRESSIONS if (dataflow_.getValue(term)->abstractValue().isConcrete()) { return true; } #endif if (auto substitute = getSubstitute(term)) { return canBeMoved(substitute, destination); } switch (term->kind()) { case Term::INT_CONST: case Term::INTRINSIC: { return true; } case Term::MEMORY_LOCATION_ACCESS: case Term::DEREFERENCE: { if (auto variable = parent().variables().getVariable(term)) { /* * This assumes that our dataflow analysis has successfully * detected all accesses to the local variable, which obviously * cannot always be the case. */ return variable->isLocal() && allOfStatementsBetween( term->statement(), destination, *cfg_, [&](const Statement *statement) -> bool { auto term = getWrittenTerm(statement); return !term || parent().variables().getVariable(term) != variable; }) == true; } Domain domain = *getDomain(term); return allOfStatementsBetween( term->statement(), destination, *cfg_, [&](const Statement *statement) -> bool { auto term = getWrittenTerm(statement); return !term || getDomain(term) != domain; }) == true; } case Term::UNARY_OPERATOR: { auto unary = term->asUnaryOperator(); return canBeMoved(unary->operand(), destination); } case Term::BINARY_OPERATOR: { auto binary = term->asBinaryOperator(); return canBeMoved(binary->left(), destination) && canBeMoved(binary->right(), destination); } } unreachable(); } } // namespace cgen } // namespace ir } // namespace core } // namespace nc /* vim:set et sts=4 sw=4: */
43.143067
217
0.572988
[ "vector" ]
ebd9e2b172955d04b8f93c8ac81e324a91eac6aa
7,789
cpp
C++
vsearch/metadata_set.cpp
xjdr/VectorSearch
ab2c14c8f49d840a69ee1c93ec2c334704f59153
[ "MIT" ]
null
null
null
vsearch/metadata_set.cpp
xjdr/VectorSearch
ab2c14c8f49d840a69ee1c93ec2c334704f59153
[ "MIT" ]
null
null
null
vsearch/metadata_set.cpp
xjdr/VectorSearch
ab2c14c8f49d840a69ee1c93ec2c334704f59153
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "metadata_set.h" #include <fstream> #include <iostream> using namespace vsearch; ErrorCode MetadataSet::RefineMetadata(std::vector<int>& indices, const std::string& p_folderPath) { std::ofstream metaOut(p_folderPath + "metadata.bin_tmp", std::ios::binary); std::ofstream metaIndexOut(p_folderPath + "metadataIndex.bin", std::ios::binary); if (!metaOut.is_open() || !metaIndexOut.is_open()) return ErrorCode::FailedCreateFile; int R = (int)indices.size(); metaIndexOut.write((char*)&R, sizeof(int)); std::uint64_t offset = 0; for (int i = 0; i < R; i++) { metaIndexOut.write((char*)&offset, sizeof(std::uint64_t)); ByteArray meta = GetMetadata(indices[i]); metaOut.write((char*)meta.Data(), sizeof(uint8_t) * meta.Length()); offset += meta.Length(); } metaOut.close(); metaIndexOut.write((char*)&offset, sizeof(std::uint64_t)); metaIndexOut.close(); vsearch::MetadataSet::MetaCopy(p_folderPath + "metadata.bin_tmp", p_folderPath + "metadata.bin"); return ErrorCode::Success; } ErrorCode MetadataSet::MetaCopy(const std::string& p_src, const std::string& p_dst) { if (p_src == p_dst) return ErrorCode::Success; std::ifstream src(p_src, std::ios::binary); if (!src.is_open()) { std::cerr << "ERROR: Can't open " << p_src << std::endl; return ErrorCode::FailedOpenFile; } std::ofstream dst(p_dst, std::ios::binary); if (!dst.is_open()) { std::cerr << "ERROR: Can't create " << p_dst << std::endl; src.close(); return ErrorCode::FailedCreateFile; } int bufsize = 1000000; char* buf = new char[bufsize]; while (!src.eof()) { src.read(buf, bufsize); dst.write(buf, src.gcount()); } delete[] buf; src.close(); dst.close(); return ErrorCode::Success; } MetadataSet::MetadataSet() {} MetadataSet::~MetadataSet() {} FileMetadataSet::FileMetadataSet(const std::string& p_metafile, const std::string& p_metaindexfile) : m_metaFile(p_metafile), m_metaindexFile(p_metaindexfile) { m_fp = new std::ifstream(p_metafile, std::ifstream::binary); std::ifstream fpidx(p_metaindexfile, std::ifstream::binary); if (!m_fp->is_open() || !fpidx.is_open()) { std::cerr << "ERROR: Cannot open meta files " << p_metafile << " and " << p_metaindexfile << "!" << std::endl; return; } fpidx.read((char*)&m_count, sizeof(m_count)); m_pOffsets.resize(m_count + 1); fpidx.read((char*)m_pOffsets.data(), sizeof(std::uint64_t) * (m_count + 1)); fpidx.close(); } FileMetadataSet::~FileMetadataSet() { if (m_fp) { m_fp->close(); delete m_fp; } } ByteArray FileMetadataSet::GetMetadata(IndexType p_vectorID) const { std::uint64_t startoff = m_pOffsets[p_vectorID]; std::uint64_t bytes = m_pOffsets[p_vectorID + 1] - startoff; if (p_vectorID < (IndexType)m_count) { m_fp->seekg(startoff, std::ios_base::beg); ByteArray b = ByteArray::Alloc((SizeType)bytes); m_fp->read((char*)b.Data(), bytes); return b; } else { startoff -= m_pOffsets[m_count]; return ByteArray((std::uint8_t*)m_newdata.data() + startoff, static_cast<SizeType>(bytes), false); } } SizeType FileMetadataSet::Count() const { return static_cast<SizeType>(m_pOffsets.size() - 1); } bool FileMetadataSet::Available() const { return m_fp && m_fp->is_open() && m_pOffsets.size() > 1; } void FileMetadataSet::AddBatch(MetadataSet& data) { for (int i = 0; i < static_cast<int>(data.Count()); i++) { ByteArray newdata = data.GetMetadata(i); m_newdata.insert(m_newdata.end(), newdata.Data(), newdata.Data() + newdata.Length()); m_pOffsets.push_back(m_pOffsets[m_pOffsets.size() - 1] + newdata.Length()); } } ErrorCode FileMetadataSet::SaveMetadata(const std::string& p_metaFile, const std::string& p_metaindexFile) { ErrorCode ret = ErrorCode::Success; m_fp->close(); ret = MetaCopy(m_metaFile, p_metaFile); if (ErrorCode::Success != ret) { return ret; } if (m_newdata.size() > 0) { std::ofstream tmpout(p_metaFile, std::ofstream::app | std::ios::binary); if (!tmpout.is_open()) return ErrorCode::FailedOpenFile; tmpout.write((char*)m_newdata.data(), m_newdata.size()); tmpout.close(); } m_fp->open(p_metaFile, std::ifstream::binary); std::ofstream dst(p_metaindexFile, std::ios::binary); m_count = static_cast<int>(m_pOffsets.size()) - 1; m_newdata.clear(); dst.write((char*)&m_count, sizeof(m_count)); dst.write((char*)m_pOffsets.data(), sizeof(std::uint64_t) * m_pOffsets.size()); return ret; } MemMetadataSet::MemMetadataSet(ByteArray p_metadata, ByteArray p_offsets, SizeType p_count) : m_metadataHolder(std::move(p_metadata)), m_offsetHolder(std::move(p_offsets)), m_count(p_count) { const std::uint64_t* newdata = reinterpret_cast<const std::uint64_t*>(m_offsetHolder.Data()); m_offsets.insert(m_offsets.end(), newdata, newdata + p_count + 1); } MemMetadataSet::~MemMetadataSet() {} ByteArray MemMetadataSet::GetMetadata(IndexType p_vectorID) const { if (static_cast<SizeType>(p_vectorID) < m_count) { return ByteArray(m_metadataHolder.Data() + m_offsets[p_vectorID], static_cast<SizeType>(m_offsets[p_vectorID + 1] - m_offsets[p_vectorID]), m_metadataHolder.DataHolder()); } else if (p_vectorID < m_offsets.size() - 1) { return ByteArray((std::uint8_t*)m_newdata.data() + m_offsets[p_vectorID] - m_offsets[m_count], static_cast<SizeType>(m_offsets[p_vectorID + 1] - m_offsets[p_vectorID]), false); } return ByteArray::c_empty; } SizeType MemMetadataSet::Count() const { return m_count; } bool MemMetadataSet::Available() const { return m_metadataHolder.Length() > 0 && m_offsetHolder.Length() > 0; } void MemMetadataSet::AddBatch(MetadataSet& data) { for (int i = 0; i < static_cast<int>(data.Count()); i++) { ByteArray newdata = data.GetMetadata(i); m_newdata.insert(m_newdata.end(), newdata.Data(), newdata.Data() + newdata.Length()); m_offsets.push_back(m_offsets[m_offsets.size() - 1] + newdata.Length()); } } ErrorCode MemMetadataSet::SaveMetadata(const std::string& p_metaFile, const std::string& p_metaindexFile) { std::ofstream outputStream; outputStream.open(p_metaFile, std::ios::binary); if (!outputStream.is_open()) { std::cerr << "Error: Failed to create file " << p_metaFile << "." << std::endl; return ErrorCode::FailedCreateFile; } outputStream.write(reinterpret_cast<const char*>(m_metadataHolder.Data()), m_metadataHolder.Length()); outputStream.write((const char*)m_newdata.data(), sizeof(std::uint8_t) * m_newdata.size()); outputStream.close(); outputStream.open(p_metaindexFile, std::ios::binary); if (!outputStream.is_open()) { std::cerr << "Error: Failed to create file " << p_metaindexFile << "." << std::endl; return ErrorCode::FailedCreateFile; } m_count = static_cast<int>(m_offsets.size()) - 1; outputStream.write(reinterpret_cast<const char*>(&m_count), sizeof(m_count)); outputStream.write(reinterpret_cast<const char*>(m_offsets.data()), sizeof(std::uint64_t) * m_offsets.size()); outputStream.close(); return ErrorCode::Success; }
34.464602
79
0.637951
[ "vector" ]
ebda786b578740f421ec99e2c3a1ab0449b3274d
5,914
hh
C++
src/sim/voltage_domain.hh
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
2
2021-01-15T17:32:18.000Z
2021-12-21T02:53:58.000Z
src/sim/voltage_domain.hh
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
3
2021-03-26T20:33:59.000Z
2022-01-24T22:54:03.000Z
src/sim/voltage_domain.hh
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
3
2021-03-27T16:36:19.000Z
2022-03-28T18:32:57.000Z
/* * Copyright (c) 2012, 2019 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __SIM_VOLTAGE_DOMAIN_HH__ #define __SIM_VOLTAGE_DOMAIN_HH__ #include <vector> #include "base/statistics.hh" #include "params/VoltageDomain.hh" #include "sim/clock_domain.hh" #include "sim/sim_object.hh" /** * A VoltageDomain is used to group clock domains that operate under * the same voltage. The class provides methods for setting and * getting the voltage. */ class VoltageDomain : public SimObject { public: typedef VoltageDomainParams Params; VoltageDomain(const Params &p); typedef SrcClockDomain::PerfLevel PerfLevel; /** * Get the current voltage. * * @return Voltage of the domain */ double voltage() const { return voltageOpPoints[_perfLevel]; } /** * Get the voltage at specified performance level. * * @param perf_level Performance level for which the voltage is requested * @return Voltage of the domain at specified performance level */ double voltage(PerfLevel perf_level) const { chatty_assert(perf_level < numVoltages(), "VoltageDomain %s "\ "request for voltage perf level %u is outside "\ "of numVoltages %u", name(), perf_level, numVoltages()); return voltageOpPoints[perf_level]; } uint32_t numVoltages() const { return (uint32_t)voltageOpPoints.size(); } /** * Set the voltage point of the domain. * @param Voltage value to be set */ void perfLevel(PerfLevel perf_level); /** * Get the voltage point of the domain. * @param Voltage value to be set */ PerfLevel perfLevel() const { return _perfLevel; } /** * Register a SrcClockDomain with this voltage domain. * @param src_clock_domain The SrcClockDomain to register. */ void registerSrcClockDom(SrcClockDomain *src_clock_dom) { assert(src_clock_dom->voltageDomain() == this); srcClockChildren.push_back(src_clock_dom); } /** * Startup has all SrcClockDomains registered with this voltage domain, so * try to make sure that all perf level requests from them are met. */ void startup() override; /** * Recomputes the highest (fastest, i.e., numerically lowest) requested * performance level of all associated clock domains, and updates the * performance level of this voltage domain to match. This means that for * two connected clock domains, one fast and one slow, the voltage domain * will provide the voltage associated with the fast DVFS operation point. * Must be called whenever a clock domain decides to swtich its performance * level. * * @return True, if the voltage was actually changed. */ bool sanitiseVoltages(); void serialize(CheckpointOut &cp) const override; void unserialize(CheckpointIn &cp) override; private: typedef std::vector<double> Voltages; /** * List of possible minimum voltage at each of the frequency operational * points, should be in descending order and same size as freqOpPoints. * An empty list corresponds to default voltage specified for the voltage * domain its clock domain belongs. The same voltage is applied for each * freqOpPoints, overall implying NO DVS */ const Voltages voltageOpPoints; PerfLevel _perfLevel; struct VoltageDomainStats : public Stats::Group { VoltageDomainStats(VoltageDomain &vd); /** * Stat for reporting voltage of the domain */ Stats::Value voltage; } stats; /** * List of associated SrcClockDomains that are connected to this voltage * domain. */ typedef std::vector<SrcClockDomain *> SrcClockChildren; SrcClockChildren srcClockChildren; }; #endif
36.9625
79
0.713054
[ "vector" ]
ebe344da194acbdf913443a4748afaa186ea89ac
5,443
hpp
C++
include/System/Runtime/Remoting/TypeInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Runtime/Remoting/TypeInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Runtime/Remoting/TypeInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Runtime.Remoting.IRemotingTypeInfo #include "System/Runtime/Remoting/IRemotingTypeInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Runtime.Remoting namespace System::Runtime::Remoting { // Forward declaring type: TypeInfo class TypeInfo; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Runtime::Remoting::TypeInfo); DEFINE_IL2CPP_ARG_TYPE(::System::Runtime::Remoting::TypeInfo*, "System.Runtime.Remoting", "TypeInfo"); // Type namespace: System.Runtime.Remoting namespace System::Runtime::Remoting { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Runtime.Remoting.TypeInfo // [TokenAttribute] Offset: FFFFFFFF class TypeInfo : public ::Il2CppObject/*, public ::System::Runtime::Remoting::IRemotingTypeInfo*/ { public: public: // private System.String serverType // Size: 0x8 // Offset: 0x10 ::StringW serverType; // Field size check static_assert(sizeof(::StringW) == 0x8); // private System.String[] serverHierarchy // Size: 0x8 // Offset: 0x18 ::ArrayW<::StringW> serverHierarchy; // Field size check static_assert(sizeof(::ArrayW<::StringW>) == 0x8); // private System.String[] interfacesImplemented // Size: 0x8 // Offset: 0x20 ::ArrayW<::StringW> interfacesImplemented; // Field size check static_assert(sizeof(::ArrayW<::StringW>) == 0x8); public: // Creating interface conversion operator: operator ::System::Runtime::Remoting::IRemotingTypeInfo operator ::System::Runtime::Remoting::IRemotingTypeInfo() noexcept { return *reinterpret_cast<::System::Runtime::Remoting::IRemotingTypeInfo*>(this); } // Get instance field reference: private System.String serverType [[deprecated("Use field access instead!")]] ::StringW& dyn_serverType(); // Get instance field reference: private System.String[] serverHierarchy [[deprecated("Use field access instead!")]] ::ArrayW<::StringW>& dyn_serverHierarchy(); // Get instance field reference: private System.String[] interfacesImplemented [[deprecated("Use field access instead!")]] ::ArrayW<::StringW>& dyn_interfacesImplemented(); // public System.String get_TypeName() // Offset: 0x12B21E4 ::StringW get_TypeName(); // public System.Void .ctor(System.Type type) // Offset: 0x12B1E70 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TypeInfo* New_ctor(::System::Type* type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::Remoting::TypeInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TypeInfo*, creationType>(type))); } // public System.Boolean CanCastTo(System.Type fromType, System.Object o) // Offset: 0x12B21EC bool CanCastTo(::System::Type* fromType, ::Il2CppObject* o); }; // System.Runtime.Remoting.TypeInfo #pragma pack(pop) static check_size<sizeof(TypeInfo), 32 + sizeof(::ArrayW<::StringW>)> __System_Runtime_Remoting_TypeInfoSizeCheck; static_assert(sizeof(TypeInfo) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Runtime::Remoting::TypeInfo::get_TypeName // Il2CppName: get_TypeName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Runtime::Remoting::TypeInfo::*)()>(&System::Runtime::Remoting::TypeInfo::get_TypeName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::TypeInfo*), "get_TypeName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Runtime::Remoting::TypeInfo::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Runtime::Remoting::TypeInfo::CanCastTo // Il2CppName: CanCastTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Runtime::Remoting::TypeInfo::*)(::System::Type*, ::Il2CppObject*)>(&System::Runtime::Remoting::TypeInfo::CanCastTo)> { static const MethodInfo* get() { static auto* fromType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* o = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::TypeInfo*), "CanCastTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{fromType, o}); } };
49.036036
201
0.721661
[ "object", "vector" ]
ebe78631b1f29b4be6738772989325c98f48eb6e
1,051
hpp
C++
include/bulk/util/meta_helpers.hpp
SdeBerg/Bulk
31fec4c80271d4cf600483e428a4c780fb129a37
[ "MIT" ]
null
null
null
include/bulk/util/meta_helpers.hpp
SdeBerg/Bulk
31fec4c80271d4cf600483e428a4c780fb129a37
[ "MIT" ]
null
null
null
include/bulk/util/meta_helpers.hpp
SdeBerg/Bulk
31fec4c80271d4cf600483e428a4c780fb129a37
[ "MIT" ]
null
null
null
#pragma once #include <type_traits> #include <utility> #include <vector> namespace bulk::meta { template <typename T> struct representation { static_assert(std::is_trivially_copyable<T>::value, "Only trivially copyable types are supported as `T` for " "distributed variables and queues"); using type = T; }; template <typename T> struct representation<T[]> { using type = std::vector<T>; }; template <> struct representation<std::string> { using type = std::string; }; // Partial specialization of alias templates is not allowed, so we need this // indirection template <typename Enable, typename... Ts> struct message_t; template <typename... Ts> struct message_t<typename std::enable_if_t<(sizeof...(Ts) > 1)>, Ts...> { std::tuple<typename representation<Ts>::type...> content; }; template <typename T> struct message_t<void, T> { typename representation<T>::type content; }; template <typename... Ts> struct message : public message_t<void, Ts...> {}; } // namespace bulk::meta
22.847826
76
0.680304
[ "vector" ]
ebe9c137e86f7f7732fd8cb9e176da9d0bb8cd5c
9,127
cxx
C++
Filters/Core/vtkCellCenters.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
Filters/Core/vtkCellCenters.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
Filters/Core/vtkCellCenters.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkCellCenters.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkCellCenters.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkDataArrayRange.h" #include "vtkDataSet.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkGenericCell.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkLogger.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkSMPThreadLocalObject.h" #include "vtkSMPTools.h" #include "vtkUnsignedCharArray.h" #include <atomic> vtkStandardNewMacro(vtkCellCenters); namespace { class CellCenterFunctor { vtkSMPThreadLocalObject<vtkGenericCell> TLCell; vtkSMPThreadLocal<std::vector<double>> TLWeigths; vtkDataSet* DataSet; vtkDoubleArray* CellCenters; vtkIdType MaxCellSize; public: CellCenterFunctor(vtkDataSet* ds, vtkDoubleArray* cellCenters) : DataSet(ds) , CellCenters(cellCenters) , MaxCellSize(ds->GetMaxCellSize()) { } void operator()(vtkIdType begin, vtkIdType end) { if (this->DataSet == nullptr) { return; } if (this->CellCenters == nullptr) { return; } auto& weights = this->TLWeigths.Local(); weights.resize(this->MaxCellSize); auto cell = this->TLCell.Local(); for (vtkIdType cellId = begin; cellId < end; ++cellId) { this->DataSet->GetCell(cellId, cell); double x[3] = { 0.0 }; if (cell->GetCellType() != VTK_EMPTY_CELL) { double pcoords[3]; int subId = cell->GetParametricCenter(pcoords); cell->EvaluateLocation(subId, pcoords, x, weights.data()); } else { x[0] = 0.0; x[1] = 0.0; x[2] = 0.0; } this->CellCenters->SetTypedTuple(cellId, x); } } }; //============================================================================== struct InputGhostCellFinder { InputGhostCellFinder(vtkUnsignedCharArray* ghostCells, vtkIdList* cellIdList) : GhostCells(ghostCells) , CellIdList(cellIdList) , HasInputGhostCells(false) { } void operator()(vtkIdType startId, vtkIdType endId) { auto ghosts = vtk::DataArrayValueRange<1>(this->GhostCells); for (vtkIdType id = startId; id < endId; ++id) { if (this->HasInputGhostCells) { return; } if (ghosts[this->CellIdList->GetId(id)] & (vtkDataSetAttributes::DUPLICATECELL | vtkDataSetAttributes::HIDDENCELL | vtkDataSetAttributes::REFINEDCELL)) { this->HasInputGhostCells = true; } } } vtkUnsignedCharArray* GhostCells; vtkIdList* CellIdList; std::atomic<bool> HasInputGhostCells; }; //============================================================================== struct GhostCellsToGhostPointsConverter { GhostCellsToGhostPointsConverter( vtkUnsignedCharArray* ghostCells, vtkUnsignedCharArray* ghostPoints, vtkIdList* cellIdList) : GhostCells(ghostCells) , GhostPoints(ghostPoints) , CellIdList(cellIdList) { } void operator()(vtkIdType startId, vtkIdType endId) { auto ghostPoints = vtk::DataArrayValueRange<1>(this->GhostPoints); auto ghostCells = vtk::DataArrayValueRange<1>(this->GhostCells); for (vtkIdType id = startId; id < endId; ++id) { unsigned char ghost = ghostCells[this->CellIdList->GetId(id)]; ghostPoints[id] = 0; if (ghost & vtkDataSetAttributes::DUPLICATECELL) { ghostPoints[id] |= vtkDataSetAttributes::DUPLICATEPOINT; } if (ghost & (vtkDataSetAttributes::HIDDENCELL | vtkDataSetAttributes::REFINEDCELL)) { ghostPoints[id] |= vtkDataSetAttributes::HIDDENPOINT; } } } vtkUnsignedCharArray* GhostCells; vtkUnsignedCharArray* GhostPoints; vtkIdList* CellIdList; }; } // end anonymous namespace //------------------------------------------------------------------------------ void vtkCellCenters::ComputeCellCenters(vtkDataSet* dataset, vtkDoubleArray* centers) { CellCenterFunctor functor(dataset, centers); // Call this once one the main thread before calling on multiple threads. // According to the documentation for vtkDataSet::GetCell(vtkIdType, vtkGenericCell*), // this is required to make this call subsequently thread safe if (dataset->GetNumberOfCells() > 0) { vtkNew<vtkGenericCell> cell; dataset->GetCell(0, cell); } // Now split the work among threads. vtkSMPTools::For(0, dataset->GetNumberOfCells(), functor); } //------------------------------------------------------------------------------ // Generate points int vtkCellCenters::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the input and output vtkDataSet* input = vtkDataSet::GetData(inputVector[0]); vtkPolyData* output = vtkPolyData::GetData(outputVector); vtkCellData* inCD = input->GetCellData(); vtkPointData* outPD = output->GetPointData(); vtkCellData* outCD = output->GetCellData(); vtkIdType numCells = input->GetNumberOfCells(); if (numCells == 0) { vtkDebugMacro(<< "No cells to generate center points for"); return 1; } vtkNew<vtkPoints> newPts; newPts->SetDataTypeToDouble(); newPts->SetNumberOfPoints(numCells); vtkDoubleArray* pointArray = vtkDoubleArray::SafeDownCast(newPts->GetData()); vtkNew<vtkIdList> pointIdList; pointIdList->SetNumberOfIds(numCells); vtkNew<vtkIdList> cellIdList; cellIdList->SetNumberOfIds(numCells); vtkCellCenters::ComputeCellCenters(input, pointArray); // Remove points that would have been produced by empty cells // This should be multithreaded someday bool hasEmptyCells = false; vtkTypeBool abort = 0; vtkIdType progressInterval = numCells / 10 + 1; vtkIdType numPoints = 0; for (vtkIdType cellId = 0; cellId < numCells && !abort; ++cellId) { if (!(cellId % progressInterval)) { vtkDebugMacro(<< "Processing #" << cellId); this->UpdateProgress((0.5 * cellId / numCells) + 0.5); abort = this->GetAbortExecute(); } if (input->GetCellType(cellId) != VTK_EMPTY_CELL) { newPts->SetPoint(numPoints, newPts->GetPoint(cellId)); pointIdList->SetId(numPoints, numPoints); cellIdList->SetId(numPoints, cellId); numPoints++; } else { hasEmptyCells = true; } } if (abort) { return 0; } newPts->Resize(numPoints); pointIdList->Resize(numPoints); cellIdList->Resize(numPoints); output->SetPoints(newPts); if (this->CopyArrays) { if (hasEmptyCells) { outPD->CopyAllocate(inCD, numPoints); outPD->CopyData(inCD, cellIdList, pointIdList); } else { outPD->PassData(inCD); // because number of points == number of cells } } if (vtkUnsignedCharArray* inputGhostCells = input->GetCellData()->GetGhostArray()) { ::InputGhostCellFinder finder(inputGhostCells, cellIdList); vtkSMPTools::For(0, numPoints, finder); if (finder.HasInputGhostCells) { vtkNew<vtkUnsignedCharArray> ghostPoints; ghostPoints->SetNumberOfValues(numPoints); ghostPoints->SetName(vtkDataSetAttributes::GhostArrayName()); ::GhostCellsToGhostPointsConverter worker(inputGhostCells, ghostPoints, cellIdList); vtkSMPTools::For(0, numPoints, worker); outPD->AddArray(ghostPoints); } } if (this->VertexCells) { vtkNew<vtkIdTypeArray> iArray; iArray->SetNumberOfComponents(1); iArray->SetNumberOfTuples(numPoints * 2); for (vtkIdType i = 0; i < numPoints; i++) { iArray->SetValue(2 * i, 1); iArray->SetValue(2 * i + 1, i); } vtkNew<vtkCellArray> verts; verts->AllocateEstimate(numPoints, 1); verts->ImportLegacyFormat(iArray); output->SetVerts(verts); outCD->ShallowCopy(outPD); } output->Squeeze(); this->UpdateProgress(1.0); return 1; } //------------------------------------------------------------------------------ int vtkCellCenters::FillInputPortInformation(int, vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } //------------------------------------------------------------------------------ void vtkCellCenters::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Vertex Cells: " << (this->VertexCells ? "On\n" : "Off\n"); os << indent << "CopyArrays: " << (this->CopyArrays ? "On" : "Off") << endl; }
28.34472
95
0.638326
[ "vector" ]
ebea041a55278ff735e391ed7baeb0538ee8f81d
14,765
cpp
C++
cpp/plugins/cucim.kit.cumed/src/cumed/cumed.cpp
aasthajh/cucim
a95cc5c4ab25beffeac42d642dea8cb1bbf21408
[ "Apache-2.0" ]
131
2021-04-09T19:02:10.000Z
2022-03-25T08:49:11.000Z
cpp/plugins/cucim.kit.cumed/src/cumed/cumed.cpp
aasthajh/cucim
a95cc5c4ab25beffeac42d642dea8cb1bbf21408
[ "Apache-2.0" ]
222
2021-04-12T07:15:14.000Z
2022-03-31T20:01:01.000Z
cpp/plugins/cucim.kit.cumed/src/cumed/cumed.cpp
aasthajh/cucim
a95cc5c4ab25beffeac42d642dea8cb1bbf21408
[ "Apache-2.0" ]
34
2021-04-09T18:54:13.000Z
2022-03-29T12:59:26.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #define CUCIM_EXPORTS #include "cumed.h" #include <fcntl.h> #include <filesystem> #include <fmt/format.h> #include <cucim/core/framework.h> #include <cucim/core/plugin_util.h> #include <cucim/filesystem/file_path.h> #include <cucim/io/format/image_format.h> #include <cucim/memory/memory_manager.h> const struct cucim::PluginImplDesc kPluginImpl = { "cucim.kit.cumed", // name { 0, 1, 0 }, // version "dev", // build "clara team", // author "cumed", // description "cumed plugin", // long_description "Apache-2.0", // license "https://github.com/rapidsai/cucim", // url "linux", // platforms, cucim::PluginHotReload::kDisabled, // hot_reload }; // Using CARB_PLUGIN_IMPL_MINIMAL instead of CARB_PLUGIN_IMPL // This minimal macro doesn't define global variables for logging, profiler, crash reporting, // and also doesn't call for the client registration for those systems CUCIM_PLUGIN_IMPL_MINIMAL(kPluginImpl, cucim::io::format::IImageFormat) CUCIM_PLUGIN_IMPL_NO_DEPS() static void set_enabled(bool val) { (void)val; } static bool is_enabled() { return true; } static const char* get_format_name() { return "MetaIO"; } static bool CUCIM_ABI checker_is_valid(const char* file_name, const char* buf, size_t size) { (void)buf; (void)size; auto file = std::filesystem::path(file_name); auto extension = file.extension().string(); if (extension.compare(".mhd") == 0) { return true; } return false; } static CuCIMFileHandle CUCIM_ABI parser_open(const char* file_path_) { const cucim::filesystem::Path& file_path = file_path_; int mode = O_RDONLY; // Copy file path (Allocated memory would be freed at close() method.) char* file_path_cstr = static_cast<char*>(malloc(file_path.size() + 1)); (void)file_path_cstr; memcpy(file_path_cstr, file_path.c_str(), file_path.size()); file_path_cstr[file_path.size()] = '\0'; int fd = ::open(file_path_cstr, mode, 0666); if (fd == -1) { cucim_free(file_path_cstr); throw std::invalid_argument(fmt::format("Cannot open {}!", file_path)); } // TODO: make file_handle_ object to pointer auto file_handle = CuCIMFileHandle{ fd, nullptr, FileHandleType::kPosix, file_path_cstr, nullptr }; return file_handle; } static bool CUCIM_ABI parser_parse(CuCIMFileHandle* handle, cucim::io::format::ImageMetadataDesc* out_metadata_desc) { (void)handle; if (!out_metadata_desc || !out_metadata_desc->handle) { throw std::runtime_error("out_metadata_desc shouldn't be nullptr!"); } cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); // // Metadata Setup // // Note: int-> uint16_t due to type differences between ImageMetadataDesc.ndim and DLTensor.ndim const uint16_t ndim = 3; auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; std::pmr::vector<int64_t> shape({ 256, 256, 3 }, &resource); DLDataType dtype{ kDLUInt, 8, 1 }; // Assume RGB std::pmr::vector<std::string_view> channel_names( { std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource); std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); spacing.insert(spacing.end(), ndim, 1.0); std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); spacing_units.emplace_back(std::string_view{ "pixel" }); spacing_units.emplace_back(std::string_view{ "pixel" }); spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; size_t level_count = 1; const uint16_t level_ndim = 2; // {'X', 'Y'} std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { level_dimensions.emplace_back(256); level_dimensions.emplace_back(256); } std::pmr::vector<float> level_downsamples(&resource); for (size_t i = 0; i < level_count; ++i) { level_downsamples.emplace_back(1.0); } std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { level_tile_sizes.emplace_back(256); level_tile_sizes.emplace_back(256); } const size_t associated_image_count = 0; std::pmr::vector<std::string_view> associated_image_names(&resource); std::string_view raw_data{ "" }; // Dynamically allocate memory for json_data (need to be freed manually); const std::string& json_str = std::string{}; char* json_data_ptr = static_cast<char*>(cucim_malloc(json_str.size() + 1)); memcpy(json_data_ptr, json_str.data(), json_str.size() + 1); std::string_view json_data{ json_data_ptr, json_str.size() }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(level_count); out_metadata.level_ndim(level_ndim); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); return true; } static bool CUCIM_ABI parser_close(CuCIMFileHandle* handle) { if (handle->path) { cucim_free(handle->path); handle->path = nullptr; } if (handle->client_data) { // TODO: comment out and reinterpret_cast when needed. // delete reinterpret_cast<xx*>(handle->client_data); handle->client_data = nullptr; } return true; } static bool CUCIM_ABI reader_read(const CuCIMFileHandle* handle, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata_desc = nullptr) { (void)handle; (void)metadata; std::string device_name(request->device); if (request->shm_name) { device_name = device_name + fmt::format("[{}]", request->shm_name); // TODO: check performance } cucim::io::Device out_device(device_name); uint8_t* raster = nullptr; uint32_t width = 256; uint32_t height = 256; uint32_t samples_per_pixel = 3; size_t raster_size = width * height * samples_per_pixel; // Raw metadata for the associated image const char* raw_data_ptr = nullptr; size_t raw_data_len = 0; // Json metadata for the associated image char* json_data_ptr = nullptr; // Populate image data const uint16_t ndim = 3; int64_t* container_shape = static_cast<int64_t*>(cucim_malloc(sizeof(int64_t) * ndim)); container_shape[0] = height; container_shape[1] = width; container_shape[2] = 3; // hard-coded for 'C' // Copy the raster memory and free it if needed. cucim::memory::move_raster_from_host((void**)&raster, raster_size, out_device); auto& out_image_container = out_image_data->container; out_image_container.data = raster; out_image_container.ctx = DLContext{ static_cast<DLDeviceType>(out_device.type()), out_device.index() }; out_image_container.ndim = ndim; out_image_container.dtype = { kDLUInt, 8, 1 }; out_image_container.shape = container_shape; out_image_container.strides = nullptr; // Tensor is compact and row-majored out_image_container.byte_offset = 0; auto& shm_name = out_device.shm_name(); size_t shm_name_len = shm_name.size(); if (shm_name_len != 0) { out_image_data->shm_name = static_cast<char*>(cucim_malloc(shm_name_len + 1)); memcpy(out_image_data->shm_name, shm_name.c_str(), shm_name_len + 1); } else { out_image_data->shm_name = nullptr; } // Populate metadata if (out_metadata_desc && out_metadata_desc->handle) { cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; std::pmr::vector<int64_t> shape(&resource); shape.reserve(ndim); shape.insert(shape.end(), &container_shape[0], &container_shape[ndim]); DLDataType dtype{ kDLUInt, 8, 1 }; // TODO: Do not assume channel names as 'RGB' std::pmr::vector<std::string_view> channel_names( { std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource); // We don't know physical pixel size for associated image so fill it with default value 1 std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); spacing.insert(spacing.end(), ndim, 1.0); std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; // Manually set resolution dimensions to 2 const uint16_t level_ndim = 2; std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_ndim * 1); // it has only one size level_dimensions.emplace_back(shape[1]); // width level_dimensions.emplace_back(shape[0]); // height std::pmr::vector<float> level_downsamples(&resource); level_downsamples.reserve(1); level_downsamples.emplace_back(1.0); std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_ndim * 1); // it has only one size level_tile_sizes.emplace_back(shape[1]); // tile_width level_tile_sizes.emplace_back(shape[0]); // tile_height // Empty associated images const size_t associated_image_count = 0; std::pmr::vector<std::string_view> associated_image_names(&resource); std::string_view raw_data{ raw_data_ptr ? raw_data_ptr : "", raw_data_len }; std::string_view json_data{ json_data_ptr ? json_data_ptr : "" }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(1); out_metadata.level_ndim(2); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); } return true; } static bool CUCIM_ABI writer_write(const CuCIMFileHandle* handle, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageDataDesc* image_data) { (void)handle; (void)metadata; (void)image_data; return true; } void fill_interface(cucim::io::format::IImageFormat& iface) { static cucim::io::format::ImageCheckerDesc image_checker = { 0, 0, checker_is_valid }; static cucim::io::format::ImageParserDesc image_parser = { parser_open, parser_parse, parser_close }; static cucim::io::format::ImageReaderDesc image_reader = { reader_read }; static cucim::io::format::ImageWriterDesc image_writer = { writer_write }; // clang-format off static cucim::io::format::ImageFormatDesc image_format_desc = { set_enabled, is_enabled, get_format_name, image_checker, image_parser, image_reader, image_writer }; // clang-format on // clang-format off iface = { &image_format_desc, 1 }; // clang-format on }
35.154762
118
0.660549
[ "object", "shape", "vector", "3d" ]
ebeb264c3720fd97c395cf909832434b8d318049
25,319
cc
C++
components/autofill_assistant/browser/user_data_util.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill_assistant/browser/user_data_util.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
components/autofill_assistant/browser/user_data_util.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 "components/autofill_assistant/browser/user_data_util.h" #include <map> #include <numeric> #include "base/callback.h" #include "base/i18n/case_conversion.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/geo/address_i18n.h" #include "components/autofill_assistant/browser/action_value.pb.h" #include "components/autofill_assistant/browser/cud_condition.pb.h" #include "components/autofill_assistant/browser/field_formatter.h" #include "components/autofill_assistant/browser/model.pb.h" #include "components/autofill_assistant/browser/url_utils.h" #include "components/autofill_assistant/browser/website_login_manager.h" #include "components/strings/grit/components_strings.h" #include "third_party/libaddressinput/chromium/addressinput_util.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" #include "third_party/re2/src/re2/re2.h" #include "ui/base/l10n/l10n_util.h" namespace autofill_assistant { namespace user_data { namespace { constexpr char kDefaultLocale[] = "en-US"; template <typename T> ClientStatus ExtractDataAndFormatClientValue( const T& client_value, const ValueExpression& value_expression, const UserData& user_data, bool quote_meta, const std::string& locale, std::string* out_value) { if (value_expression.chunk().empty()) { VLOG(1) << "|value_expression| is empty"; return ClientStatus(INVALID_ACTION); } std::map<field_formatter::Key, std::string> data; std::string localeOrDefault = locale.empty() ? kDefaultLocale : locale; if (client_value.has_profile()) { const auto& profile = client_value.profile(); if (profile.identifier().empty()) { VLOG(1) << "empty |profile.identifier|"; return ClientStatus(INVALID_ACTION); } const autofill::AutofillProfile* address = user_data.selected_address(profile.identifier()); if (address == nullptr) { VLOG(1) << "Requested unknown address '" << profile.identifier() << "'"; return ClientStatus(PRECONDITION_FAILED); } auto address_map = field_formatter::CreateAutofillMappings(*address, localeOrDefault); data.insert(address_map.begin(), address_map.end()); } const autofill::CreditCard* card = user_data.selected_card(); if (card != nullptr) { auto card_map = field_formatter::CreateAutofillMappings(*card, localeOrDefault); data.insert(card_map.begin(), card_map.end()); } for (const auto& chunk : value_expression.chunk()) { if (!chunk.has_memory_key() || !user_data.HasAdditionalValue(chunk.memory_key())) { continue; } const ValueProto* value = user_data.GetAdditionalValue(chunk.memory_key()); if (value->strings().values().size() == 1) { data.emplace(field_formatter::Key(chunk.memory_key()), value->strings().values(0)); } } const ClientStatus& format_status = field_formatter::FormatExpression( value_expression, data, quote_meta, out_value); if (!format_status.ok()) { return format_status; } if (out_value->empty()) { VLOG(1) << "|value_expression| result is empty"; return ClientStatus(EMPTY_VALUE_EXPRESSION_RESULT); } return OkClientStatus(); } void OnGetStoredPassword( base::OnceCallback<void(const ClientStatus&, const std::string&)> callback, bool success, std::string password) { if (!success) { std::move(callback).Run(ClientStatus(AUTOFILL_INFO_NOT_AVAILABLE), std::string()); return; } std::move(callback).Run(OkClientStatus(), password); } bool EvaluateCondition(const std::map<field_formatter::Key, std::string>& data, const RequiredDataPiece::Condition& condition) { auto it = data.find(field_formatter::Key(condition.key())); if (it == data.end()) { return false; } auto value = it->second; switch (condition.condition_case()) { case RequiredDataPiece::Condition::kNotEmpty: return !value.empty(); case RequiredDataPiece::Condition::kRegexp: { re2::RE2::Options options; options.set_case_sensitive( condition.regexp().text_filter().case_sensitive()); re2::RE2 regexp(condition.regexp().text_filter().re2(), options); return RE2::PartialMatch(value, regexp); } case RequiredDataPiece::Condition::CONDITION_NOT_SET: return false; } } std::vector<std::string> GetValidationErrors( const std::map<field_formatter::Key, std::string>& data, const std::vector<RequiredDataPiece>& required_data_pieces) { std::vector<std::string> errors; for (const auto& required_data_piece : required_data_pieces) { if (!EvaluateCondition(data, required_data_piece.condition())) { errors.push_back(required_data_piece.error_message()); } } return errors; } // Helper function that compares instances of AutofillProfile by completeness // in regards to the current options. Full profiles should be ordered before // empty ones and fall back to compare the profile's last usage. bool CompletenessCompareContacts( const CollectUserDataOptions& options, const autofill::AutofillProfile& a, const std::map<field_formatter::Key, std::string>& data_a, const autofill::AutofillProfile& b, const std::map<field_formatter::Key, std::string>& data_b) { int incomplete_fields_a = GetValidationErrors(data_a, options.required_contact_data_pieces).size(); int incomplete_fields_b = GetValidationErrors(data_b, options.required_contact_data_pieces).size(); if (incomplete_fields_a != incomplete_fields_b) { return incomplete_fields_a <= incomplete_fields_b; } return a.use_date() > b.use_date(); } int GetAddressEditorCompletenessRating( const autofill::AutofillProfile& profile) { auto address_data = autofill::i18n::CreateAddressDataFromAutofillProfile( profile, kDefaultLocale); std::multimap<i18n::addressinput::AddressField, i18n::addressinput::AddressProblem> problems; autofill::addressinput::ValidateRequiredFields( *address_data, /* filter= */ nullptr, &problems); return problems.size(); } int CompletenessCompareAddresses( const std::vector<RequiredDataPiece>& required_data_pieces, const autofill::AutofillProfile& a, const std::map<field_formatter::Key, std::string>& data_a, const autofill::AutofillProfile& b, const std::map<field_formatter::Key, std::string>& data_b) { // Compare by editor completeness first. This is done because the // AddressEditor only allows storing addresses it considers complete. int incomplete_fields_a = GetAddressEditorCompletenessRating(a); int incomplete_fields_b = GetAddressEditorCompletenessRating(b); if (incomplete_fields_a != incomplete_fields_b) { return incomplete_fields_b - incomplete_fields_a; } incomplete_fields_a = GetValidationErrors(data_a, required_data_pieces).size(); incomplete_fields_b = GetValidationErrors(data_b, required_data_pieces).size(); return incomplete_fields_b - incomplete_fields_a; } // Helper function that compares instances of AutofillProfile by completeness // in regards to the current options. Full profiles should be ordered before // empty ones and fall back to compare the profile's name in case of equality. bool CompletenessCompareShippingAddresses( const CollectUserDataOptions& options, const autofill::AutofillProfile& a, const std::map<field_formatter::Key, std::string>& data_a, const autofill::AutofillProfile& b, const std::map<field_formatter::Key, std::string>& data_b) { int address_compare = CompletenessCompareAddresses( options.required_shipping_address_data_pieces, a, data_a, b, data_b); if (address_compare != 0) { return address_compare > 0; } return a.use_date() > b.use_date(); } // Helper function that compares instances of PaymentInstrument by completeness // in regards to the current options. Full payment instruments should be // ordered before empty ones and fall back to compare the full name on the // credit card in case of equality. bool CompletenessComparePaymentInstruments( const CollectUserDataOptions& options, const PaymentInstrument& a, const std::map<field_formatter::Key, std::string>& data_a, const PaymentInstrument& b, const std::map<field_formatter::Key, std::string>& data_b) { DCHECK(a.card); DCHECK(b.card); int incomplete_fields_a = GetValidationErrors(data_a, options.required_credit_card_data_pieces) .size(); int incomplete_fields_b = GetValidationErrors(data_b, options.required_credit_card_data_pieces) .size(); if (incomplete_fields_a != incomplete_fields_b) { return incomplete_fields_a <= incomplete_fields_b; } bool a_has_valid_expiration = a.card->HasValidExpirationDate(); bool b_has_valid_expiration = b.card->HasValidExpirationDate(); if (a_has_valid_expiration != b_has_valid_expiration) { return !b_has_valid_expiration; } bool a_has_valid_number = (a.card->record_type() != autofill::CreditCard::MASKED_SERVER_CARD && a.card->HasValidCardNumber()) || (a.card->record_type() == autofill::CreditCard::MASKED_SERVER_CARD && !a.card->GetRawInfo(autofill::CREDIT_CARD_NUMBER).empty()); bool b_has_valid_number = (b.card->record_type() != autofill::CreditCard::MASKED_SERVER_CARD && b.card->HasValidCardNumber()) || (b.card->record_type() == autofill::CreditCard::MASKED_SERVER_CARD && !b.card->GetRawInfo(autofill::CREDIT_CARD_NUMBER).empty()); if (a_has_valid_number != b_has_valid_number) { return !b_has_valid_number; } bool a_has_address = a.billing_address != nullptr; bool b_has_address = b.billing_address != nullptr; if (a_has_address != b_has_address) { return !b_has_address; } if (a_has_address && b_has_address) { int address_compare = CompletenessCompareAddresses( options.required_billing_address_data_pieces, *a.billing_address, data_a, *b.billing_address, data_b); if (address_compare != 0) { return address_compare > 0; } } return a.card->use_date() > b.card->use_date(); } } // namespace std::vector<std::string> GetContactValidationErrors( const autofill::AutofillProfile* profile, const CollectUserDataOptions& collect_user_data_options) { if (collect_user_data_options.required_contact_data_pieces.empty()) { return std::vector<std::string>(); } return GetValidationErrors( profile ? field_formatter::CreateAutofillMappings(*profile, kDefaultLocale) : std::map<field_formatter::Key, std::string>(), collect_user_data_options.required_contact_data_pieces); } std::vector<int> SortContactsByCompleteness( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<autofill::AutofillProfile>>& profiles) { std::vector<std::map<field_formatter::Key, std::string>> mapped_profiles; for (const auto& profile : profiles) { mapped_profiles.push_back( field_formatter::CreateAutofillMappings(*profile, kDefaultLocale)); } std::vector<int> profile_indices(profiles.size()); std::iota(std::begin(profile_indices), std::end(profile_indices), 0); std::stable_sort( profile_indices.begin(), profile_indices.end(), [&collect_user_data_options, &profiles, &mapped_profiles](int i, int j) { return CompletenessCompareContacts(collect_user_data_options, *profiles[i], mapped_profiles[i], *profiles[j], mapped_profiles[j]); }); return profile_indices; } int GetDefaultContactProfile( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<autofill::AutofillProfile>>& profiles) { if (profiles.empty()) { return -1; } auto sorted_indices = SortContactsByCompleteness(collect_user_data_options, profiles); if (!collect_user_data_options.default_email.empty()) { for (int index : sorted_indices) { if (base::UTF16ToUTF8( profiles[index]->GetRawInfo(autofill::EMAIL_ADDRESS)) == collect_user_data_options.default_email) { return index; } } } return sorted_indices[0]; } std::vector<std::string> GetShippingAddressValidationErrors( const autofill::AutofillProfile* profile, const CollectUserDataOptions& collect_user_data_options) { std::vector<std::string> errors; if (!collect_user_data_options.request_shipping) { return errors; } if (!collect_user_data_options.required_shipping_address_data_pieces .empty()) { errors = GetValidationErrors( profile ? field_formatter::CreateAutofillMappings(*profile, kDefaultLocale) : std::map<field_formatter::Key, std::string>(), collect_user_data_options.required_shipping_address_data_pieces); } // Require address editor completeness if Assistant validation succeeds. If // Assistant validation fails, the editor has to be opened and requires // completeness to save the change, do not append the (potentially duplicate) // error in this case. if (errors.empty() && (profile == nullptr || GetAddressEditorCompletenessRating(*profile) != 0)) { errors.push_back(l10n_util::GetStringUTF8( IDS_AUTOFILL_ASSISTANT_PAYMENT_INFORMATION_MISSING)); } return errors; } std::vector<int> SortShippingAddressesByCompleteness( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<autofill::AutofillProfile>>& profiles) { std::vector<std::map<field_formatter::Key, std::string>> mapped_profiles; for (const auto& profile : profiles) { mapped_profiles.push_back( field_formatter::CreateAutofillMappings(*profile, kDefaultLocale)); } std::vector<int> profile_indices(profiles.size()); std::iota(std::begin(profile_indices), std::end(profile_indices), 0); std::stable_sort( profile_indices.begin(), profile_indices.end(), [&collect_user_data_options, &profiles, &mapped_profiles](int i, int j) { return CompletenessCompareShippingAddresses( collect_user_data_options, *profiles[i], mapped_profiles[i], *profiles[j], mapped_profiles[j]); }); return profile_indices; } int GetDefaultShippingAddressProfile( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<autofill::AutofillProfile>>& profiles) { if (profiles.empty()) { return -1; } auto sorted_indices = SortShippingAddressesByCompleteness(collect_user_data_options, profiles); return sorted_indices[0]; } std::vector<std::string> GetPaymentInstrumentValidationErrors( const autofill::CreditCard* credit_card, const autofill::AutofillProfile* billing_address, const CollectUserDataOptions& collect_user_data_options) { std::vector<std::string> errors; if (!collect_user_data_options.request_payment_method) { return errors; } if (!collect_user_data_options.required_credit_card_data_pieces.empty()) { const auto& card_errors = GetValidationErrors( credit_card ? field_formatter::CreateAutofillMappings(*credit_card, kDefaultLocale) : std::map<field_formatter::Key, std::string>(), collect_user_data_options.required_credit_card_data_pieces); errors.insert(errors.end(), card_errors.begin(), card_errors.end()); } if (credit_card && !credit_card->HasValidExpirationDate()) { errors.push_back(collect_user_data_options.credit_card_expired_text); } if (!collect_user_data_options.required_billing_address_data_pieces.empty()) { const auto& address_errors = GetValidationErrors( billing_address ? field_formatter::CreateAutofillMappings( *billing_address, kDefaultLocale) : std::map<field_formatter::Key, std::string>(), collect_user_data_options.required_billing_address_data_pieces); errors.insert(errors.end(), address_errors.begin(), address_errors.end()); } // Require card editor completeness if Assistant validation succeeds. If // Assistant validation fails, the editor has to be opened and requires // completeness to save the change, do not append the (potentially duplicate) // error in this case. if (errors.empty()) { if (credit_card && credit_card->record_type() != autofill::CreditCard::MASKED_SERVER_CARD && !credit_card->HasValidCardNumber()) { // Can't check validity of masked server card numbers, because they are // incomplete until decrypted. errors.push_back(l10n_util::GetStringUTF8( IDS_AUTOFILL_ASSISTANT_PAYMENT_INFORMATION_MISSING)); } else if (!billing_address || GetAddressEditorCompletenessRating(*billing_address) != 0) { errors.push_back(l10n_util::GetStringUTF8( IDS_AUTOFILL_ASSISTANT_PAYMENT_INFORMATION_MISSING)); } } return errors; } std::vector<int> SortPaymentInstrumentsByCompleteness( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<PaymentInstrument>>& payment_instruments) { std::vector<std::map<field_formatter::Key, std::string>> mapped_payment_instruments; for (const auto& payment_instrument : payment_instruments) { std::map<field_formatter::Key, std::string> mapped_payment_instrument = field_formatter::CreateAutofillMappings(*payment_instrument->card, kDefaultLocale); if (payment_instrument->billing_address != nullptr) { std::map<field_formatter::Key, std::string> mapped_address = field_formatter::CreateAutofillMappings( *payment_instrument->billing_address, kDefaultLocale); mapped_payment_instrument.insert(mapped_address.begin(), mapped_address.end()); } mapped_payment_instruments.push_back(mapped_payment_instrument); } std::vector<int> payment_instrument_indices(payment_instruments.size()); std::iota(std::begin(payment_instrument_indices), std::end(payment_instrument_indices), 0); std::stable_sort(payment_instrument_indices.begin(), payment_instrument_indices.end(), [&collect_user_data_options, &payment_instruments, &mapped_payment_instruments](int a, int b) { return CompletenessComparePaymentInstruments( collect_user_data_options, *payment_instruments[a], mapped_payment_instruments[a], *payment_instruments[b], mapped_payment_instruments[b]); }); return payment_instrument_indices; } int GetDefaultPaymentInstrument( const CollectUserDataOptions& collect_user_data_options, const std::vector<std::unique_ptr<PaymentInstrument>>& payment_instruments) { if (payment_instruments.empty()) { return -1; } auto sorted_indices = SortPaymentInstrumentsByCompleteness( collect_user_data_options, payment_instruments); return sorted_indices[0]; } std::unique_ptr<autofill::AutofillProfile> MakeUniqueFromProfile( const autofill::AutofillProfile& profile) { auto unique_profile = std::make_unique<autofill::AutofillProfile>(profile); // Temporary workaround so that fields like first/last name a properly // populated. unique_profile->FinalizeAfterImport(); return unique_profile; } bool CompareContactDetails( const CollectUserDataOptions& collect_user_data_options, const autofill::AutofillProfile* a, const autofill::AutofillProfile* b) { std::vector<autofill::ServerFieldType> types; if (collect_user_data_options.request_payer_name) { types.emplace_back(autofill::NAME_FULL); types.emplace_back(autofill::NAME_FIRST); types.emplace_back(autofill::NAME_MIDDLE); types.emplace_back(autofill::NAME_LAST); } if (collect_user_data_options.request_payer_phone) { types.emplace_back(autofill::PHONE_HOME_WHOLE_NUMBER); } if (collect_user_data_options.request_payer_email) { types.emplace_back(autofill::EMAIL_ADDRESS); } if (types.empty()) { return a->guid() == b->guid(); } for (auto type : types) { int comparison = a->GetRawInfo(type).compare(b->GetRawInfo(type)); if (comparison != 0) { return false; } } return true; } ClientStatus GetFormattedClientValue(const AutofillValue& autofill_value, const UserData& user_data, std::string* out_value) { return ExtractDataAndFormatClientValue( autofill_value, autofill_value.value_expression(), user_data, /* quote_meta= */ false, autofill_value.locale(), out_value); } ClientStatus GetFormattedClientValue( const AutofillValueRegexp& autofill_value_regexp, const UserData& user_data, std::string* out_value) { return ExtractDataAndFormatClientValue( autofill_value_regexp, autofill_value_regexp.value_expression_re2().value_expression(), user_data, /* quote_meta= */ true, autofill_value_regexp.locale(), out_value); } void GetPasswordManagerValue( const PasswordManagerValue& password_manager_value, const ElementFinder::Result& target_element, const UserData* user_data, WebsiteLoginManager* website_login_manager, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) { if (!user_data->selected_login_) { std::move(callback).Run(ClientStatus(PRECONDITION_FAILED), std::string()); return; } if (!target_element.container_frame_host) { std::move(callback).Run(ClientStatus(PASSWORD_ORIGIN_MISMATCH), std::string()); return; } switch (password_manager_value.credential_type()) { case PasswordManagerValue::PASSWORD: { auto login = *user_data->selected_login_; // Origin check is done in PWM based on the // |target_element.container_frame_host->GetLastCommittedURL()| login.origin = target_element.container_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL(); website_login_manager->GetPasswordForLogin( login, base::BindOnce(&OnGetStoredPassword, std::move(callback))); return; } case PasswordManagerValue::USERNAME: std::move(callback).Run(OkClientStatus(), user_data->selected_login_->username); return; case PasswordManagerValue::NOT_SET: std::move(callback).Run(ClientStatus(INVALID_ACTION), std::string()); return; } } ClientStatus GetClientMemoryStringValue(const std::string& client_memory_key, const UserData* user_data, std::string* out_value) { if (client_memory_key.empty()) { return ClientStatus(INVALID_ACTION); } if (!user_data->HasAdditionalValue(client_memory_key) || user_data->GetAdditionalValue(client_memory_key) ->strings() .values() .size() != 1) { VLOG(1) << "Requested key '" << client_memory_key << "' not available in client memory"; return ClientStatus(PRECONDITION_FAILED); } out_value->assign( user_data->GetAdditionalValue(client_memory_key)->strings().values(0)); return OkClientStatus(); } void ResolveTextValue(const TextValue& text_value, const ElementFinder::Result& target_element, const ActionDelegate* action_delegate, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) { std::string value; ClientStatus status = OkClientStatus(); switch (text_value.value_case()) { case TextValue::kText: value = text_value.text(); break; case TextValue::kAutofillValue: { status = GetFormattedClientValue(text_value.autofill_value(), *action_delegate->GetUserData(), &value); break; } case TextValue::kPasswordManagerValue: { GetPasswordManagerValue(text_value.password_manager_value(), target_element, action_delegate->GetUserData(), action_delegate->GetWebsiteLoginManager(), std::move(callback)); return; } case TextValue::kClientMemoryKey: { status = GetClientMemoryStringValue(text_value.client_memory_key(), action_delegate->GetUserData(), &value); break; } case TextValue::VALUE_NOT_SET: status = ClientStatus(INVALID_ACTION); } std::move(callback).Run(status, value); } } // namespace user_data } // namespace autofill_assistant
39.254264
85
0.70295
[ "vector", "model" ]
ebf6323e4e43d16b20818f32b1b440f7a365dc5d
18,010
cpp
C++
MoravaEngine/src/Scene/Scene.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Scene/Scene.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Scene/Scene.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#define _CRT_SECURE_NO_WARNINGS #include "Scene/Scene.h" #include "Hazel/Events/ApplicationEvent.h" #include "Hazel/Scene/Components.h" #include "Core/Application.h" #include "Mesh/MeshData.h" #include "Mesh/Tile2D.h" #include "Texture/TextureLoader.h" #include "Core/Timer.h" #include "Core/Input.h" #include "Core/MousePicker.h" SceneSettings Scene::sceneSettings; // ImGuizmo glm::mat4* Scene::s_ImGuizmoTransform = nullptr; int Scene::s_ImGuizmoType = -1; // -1 = no gizmo Scene::Scene() { sceneSettings.enableShadows = false; sceneSettings.enableOmniShadows = false; sceneSettings.enableCascadedShadowMaps = false; sceneSettings.enablePointLights = false; sceneSettings.enableSpotLights = false; sceneSettings.enableWaterEffects = false; sceneSettings.enableSkybox = false; sceneSettings.enableNormalMaps = false; sceneSettings.enableCulling = false; sceneSettings.enableParticles = false; sceneSettings.cameraPosition = glm::vec3(0.0f, 6.0f, 20.0f); sceneSettings.cameraStartYaw = -90.0f; sceneSettings.cameraStartPitch = 0.0f; sceneSettings.cameraMoveSpeed = 4.0f; sceneSettings.nearPlane = 0.01f; sceneSettings.farPlane = 1000.0f; // Directional light sceneSettings.directionalLight.base.enabled = true; sceneSettings.directionalLight.base.color = glm::vec3(1.0f, 1.0f, 1.0f); sceneSettings.directionalLight.base.ambientIntensity = 0.5f; sceneSettings.directionalLight.base.diffuseIntensity = 0.8f; sceneSettings.directionalLight.direction = glm::vec3(3.0f, -9.0f, -3.0f); sceneSettings.lightProjectionMatrix = glm::ortho(-32.0f, 32.0f, -32.0f, 32.0f, -32.0f, 32.0f); // Point lights sceneSettings.pointLights[0].base.enabled = true; sceneSettings.pointLights[0].base.color = glm::vec3(1.0f, 0.0f, 1.0f); sceneSettings.pointLights[0].position = glm::vec3(0.0f, 20.0f, 0.0f); sceneSettings.pointLights[0].base.ambientIntensity = 1.0f; sceneSettings.pointLights[0].base.diffuseIntensity = 1.0f; sceneSettings.pointLights[0].constant = 0.4f; sceneSettings.pointLights[0].linear = 0.3f; sceneSettings.pointLights[0].exponent = 0.2f; sceneSettings.pointLights[1].base.enabled = true; sceneSettings.pointLights[1].base.color = glm::vec3(1.0f, 0.0f, 0.0f); sceneSettings.pointLights[1].position = glm::vec3(-2.0f, 9.6f, 0.0f); sceneSettings.pointLights[1].base.ambientIntensity = 1.0f; sceneSettings.pointLights[1].base.diffuseIntensity = 1.0f; sceneSettings.pointLights[1].constant = 0.4f; sceneSettings.pointLights[1].linear = 0.3f; sceneSettings.pointLights[1].exponent = 0.2f; sceneSettings.pointLights[2].base.enabled = true; sceneSettings.pointLights[2].base.color = glm::vec3(0.8f, 0.8f, 0.5f); sceneSettings.pointLights[2].position = glm::vec3(-2.0f, 4.0f, 0.0f); sceneSettings.pointLights[2].base.ambientIntensity = 1.0f; sceneSettings.pointLights[2].base.ambientIntensity = 1.0f; sceneSettings.pointLights[2].constant = 0.4f; sceneSettings.pointLights[2].linear = 0.3f; sceneSettings.pointLights[2].exponent = 0.2f; sceneSettings.pointLights[3].base.enabled = true; sceneSettings.pointLights[3].base.color = glm::vec3(0.8f, 0.8f, 0.5f); sceneSettings.pointLights[3].position = glm::vec3(-2.0f, 4.0f, 0.0f); sceneSettings.pointLights[3].base.ambientIntensity = 1.0f; sceneSettings.pointLights[3].base.diffuseIntensity = 1.0f; sceneSettings.pointLights[3].constant = 0.4f; sceneSettings.pointLights[3].linear = 0.3f; sceneSettings.pointLights[3].exponent = 0.2f; // Spot lights sceneSettings.spotLights[0].base.base.enabled = true; sceneSettings.spotLights[0].base.base.color = glm::vec3(1.0f, 1.0f, 1.0f); sceneSettings.spotLights[0].base.position = glm::vec3(0.0f, 0.0f, 0.0f); sceneSettings.spotLights[0].direction = glm::vec3(0.0f, -1.0f, 0.0f); sceneSettings.spotLights[0].base.base.ambientIntensity = 1.0f; sceneSettings.spotLights[0].base.base.diffuseIntensity = 1.0f; sceneSettings.spotLights[0].base.constant = 0.4f; sceneSettings.spotLights[0].base.linear = 0.3f; sceneSettings.spotLights[0].base.exponent = 0.2f; sceneSettings.spotLights[0].edge = 35.0f; sceneSettings.spotLights[1].base.base.enabled = true; sceneSettings.spotLights[1].base.base.color = glm::vec3(1.0f, 1.0f, 1.0f); sceneSettings.spotLights[1].base.position = glm::vec3(0.0f, 0.0f, 0.0f); sceneSettings.spotLights[1].direction = glm::vec3(0.0f, -1.0f, 0.0f); sceneSettings.spotLights[1].base.base.ambientIntensity = 1.0f; sceneSettings.spotLights[1].base.base.diffuseIntensity = 1.0f; sceneSettings.spotLights[1].base.constant = 0.4f; sceneSettings.spotLights[1].base.linear = 0.3f; sceneSettings.spotLights[1].base.exponent = 0.2f; sceneSettings.spotLights[1].edge = 35.0f; sceneSettings.spotLights[2].base.base.enabled = true; sceneSettings.spotLights[2].base.base.color = glm::vec3(1.0f, 1.0f, 1.0f); sceneSettings.spotLights[2].base.position = glm::vec3(0.0f, 0.0f, 0.0f); sceneSettings.spotLights[2].direction = glm::vec3(0.0f, -1.0f, 0.0f); sceneSettings.spotLights[2].base.base.ambientIntensity = 1.0f; sceneSettings.spotLights[2].base.base.diffuseIntensity = 1.0f; sceneSettings.spotLights[2].base.constant = 0.4f; sceneSettings.spotLights[2].base.linear = 0.3f; sceneSettings.spotLights[2].base.exponent = 0.2f; sceneSettings.spotLights[2].edge = 35.0f; sceneSettings.spotLights[3].base.base.enabled = true; sceneSettings.spotLights[3].base.base.color = glm::vec3(1.0f, 1.0f, 1.0f); sceneSettings.spotLights[3].base.position = glm::vec3(0.0f, 0.0f, 0.0f); sceneSettings.spotLights[3].direction = glm::vec3(0.0f, -1.0f, 0.0f); sceneSettings.spotLights[3].base.base.ambientIntensity = 1.0f; sceneSettings.spotLights[3].base.base.diffuseIntensity = 1.0f; sceneSettings.spotLights[3].base.constant = 0.4f; sceneSettings.spotLights[3].base.linear = 0.3f; sceneSettings.spotLights[3].base.exponent = 0.2f; sceneSettings.spotLights[3].edge = 35.0f; sceneSettings.shadowMapWidth = 2048; sceneSettings.shadowMapHeight = 2048; sceneSettings.omniShadowMapWidth = 1024; sceneSettings.omniShadowMapHeight = 1024; sceneSettings.shadowSpeed = 0.4f; sceneSettings.waterHeight = 1.6f; sceneSettings.waterWaveSpeed = 0.005f; m_FOV = 60.0f; m_AspectRatio = 16 / 9.0f; shadowMapWidth = 1024; shadowMapHeight = 1024; m_WireframeEnabled = false; // Key cooldown time (emulate onKeyReleased) m_KeyPressCooldown = { 0.0f, 0.2f }; // SetLightManager(); SetupFramebuffers(); SetupTextures(); SetupTextureSlots(); SetupMaterials(); SetupMeshes(); } void Scene::Update(float timestep, Window* mainWindow) { Timer::Get()->Update(); m_Camera->OnUpdate(timestep); m_CameraController->Update(); MousePicker::Get()->Update(m_Camera->GetViewMatrix()); if (ImGuiWrapper::CanViewportReceiveEvents()) { // Toggle wireframe mode if (Input::IsKeyPressed(Key::R)) { if (Timer::Get()->GetCurrentTimestamp() - m_KeyPressCooldown.lastTime > m_KeyPressCooldown.cooldown) { m_WireframeEnabled = !m_WireframeEnabled; m_KeyPressCooldown.lastTime = Timer::Get()->GetCurrentTimestamp(); } } // Flashlight toggle key if (Input::IsKeyPressed(Key::F)) { LightManager::spotLights[2].GetBasePL()->Toggle(); // Application::Get()->GetWindow()->getKeys()[GLFW_KEY_L] = false; } // Take a screenshot if (Input::IsKeyPressed(Key::LeftControl) && Input::IsKeyPressed(Key::P)) { if (Timer::Get()->GetCurrentTimestamp() - m_KeyPressCooldown.lastTime > m_KeyPressCooldown.cooldown) { time_t rawtime; struct tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, sizeof(buffer), "%Y-%m-%d_%H-%M-%S", timeinfo); std::string dateTimeString(buffer); Application::Get()->CaptureScreenshot("Screenshots/" + dateTimeString + ".jpg"); m_KeyPressCooldown.lastTime = Timer::Get()->GetCurrentTimestamp(); } } } if (m_WireframeEnabled) { RendererBasic::EnableWireframe(); } else { RendererBasic::DisableWireframe(); } } void Scene::OnWindowResize(WindowResizeEvent& e) { m_CameraController->OnResize((uint32_t)e.GetWidth(), (uint32_t)e.GetHeight()); m_Camera->SetViewportSize((float)e.GetWidth(), (float)e.GetHeight()); } void Scene::SetupTextureSlots() { textureSlots.insert(std::make_pair("diffuse", 1)); textureSlots.insert(std::make_pair("normal", 2)); textureSlots.insert(std::make_pair("shadow", 3)); textureSlots.insert(std::make_pair("omniShadow", 4)); textureSlots.insert(std::make_pair("reflection", 5)); textureSlots.insert(std::make_pair("refraction", 6)); textureSlots.insert(std::make_pair("depth", 7)); textureSlots.insert(std::make_pair("DuDv", 8)); // PBR textureSlots.insert(std::make_pair("albedo", 1)); textureSlots.insert(std::make_pair("normal", 2)); textureSlots.insert(std::make_pair("metallic", 3)); textureSlots.insert(std::make_pair("roughness", 4)); textureSlots.insert(std::make_pair("ao", 5)); // environment cubemap textureSlots.insert(std::make_pair("equirectangularMap", 6)); textureSlots.insert(std::make_pair("environmentMap", 7)); } void Scene::SetupMaterials() { if (Hazel::RendererAPI::Current() == Hazel::RendererAPIType::OpenGL) { materials.insert(std::make_pair("shiny", new Material(1.0f, 128.0f))); materials.insert(std::make_pair("dull", new Material(1.0f, 64.0f))); materials.insert(std::make_pair("superShiny", new Material(1.0f, 1024.0f))); materials.insert(std::make_pair("superDull", new Material(1.0f, 16.0f))); } } void Scene::SetupMeshes() { } void Scene::SetupParticles() { } void Scene::SetupFramebuffers() { } void Scene::SetupShaders() { } void Scene::SetupModels() { } void Scene::SetSkybox() { } void Scene::SetupTextures() { if (Hazel::RendererAPI::Current() == Hazel::RendererAPIType::OpenGL) { textures.insert(std::make_pair("normalMapDefault", TextureLoader::Get()->GetTexture("Textures/normal_map_default.png", false, false))); textures.insert(std::make_pair("shadowMapDefault", TextureLoader::Get()->GetTexture("Textures/shadow_map_default.png", false, false))); textures.insert(std::make_pair("waterDuDv", TextureLoader::Get()->GetTexture("Textures/water/waterDuDv.png", false, false))); textures.insert(std::make_pair("waterNormal", TextureLoader::Get()->GetTexture("Textures/water/waterNormal.png", false, false))); } } void Scene::SetCamera() { m_Camera = new Camera(sceneSettings.cameraPosition, glm::vec3(0.0f, 1.0f, 0.0f), sceneSettings.cameraStartYaw, sceneSettings.cameraStartPitch); m_CameraController = new CameraController(m_Camera, m_AspectRatio, sceneSettings.cameraMoveSpeed, 0.1f); } void Scene::SetLightManager() { // Skip if Light Manager already initialized if (LightManager::pointLightCount > 0 || LightManager::spotLightCount > 0) return; LightManager::Init(sceneSettings); } void Scene::SetWaterManager(int width, int height) { // Water framebuffers m_WaterManager = new WaterManager(width, height, sceneSettings.waterHeight, sceneSettings.waterWaveSpeed); } // Demonstrate using DockSpace() to create an explicit docking node within an existing window. // Note that you already dock windows into each others _without_ a DockSpace() by just moving windows // from their title bar (or by holding SHIFT if io.ConfigDockingWithShift is set). // DockSpace() is only useful to construct to a central location for your application. void Scene::ShowExampleAppDockSpace(bool* p_open, Window* mainWindow) { static bool opt_fullscreen_persistant = true; bool opt_fullscreen = opt_fullscreen_persistant; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None | ImGuiDockNodeFlags_PassthruCentralNode | ImGuiDockNodeFlags_NoDockingInCentralNode; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() returns false (aka window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", p_open, window_flags); ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } else { ImGuiIO& io = ImGui::GetIO(); ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration."); ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or "); ImGui::SameLine(0.0f, 0.0f); if (ImGui::SmallButton("click here")) io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; } if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Exit")) mainWindow->SetShouldClose(true); ImGui::EndMenu(); } if (ImGui::BeginMenu("Edit")) { ImGui::MenuItem("Undo"); ImGui::MenuItem("Redo"); ImGui::MenuItem("Cut"); ImGui::MenuItem("Copy"); ImGui::MenuItem("Paste"); ImGui::EndMenu(); } if (ImGui::BeginMenu("Docking")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize; if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; ImGui::EndMenu(); } ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted("When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n\n" " > if io.ConfigDockingWithShift==false (default):" "\n" " drag windows from title bar to dock" "\n" " > if io.ConfigDockingWithShift==true:" "\n" " drag windows from anywhere and hold Shift to dock" "\n\n" "This demo app has nothing to do with it!" "\n\n" "This demo app only demonstrate the use of ImGui::DockSpace() which allows you to manually create a docking node _within_ another window. This is useful so you can decorate your main application window (e.g. with a menu bar)." "\n\n" "ImGui::DockSpace() comes with one hard constraint: it needs to be submitted _before_ any window which may be docked into it. Therefore, if you use a dock spot as the central point of your application, you'll probably want it to be part of the very first window you are submitting to imgui every frame." "\n\n" "(NB: because of this constraint, the implicit \"Debug\" window can not be docked into an explicit DockSpace() node, because that window is submitted as part of the NewFrame() call. An easy workaround is that you can create your own implicit \"Debug##2\" window after calling DockSpace() and leave it in the window stack for anyone to use.)"); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } ImGui::EndMenuBar(); } ImGui::End(); } Camera* Scene::GetCamera() { return m_Camera; } Scene::~Scene() { delete m_Skybox; delete m_CameraController; delete m_Camera; delete m_WaterManager; // for (auto& texture : textures) // TextureLoader is now responsible for deallocating // if (texture.second != nullptr) // delete texture.second; TextureLoader::Get()->Clean(); // Objects already deallocated in the Scene destructor // for (auto& mesh : meshes) // { // delete mesh.second; // } for (auto& material : materials) { delete material.second; } for (auto& model : models) { delete model.second; } skyboxFaces.clear(); textures.clear(); textureSlots.clear(); materials.clear(); meshes.clear(); models.clear(); }
38.15678
347
0.728984
[ "mesh", "render", "model" ]
ebfa5ddb1bf6b803f7057ce0e6743bf656646ee7
15,489
cpp
C++
src/nosuch/NosuchUtil.cpp
nosuchtim/MMTT1
83f93c2aa333a7ec3d57c1da7d6c5372718eabe2
[ "MIT" ]
null
null
null
src/nosuch/NosuchUtil.cpp
nosuchtim/MMTT1
83f93c2aa333a7ec3d57c1da7d6c5372718eabe2
[ "MIT" ]
null
null
null
src/nosuch/NosuchUtil.cpp
nosuchtim/MMTT1
83f93c2aa333a7ec3d57c1da7d6c5372718eabe2
[ "MIT" ]
null
null
null
/* Space Manifold - a variety of tools for Kinect and FreeFrame Copyright (c) 2011-2012 Tim Thompson <me@timthompson.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. 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 <winsock.h> #include <stdint.h> #include "NosuchUtil.h" #include "tstring.h" #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <iterator> #include <pthread.h> #include <locale> #include <sstream> #include <string> using namespace std; #define NOSUCHMAXSTRING 8096 #include <time.h> #include <sys/types.h> #include <sys/timeb.h> void NosuchPrintTime(const char *prefix) { struct _timeb tstruct; _ftime( &tstruct ); // C4996 int milli = tstruct.millitm; long secs = (long) tstruct.time; NosuchDebug("%s: time= %ld.%03u\n",prefix,secs,milli); } std::vector<std::string> NosuchSplitOnAnyChar(std::string s, std::string sepchars) { std::vector<std::string> result; const char *seps = sepchars.c_str(); const char *str = s.c_str(); while(1) { const char *begin = str; while( strchr(seps,*str) == NULL && *str) { str++; } result.push_back(std::string(begin, str)); if(0 == *str) { break; } // skip one or more of the sepchars while( strchr(seps,*str) != NULL && *str ) { str++; } } return result; } std::vector<std::string> NosuchSplitOnString(const std::string& s, const std::string& delim, const bool keep_empty = true) { std::vector<std::string> result; if (delim.empty()) { result.push_back(s); return result; } std::string::const_iterator substart = s.begin(), subend; while (true) { subend = search(substart, s.end(), delim.begin(), delim.end()); std::string temp(substart, subend); if (keep_empty || !temp.empty()) { result.push_back(temp); } if (subend == s.end()) { break; } substart = subend + delim.size(); } return result; } static int NosuchNetworkInitialized = 0; int NosuchNetworkInit() { if ( ! NosuchNetworkInitialized ) { int err; WSADATA wsaData; err = WSAStartup(MAKEWORD(1,1),&wsaData); // err = WSAStartup(MAKEWORD(2,0), &wsaData); if ( err ) { NosuchDebug("NosuchNetworkInit failed!? err=%d",err); return 1; } NosuchNetworkInitialized = 1; } return 0; } int SendToUDPServer(std::string host, int serverport, const char *data, int leng) { SOCKET s; struct sockaddr_in sin; int sin_len = sizeof(sin); int i; PHOSTENT phe; const char *serverhost = host.c_str(); phe = gethostbyname(serverhost); if (phe == NULL) { NosuchDebug("SendToNthServer: gethostbyname(host=%s) fails?",serverhost); return 1; } s = socket(PF_INET, SOCK_DGRAM, 0); if ( s < 0 ) { NosuchDebug("SendToNthServer: unable to create socket!?"); return 1; } sin.sin_family = AF_INET; memcpy((struct sockaddr FAR *) &(sin.sin_addr), *(char **)phe->h_addr_list, phe->h_length); sin.sin_port = htons(serverport); i = sendto(s,data,leng,0,(LPSOCKADDR)&sin,sin_len); closesocket(s); return 0; } int SendToSLIPServer(std::string shost, int port, const char *data, int leng) { SOCKET lhSocket; SOCKADDR_IN lSockAddr; int lConnect; int lleng; const char *host = shost.c_str(); lhSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(lhSocket == INVALID_SOCKET) { NosuchDebug("INVALID SOCKET!"); return 1; } memset(&lSockAddr,0, sizeof(SOCKADDR_IN)); lSockAddr.sin_family = AF_INET; lSockAddr.sin_port = htons(port); // inet_addr doesn't work on "localhost" ? if ( strcmp(host,"localhost") == 0 ) { host = "127.0.0.1"; } lSockAddr.sin_addr.s_addr = inet_addr(host); lConnect = connect(lhSocket,(SOCKADDR *)&lSockAddr,sizeof(SOCKADDR_IN)); if(lConnect != 0) { NosuchDebug("connect() failed to %s:%d, err=%d WSAerr=%d",host,port,lConnect,WSAGetLastError()); return 1; } // NosuchDebug("SENDING DATA TO port=%d!!! leng=%d\n",port,leng); char *buff = (char*) malloc(leng*2+2); char *bp = buff; const char *dp = data; *bp++ = (char)SLIP_END; for ( int n=0; n<leng; n++ ) { if ( IS_SLIP_END(*dp) ) { *bp++ = (char)SLIP_ESC; *bp++ = (char)SLIP_END; NosuchDebug("ESCAPING SLIP_END!\n"); } else if ( IS_SLIP_ESC(*dp) ) { *bp++ = (char)SLIP_ESC; *bp++ = (char)SLIP_ESC2; NosuchDebug("ESCAPING SLIP_ESC!\n"); } else { *bp++ = *dp; } dp++; } *bp++ = (char)SLIP_END; int bleng = bp - buff; // NosuchDebug("SENDING data, dataleng=%d buffleng=%d\n",leng,bleng); lleng = send(lhSocket,buff,bleng,0); if(lleng < bleng) { NosuchDebug("Send error, all bytes not sent\n"); } closesocket(lhSocket); return 0; } #if 0 unsigned char * createimageofsize(CvSize sz) { size_t totalPixels = sz.width * sz.height * 3; return (unsigned char *) malloc(totalPixels); } #endif #if 0 int RegisterWithNthServer(char *serverhost, int serverport, char *myhost, int myport) { char buffer[1024]; // NosuchDebug("RegisterWithServer, serverport=%d myport=%d",serverport, myport); osc::OutboundPacketStream p( buffer, sizeof(buffer) ); p << osc::BeginMessage( "/registerclient" ) << "localhost" << myport << osc::EndMessage; return SendToNthServer(serverhost,serverport,p.Data(),(int)p.Size()); } int UnRegisterWithNthServer(char *serverhost, int serverport, char *myhost, int myport) { char buffer[1024]; osc::OutboundPacketStream p( buffer, sizeof(buffer) ); p << osc::BeginMessage( "/unregisterclient" ) << "localhost" << myport << osc::EndMessage; return SendToNthServer(serverhost,serverport,p.Data(),(int)p.Size()); } int OscSocketError(char *s) { int e = WSAGetLastError(); NosuchDebug("NSPlugin socket error: %s e=%d",s,e); return e; } #endif #if 0 CvScalar randomRGB() { float h = (float)((360.0 * rand()) / (float) RAND_MAX) ; return HLStoRGB(h,0.5,1.0); } CvScalar HLStoRGB(float hue, float lum, float sat) { float r; float g; float b; if ( sat == 0 ) { r = g = b = lum * 255; } else { float rm2; if ( lum <= 0.5 ) { rm2 = lum + lum * sat; } else { rm2 = lum + sat - lum * sat; } float rm1 = 2 * lum - rm2; r = ToRGB1(rm1, rm2, hue + 120); g = ToRGB1(rm1, rm2, hue); b = ToRGB1(rm1, rm2, hue - 120); } // NosuchDebug("HLStoRGB hue=%lf rgb=%lf,%lf,%lf",hue,r,g,b); return CV_RGB(r,g,b); } void RGBtoHLS(float r, float g, float b, float* hue, float* lum, float* sat) { float minval = min(r, min(g, b)); float maxval = max(r, max(g, b)); float mdiff = maxval - minval; float msum = maxval + minval; *lum = msum / 510; if ( maxval == minval ) { *sat = 0; *hue = 0; } else { float rnorm = (maxval - r) / mdiff; float gnorm = (maxval - g) / mdiff; float bnorm = (maxval - b) / mdiff; if ( *lum <= .5 ) { *sat = mdiff/msum; } else { *sat = mdiff / (510 - msum); } // self._saturation = (self._luminance <= .5) ? (mdiff/msum) : (mdiff / (510 - msum)); if ( r == maxval ) { *hue = 60 * (6 + bnorm - gnorm); } else if ( g == maxval ) { *hue = 60 * (2 + rnorm - bnorm); } else if ( b == maxval ) { *hue = 60 * (4 + gnorm - rnorm); } while ( *hue > 360.0 ) { *hue -= 360.0; } while ( *hue < 0.0 ) { *hue += 360.0; } } } float ToRGB1(float rm1, float rm2, float rh) { if ( rh > 360 ) { rh -= 360; } else if ( rh < 0 ) { rh += 360; } if ( rh < 60 ) { rm1 = rm1 + (rm2 - rm1) * rh / 60; } else if ( rh < 180 ) { rm1 = rm2; } else if ( rh < 240 ) { rm1 = rm1 + (rm2 - rm1) * (240 - rh) / 60; } return(rm1 * 255); } #endif float angleNormalize(float a) { while ( a < 0.0 ) { a += PI2; } while ( a > PI2 ) { a -= PI2; } return a; } // base64 code below was found at http://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c #include <math.h> #include <stdint.h> #include <stdlib.h> static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static char *decoding_table = NULL; static int mod_table[] = {0, 2, 1}; char *base64_encode(const uint8_t *data, size_t input_length) { size_t output_length = (size_t) (4.0 * ceil((double) input_length / 3.0)); char *encoded_data = (char*) malloc(output_length+1); if (encoded_data == NULL) return NULL; for (size_t i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? data[i++] : 0; uint32_t octet_b = i < input_length ? data[i++] : 0; uint32_t octet_c = i < input_length ? data[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++) encoded_data[output_length - 1 - i] = '='; encoded_data[output_length] = '\0'; return encoded_data; } void build_decoding_table() { decoding_table = (char *) malloc(256); for (int i = 0; i < 0x40; i++) decoding_table[encoding_table[i]] = i; } char *base64_decode(const char *data, size_t input_length, size_t *output_length) { if (decoding_table == NULL) build_decoding_table(); if (input_length % 4 != 0) return NULL; *output_length = input_length / 4 * 3; if (data[input_length - 1] == '=') (*output_length)--; if (data[input_length - 2] == '=') (*output_length)--; char *decoded_data = (char *) malloc(*output_length); if (decoded_data == NULL) return NULL; for (size_t i = 0, j = 0; i < input_length;) { uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } return decoded_data; } void base64_cleanup() { free(decoding_table); } std::string error_json(int code, const char *msg, const char *id) { return NosuchSnprintf( "{\"jsonrpc\": \"2.0\", \"error\": {\"code\": %d, \"message\": \"%s\"}, \"id\": \"%s\"}",code,msg,id); } std::string ok_json(const char *id) { return NosuchSnprintf( "{\"jsonrpc\": \"2.0\", \"result\": 0, \"id\": \"%s\"}",id); } std::string NosuchToLower(std::string s) { // This could probably be a lot more efficient std::string r = s; for(size_t i=0; i<s.size(); i++) { r[i] = tolower(s[i]); } return r; } void NosuchLockInit(pthread_mutex_t* mutex, char *tag) { *mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER; // *mutex = PTHREAD_MUTEX_INITIALIZER; // NosuchDebug("NosuchLockInit pthread=%d tag=%s mutex=%d",(int)pthread_self().p,tag,(int)mutex); } void NosuchLock(pthread_mutex_t* mutex, char *tag) { // NosuchDebug("NosuchLock pthread=%d tag=%s mutex=%d",(int)pthread_self().p,tag,(int)mutex); int r = pthread_mutex_lock(mutex); if ( r == EDEADLK ) { NosuchErrorOutput("Hey! NosuchLock detects DEADLOCK!! tag=%s",tag); } else if ( r != 0 ) { NosuchErrorOutput("Hey! pthread_mutex_lock tag=%s returned non-zero! r=%d",tag,r); } } void NosuchUnlock(pthread_mutex_t* mutex, char *tag) { // NosuchDebug("NosuchUnlock pthread=%d tag=%s mutex=%d",(int)pthread_self().p,tag,(int)mutex); int r = pthread_mutex_unlock(mutex); if ( r != 0 ) { NosuchErrorOutput("Hey! pthread_mutex_unlock tag=%s returned non-zero! r=%d",tag,r); } } int NosuchTryLock(pthread_mutex_t* mutex, char *tag) { // NosuchDebug("NosuchTryLock pthread=%d tag=%s mutex=%d",(int)pthread_self().p,tag,(int)mutex); return pthread_mutex_trylock(mutex); } std::string ToNarrow( const wchar_t *s, char dfault, const std::locale& loc ) { std::ostringstream stm; while( *s != L'\0' ) { stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault ); } return stm.str(); } std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); std::wstring r(len, L'\0'); MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, &r[0], len); return r; } std::string ws2s(const std::wstring& s) { int len; int slength = (int)s.length() + 1; // First figure out the length of the result, to allocate enough space len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0); char* r = new char[len]; // includes the null character WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, r, len, 0, 0); std::string rs = std::string(r); delete r; return rs; }
28.951402
124
0.58138
[ "vector" ]
230947407d1f0c34b610eac641e32ee1019d26da
11,155
cc
C++
src/PluginLoader.cc
vatanaksoytezer/ign-common
d73921557ce8e0747daa878e42070a43344557ec
[ "ECL-2.0", "Apache-2.0" ]
10
2020-04-15T16:58:39.000Z
2021-09-13T01:50:07.000Z
src/PluginLoader.cc
vatanaksoytezer/ign-common
d73921557ce8e0747daa878e42070a43344557ec
[ "ECL-2.0", "Apache-2.0" ]
255
2020-04-17T22:25:00.000Z
2022-03-31T23:58:50.000Z
src/PluginLoader.cc
vatanaksoytezer/ign-common
d73921557ce8e0747daa878e42070a43344557ec
[ "ECL-2.0", "Apache-2.0" ]
19
2020-05-21T09:01:59.000Z
2021-11-29T20:24:04.000Z
/* * Copyright (C) 2017 Open Source Robotics Foundation * * 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 <dlfcn.h> #include <algorithm> #include <functional> #include <locale> #include <sstream> #include <unordered_map> #include "ignition/common/Console.hh" #include "ignition/common/PluginInfo.hh" #include "ignition/common/PluginLoader.hh" #include "ignition/common/PluginPtr.hh" #include "ignition/common/StringUtils.hh" #include "ignition/common/Util.hh" #include "PluginUtils.hh" namespace ignition { namespace common { ///////////////////////////////////////////////// /// \brief PIMPL Implementation of the PluginLoader class class PluginLoaderPrivate { /// \brief Attempt to load a library at the given path. /// \param[in] _pathToLibrary The full path to the desired library /// \return If a library exists at the given path, get a point to its dl /// handle. If the library does not exist, get a nullptr. public: void *LoadLibrary(const std::string &_pathToLibrary) const; /// \brief Using a dl handle produced by LoadLibrary, extract the /// PluginInfo from the loaded library. /// \param[in] _dlHandle A handle produced by LoadLibrary /// \param[in] _pathToLibrary The path that the library was loaded from /// (used for debug purposes) /// \return All the PluginInfo provided by the loaded library. public: std::vector<PluginInfo> LoadPlugins( void *_dlHandle, const std::string &_pathToLibrary) const; public: using PluginMap = std::unordered_map<std::string, PluginInfo>; /// \brief A map from known plugin names to their PluginInfo public: PluginMap plugins; }; ///////////////////////////////////////////////// std::string PluginLoader::PrettyStr() const { auto interfaces = this->InterfacesImplemented(); std::stringstream pretty; pretty << "PluginLoader State" << std::endl; pretty << "\tKnown Interfaces: " << interfaces.size() << std::endl; for (auto const &interface : interfaces) pretty << "\t\t" << interface << std::endl; pretty << "\tKnown Plugins: " << dataPtr->plugins.size() << std::endl; for (const auto &pair : dataPtr->plugins) { const PluginInfo &plugin = pair.second; const size_t iSize = plugin.interfaces.size(); pretty << "\t\t[" << plugin.name << "] which implements " << iSize << PluralCast(" interface", iSize) << ":\n"; for (const auto &interface : plugin.interfaces) pretty << "\t\t\t" << interface.first << "\n"; } pretty << std::endl; return pretty.str(); } ///////////////////////////////////////////////// PluginLoader::PluginLoader() : dataPtr(new PluginLoaderPrivate()) { // Do nothing. } ///////////////////////////////////////////////// PluginLoader::~PluginLoader() { // Do nothing. } ///////////////////////////////////////////////// std::unordered_set<std::string> PluginLoader::LoadLibrary( const std::string &_pathToLibrary) { std::unordered_set<std::string> newPlugins; if (!exists(_pathToLibrary)) { ignerr << "Library [" << _pathToLibrary << "] does not exist!\n"; return newPlugins; } // Attempt to load the library at this path void *dlHandle = this->dataPtr->LoadLibrary(_pathToLibrary); if (nullptr != dlHandle) { // Found a shared library, does it have the symbols we're looking for? std::vector<PluginInfo> loadedPlugins = this->dataPtr->LoadPlugins( dlHandle, _pathToLibrary); for (PluginInfo &plugin : loadedPlugins) { if (plugin.name.empty()) continue; plugin.name = NormalizeName(plugin.name); PluginInfo::InterfaceCastingMap normalizedMap; normalizedMap.reserve(plugin.interfaces.size()); for (const auto &interface : plugin.interfaces) { normalizedMap.insert(std::make_pair( NormalizeName(interface.first), interface.second)); } plugin.interfaces = normalizedMap; this->dataPtr->plugins.insert(std::make_pair(plugin.name, plugin)); newPlugins.insert(plugin.name); } if (loadedPlugins.empty()) { ignerr << "Failed to load plugins from library [" << _pathToLibrary << "].\n"; } } else { ignerr << "Library[" << _pathToLibrary << "] error: " << dlerror() << std::endl; } return newPlugins; } ///////////////////////////////////////////////// std::unordered_set<std::string> PluginLoader::InterfacesImplemented() const { std::unordered_set<std::string> interfaces; for (auto const &plugin : this->dataPtr->plugins) { for (auto const &interface : plugin.second.interfaces) interfaces.insert(interface.first); } return interfaces; } ///////////////////////////////////////////////// std::unordered_set<std::string> PluginLoader::PluginsImplementing( const std::string &_interface) const { const std::string interface = NormalizeName(_interface); std::unordered_set<std::string> plugins; for (auto const &plugin : this->dataPtr->plugins) { if (plugin.second.interfaces.find(interface) != plugin.second.interfaces.end()) plugins.insert(plugin.second.name); } return plugins; } ///////////////////////////////////////////////// PluginPtr PluginLoader::Instantiate( const std::string &_plugin) const { return PluginPtr(this->PrivateGetPluginInfo(_plugin)); } ///////////////////////////////////////////////// const PluginInfo *PluginLoader::PrivateGetPluginInfo( const std::string &_pluginName) const { const std::string plugin = NormalizeName(_pluginName); PluginLoaderPrivate::PluginMap::const_iterator it = this->dataPtr->plugins.find(plugin); if (this->dataPtr->plugins.end() == it) { ignerr << "Failed to get info for plugin [" << plugin << "] since it has not been loaded." << std::endl; return nullptr; } return &(it->second); } ///////////////////////////////////////////////// void* PluginLoaderPrivate::LoadLibrary(const std::string &_full_path) const { // Somehow this works on windows builds? return dlopen(_full_path.c_str(), RTLD_LAZY|RTLD_GLOBAL); // TODO(MXG): Consider checking for errors here using dlerror() } ///////////////////////////////////////////////// std::vector<PluginInfo> PluginLoaderPrivate::LoadPlugins( void *_dlHandle, const std::string &_pathToLibrary) const { std::vector<PluginInfo> loadedPlugins; if (nullptr == _dlHandle) { ignerr << "Passed NULL handle.\n"; return loadedPlugins; } const std::string versionSymbol = "IGNCOMMONPluginAPIVersion"; const std::string sizeSymbol = "IGNCOMMONPluginInfoSize"; const std::string alignSymbol = "IGNCOMMONPluginInfoAlignment"; const std::string multiInfoSymbol = "IGNCOMMONMultiPluginInfo"; void *versionPtr = dlsym(_dlHandle, versionSymbol.c_str()); void *sizePtr = dlsym(_dlHandle, sizeSymbol.c_str()); void *alignPtr = dlsym(_dlHandle, alignSymbol.c_str()); void *multiInfoPtr = dlsym(_dlHandle, multiInfoSymbol.c_str()); // Does the library have the right symbols? if (nullptr == versionPtr || nullptr == sizePtr || nullptr == multiInfoPtr || nullptr == alignPtr) { ignerr << "Library [" << _pathToLibrary << "] doesn't have the right symbols:" << "\n -- version symbol -- " << versionPtr << "\n -- size symbol -- " << sizePtr << "\n -- alignment symbol -- " << alignPtr << "\n -- info symbol -- " << multiInfoPtr << "\n"; return loadedPlugins; } // Check abi version, and also check size because bugs happen int version = *(static_cast<int*>(versionPtr)); const std::size_t size = *(static_cast<std::size_t*>(sizePtr)); const std::size_t alignment = *(static_cast<std::size_t*>(alignPtr)); if (version < PLUGIN_API_VERSION) { ignwarn << "The library [" << _pathToLibrary <<"] is using an outdated " << "version [" << version << "] of the ignition::common Plugin " << "API. The version in this library is [" << PLUGIN_API_VERSION << "].\n"; } if (version > PLUGIN_API_VERSION) { ignerr << "The library [" << _pathToLibrary << "] is using a newer " << "version [" << version << "] of the ignition::common Plugin " << "API. The version in this library is [" << PLUGIN_API_VERSION << "].\n"; return loadedPlugins; } if (sizeof(PluginInfo) == size && alignof(PluginInfo) == alignment) { using PluginLoadFunctionSignature = std::size_t(*)(void * * const, const std::size_t, const std::size_t); // Info here is a function which matches the function signature defined // by PluginLoadFunctionSignature. Info(~) will be used to extract the // information about each plugin from the loaded library. auto Info = reinterpret_cast<PluginLoadFunctionSignature>(multiInfoPtr); PluginInfo * ptrToPlugin = nullptr; void ** vPlugin = reinterpret_cast<void **>(&ptrToPlugin); size_t id = 0; while (Info(vPlugin, id, sizeof(PluginInfo)) > 0) { loadedPlugins.push_back(*ptrToPlugin); ++id; } } else { const size_t expectedSize = sizeof(PluginInfo); const size_t expectedAlignment = alignof(PluginInfo); ignerr << "The library [" << _pathToLibrary << "] has the wrong plugin " << "size or alignment for API version [" << PLUGIN_API_VERSION << "]. Expected size [" << expectedSize << "], got [" << size << "]. Expected alignment [" << expectedAlignment << "], got [" << alignment << "].\n"; return loadedPlugins; } return loadedPlugins; } } }
35.078616
80
0.571582
[ "vector" ]
230ee0fe3ccdc8738fb08d54c31dcfa6ddcfa853
8,062
hpp
C++
include/teresa_wsbs/common.hpp
robotics-upo/teresa-wsbs
6cafdc508bfbd1f2984753408b466d46aded4473
[ "BSD-3-Clause" ]
1
2020-04-16T01:20:10.000Z
2020-04-16T01:20:10.000Z
include/teresa_wsbs/common.hpp
robotics-upo/teresa-wsbs
6cafdc508bfbd1f2984753408b466d46aded4473
[ "BSD-3-Clause" ]
2
2020-04-16T01:20:02.000Z
2021-03-18T15:08:14.000Z
include/teresa_wsbs/common.hpp
robotics-upo/teresa-wsbs
6cafdc508bfbd1f2984753408b466d46aded4473
[ "BSD-3-Clause" ]
2
2019-11-21T13:30:12.000Z
2021-02-15T10:21:58.000Z
#ifndef _COMMON_HPP_ #define _COMMON_HPP_ #include <tinyxml.h> #include <tf/transform_listener.h> #include <lightsfm/vector2d.hpp> #include <lightsfm/astar.hpp> #include <lightsfm/sfm.hpp> namespace wsbs { class TfListener { public: TfListener(TfListener const&) = delete; void operator=(TfListener const&) = delete; ~TfListener() {} static TfListener& getInstance() { static TfListener singleton; return singleton; } #define TF TfListener::getInstance() bool transformPose(double& x, double& y, double& theta, const std::string& sourceFrameId, const std::string& targetFrameId) const { tf::Stamped<tf::Pose> pose,tfPose; pose.setData(tf::Pose(tf::createQuaternionFromRPY(0,0,theta), tf::Vector3(x,y,0))); pose.frame_id_ = sourceFrameId; pose.stamp_ = ros::Time(0); try { tf_listener.transformPose(targetFrameId, pose, tfPose); } catch(std::exception &e) { ROS_ERROR("%s",e.what()); return false; } x = tfPose.getOrigin().getX(); y = tfPose.getOrigin().getY(); tf::Matrix3x3 m(tfPose.getRotation()); double roll,pitch; m.getRPY(roll, pitch, theta); return true; } bool transformPoint(double& x, double& y, const std::string& sourceFrameId, const std::string& targetFrameId) const { tf::Stamped<tf::Pose> pose,tfPose; pose.setData(tf::Pose(tf::createQuaternionFromRPY(0,0,0), tf::Vector3(x,y,0))); pose.frame_id_ = sourceFrameId; pose.stamp_ = ros::Time(0); try { tf_listener.transformPose(targetFrameId, pose, tfPose); } catch(std::exception &e) { ROS_ERROR("%s",e.what()); return false; } x = tfPose.getOrigin().getX(); y = tfPose.getOrigin().getY(); return true; } bool transformPoint(utils::Vector2d& point, const std::string& sourceFrameId, const std::string& targetFrameId) const { double x = point.getX(); double y = point.getY(); if (transformPoint(x,y,sourceFrameId,targetFrameId)) { point.set(x,y); return true; } return false; } private: TfListener() {} tf::TransformListener tf_listener; }; // Controller Mode enum ControllerMode { HEURISTIC = 0, LEFT = 1, RIGHT = 2, BEHIND = 3, FOLLOW_PATH = 4, WAIT = 5, SET_GOAL = 6, SET_FINAL_GOAL = 7 }; class PathProvider { public: PathProvider() {} virtual ~PathProvider() {} const std::vector<utils::Vector2d>& getGoals() const {return goals;} virtual utils::Vector2d& getNextPoint(const utils::Vector2d& position, const utils::Vector2d& goal, utils::Vector2d& nextPoint) = 0; protected: std::vector<utils::Vector2d> goals; }; class AStarPathProvider : public PathProvider { public: AStarPathProvider(const std::string& file) : aStar(file) { double x,y,r; for (unsigned i=0; i< aStar.getGoals().size();i++) { aStar.getPos(aStar.getGoals()[i], x, y, r); goals.emplace_back(x,y); } } virtual ~AStarPathProvider() {} virtual utils::Vector2d& getNextPoint(const utils::Vector2d& position, const utils::Vector2d& goal, utils::Vector2d& nextPoint) { std::string start_id,goal_id; aStar.getClosestNode(position.getX(),position.getY(),start_id); aStar.getClosestNode(goal.getX(),goal.getY(),goal_id); std::list<std::string> path; aStar.getPath(start_id,goal_id,path); if (path.size()<2) { nextPoint = goal; return nextPoint; } double x,y,r; auto it = path.begin(); ++it; aStar.getPos(*it,x,y,r); nextPoint.set(x,y); return nextPoint; } utils::AStar& getAStar() {return aStar;} private: utils::AStar aStar; }; class GoalProvider { public: GoalProvider(double threshold, unsigned size, double lookahead, double naiveGoalTime, double wsbsDistance, const std::string& frame, PathProvider& pathProvider, bool allowHistory=true); ~GoalProvider() {} void update(const utils::Vector2d& robotPos, const utils::Vector2d& targetPos, const utils::Vector2d& targetVel, const utils::Vector2d& targetGlobalGoal); void update(const utils::Vector2d& robotPos, const utils::Vector2d& targetPos, const utils::Vector2d& targetVel); void update(const utils::Vector2d& robotPos); const utils::Vector2d& getRobotLocalGoal(const ControllerMode& mode) const; const std::vector<utils::Vector2d>& getGoals() const {return pathProvider.getGoals();} PathProvider& getPathProvider() {return pathProvider;} const std::list<utils::Vector2d>& getHistory() const {return history;} private: double threshold; unsigned size; double lookahead; double naiveGoalTime; double wsbsDistance; std::string frame; PathProvider& pathProvider; bool allowHistory; utils::Vector2d rightGoal; utils::Vector2d leftGoal; utils::Vector2d behindGoal; utils::Vector2d followGoal; utils::Vector2d waitGoal; utils::Vector2d heuristicGoal; utils::Vector2d targetNaiveGoal; utils::Vector2d robotPos; utils::Vector2d targetGlobalGoal; utils::Vector2d robotLocalGoal; std::list<utils::Vector2d> history; }; GoalProvider::GoalProvider(double threshold, unsigned size, double lookahead, double naiveGoalTime, double wsbsDistance, const std::string& frame, PathProvider& pathProvider, bool allowHistory) : threshold(threshold), size(size), lookahead(lookahead), naiveGoalTime(naiveGoalTime), wsbsDistance(wsbsDistance), frame(frame), pathProvider(pathProvider), allowHistory(allowHistory) { } inline void GoalProvider::update(const utils::Vector2d& robotPos) { leftGoal = robotPos; rightGoal = robotPos; behindGoal = robotPos; waitGoal = robotPos; followGoal = robotPos; GoalProvider::robotPos = robotPos; if (allowHistory) { for (auto it = history.begin(); it!= history.end(); ++it) { if ((robotPos - *it).norm() <= lookahead) { followGoal = *it; history.erase(++it,history.end()); break; } } heuristicGoal = followGoal; } else { heuristicGoal = robotPos; } } inline void GoalProvider::update(const utils::Vector2d& robotPos, const utils::Vector2d& targetPos, const utils::Vector2d& targetVel) { if (targetVel.norm()>0.05) { targetNaiveGoal = targetPos + naiveGoalTime * targetVel; leftGoal = targetNaiveGoal + wsbsDistance*targetVel.normalized().leftNormalVector(); rightGoal = targetNaiveGoal + wsbsDistance*targetVel.normalized().rightNormalVector(); behindGoal = targetNaiveGoal - wsbsDistance*targetVel.normalized(); } waitGoal = robotPos; GoalProvider::robotPos = robotPos; if (allowHistory && (history.empty() || (targetPos - history.front()).norm() > threshold)) { history.push_front(targetPos); if (history.size()>size) { auto it = history.rbegin(); ++it; if ((robotPos - *it).norm() <= lookahead) { history.pop_back(); } else { history.pop_front(); } } } followGoal = waitGoal; for (auto it = history.begin(); it!= history.end(); ++it) { if ((robotPos - *it).norm() <= lookahead) { followGoal = *it; history.erase(++it,history.end()); break; } } if ((robotPos - targetPos).norm() <= lookahead) { if ((rightGoal - robotPos).squaredNorm() < (leftGoal - robotPos).squaredNorm()) { heuristicGoal = rightGoal; } else { heuristicGoal = leftGoal; } } else { heuristicGoal = followGoal; } } void GoalProvider::update(const utils::Vector2d& robotPos, const utils::Vector2d& targetPos, const utils::Vector2d& targetVel, const utils::Vector2d& targetGlobalGoal) { update(robotPos,targetPos,targetVel); GoalProvider::targetGlobalGoal = targetGlobalGoal; utils::Vector2d pos = robotPos; if (TF.transformPoint(pos,frame,"map")) { utils::Vector2d next; pathProvider.getNextPoint(pos,targetGlobalGoal,next); if (TF.transformPoint(next,"map",frame)) { robotLocalGoal = next; } } } inline const utils::Vector2d& GoalProvider::getRobotLocalGoal(const ControllerMode& mode) const { switch(mode) { case HEURISTIC: return heuristicGoal; case LEFT: return leftGoal; case RIGHT: return rightGoal; case BEHIND: return behindGoal; case FOLLOW_PATH: return followGoal; case WAIT: return waitGoal; case SET_GOAL: return robotLocalGoal; case SET_FINAL_GOAL: return targetGlobalGoal; } return waitGoal; } } #endif
24.806154
193
0.7064
[ "vector" ]
2317a5f46e59b3d33226d7fb7559567a1ab9e5fc
1,040
cpp
C++
AtCoder/ABC/ABC-087/SolveD.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
AtCoder/ABC/ABC-087/SolveD.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
AtCoder/ABC/ABC-087/SolveD.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long int; const int MAX = (int)(1e5 + 5); const ll INF = (ll)(1e10 + 5); const int MAX_N = (int)(1e5 + 5); int n, m; vector<vector<pair<int, ll>>> graph(MAX_N); ll pos[MAX_N]; bool visited[MAX_N]; bool check(int node, ll suppose) { if (visited[node]) { return pos[node] == suppose; } pos[node] = suppose; visited[node] = true; for (auto &e : graph[node]) { if (!check(e.first, pos[node] + e.second)) { return false; } } return true; } int main(void) { // Here your code ! scanf("%d %d", &n, &m); for (int i = 0; i < m; ++i) { int l, r; ll d; scanf("%d %d %lld", &l, &r, &d); graph[l].push_back(make_pair(r, d)); graph[r].push_back(make_pair(l, -d)); } for (int i = 1; i <= n; ++i) { visited[i] = false; } for (int i = 1; i <= n; ++i) { if (visited[i] || graph[i].empty()) continue; if (!check(i, 0LL)) { printf("No\n"); return 0; } } printf("Yes\n"); return 0; }
16.774194
49
0.523077
[ "vector" ]
231f60dcac0b3821e074377ef5f6731269c0e170
348
cpp
C++
test/Geometric_is_convex.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
test/Geometric_is_convex.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
6
2021-01-05T07:39:05.000Z
2021-01-05T07:44:31.000Z
test/Geometric_is_convex.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/all/CGL_3_B" #include "./../Geometry/Polygon.hpp" #include "./../Geometry/Geometric.cpp" #include <iostream> using namespace std; int main() { int n; cin >> n; vector<Geometric::Vec2> p(n); for (auto& i : p) cin >> i; cout << Geometric::Polygon(p).is_convex() << endl; }
26.769231
84
0.66954
[ "geometry", "vector" ]
23245a5aa436bb4fbeb3d5f0847007635a18bf3e
2,854
cpp
C++
src/mpi/interface/c/matrix/vector_comm.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
src/mpi/interface/c/matrix/vector_comm.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
src/mpi/interface/c/matrix/vector_comm.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
#include <tbsla/cpp/Vector.h> #include <tbsla/cpp/utils/range.hpp> #include <tbsla/mpi/vector_comm.h> #include <vector> #include <iostream> C_CPP_Vector_t *C_MPI_allgatherv(MPI_Comm comm, C_CPP_Vector_t *v, int bn_row, int lgr) { std::cout << "bnrow: " << bn_row << "; lgr: " << lgr << std::endl; C_CPP_Vector_t *r = C_CPP_Vector_create(); if (v == NULL) return r; std::vector<double> *v_obj; v_obj = static_cast<std::vector<double> *>(v->obj); std::vector<int> recvcounts(lgr); std::vector<int> displs(lgr, 0); for(int i = 0; i < lgr; i++) { recvcounts[i] = tbsla::utils::range::lnv(bn_row, i, lgr); } for(int i = 1; i < lgr; i++) { displs[i] = displs[i - 1] + recvcounts[i - 1]; } std::vector<double> recv(bn_row); MPI_Allgatherv(v_obj->data(), v_obj->size(), MPI_DOUBLE, recv.data(), recvcounts.data(), displs.data(), MPI_DOUBLE, comm); C_CPP_Vector_copy(r, &recv); return r; } C_CPP_Vector_t *C_MPI_reduce_sum(MPI_Comm comm, C_CPP_Vector_t *v, int n) { C_CPP_Vector_t *r = C_CPP_Vector_create(); if (v == NULL) return r; std::vector<double> *v_obj; v_obj = static_cast<std::vector<double> *>(v->obj); std::vector<double> r_obj(n); MPI_Allreduce(v_obj->data(), r_obj.data(), v_obj->size(), MPI_DOUBLE, MPI_SUM, comm); C_CPP_Vector_copy(r, &r_obj); return r; } C_CPP_Vector_t *C_MPI_reduce_gather(MPI_Comm comm, C_CPP_Vector_t *v, int bn_row, int bn_col, int lpr, int lpc, int lgr, int lgc) { C_CPP_Vector_t *r = C_CPP_Vector_create(); if (v == NULL) return r; std::vector<double> *v_obj; v_obj = static_cast<std::vector<double> *>(v->obj); MPI_Comm row_comm; MPI_Comm_split(comm, lpr, lpc, &row_comm); std::vector<double> recv(v_obj->size()); MPI_Allreduce(v_obj->data(), recv.data(), v_obj->size(), MPI_DOUBLE, MPI_SUM, row_comm); std::vector<int> recvcounts(lgr); std::vector<int> displs(lgr, 0); for(int i = 0; i < lgr; i++) { recvcounts[i] = tbsla::utils::range::lnv(bn_row, i, lgr); } for(int i = 1; i < lgr; i++) { displs[i] = displs[i - 1] + recvcounts[i - 1]; } std::vector<double> recv2(bn_row); MPI_Comm col_comm; MPI_Comm_split(comm, lpc, lpr, &col_comm); MPI_Allgatherv(recv.data(), recv.size(), MPI_DOUBLE, recv2.data(), recvcounts.data(), displs.data(), MPI_DOUBLE, col_comm); MPI_Comm_free(&col_comm); MPI_Comm_free(&row_comm); C_CPP_Vector_copy(r, &recv2); return r; } C_CPP_Vector_t *C_MPI_redistribute(MPI_Comm comm, C_CPP_Vector_t *v, int bn_row, int bn_col, int lpr, int lpc, int lgr, int lgc) { if(lgc == 1 && lgr == 1) { return v; } else if(lgc == 1 && lgr > 1) { return C_MPI_allgatherv(comm, v, bn_row, lgr); } else if(lgc > 1 && lgr == 1) { return C_MPI_reduce_sum(comm, v, bn_row); } else { return C_MPI_reduce_gather(comm, v, bn_row, bn_col, lpr, lpc, lgr, lgc); } }
32.431818
131
0.652418
[ "vector" ]
2324d5b47df90cc568694679087a731d7df68c26
29,679
cpp
C++
src/gui/p4api/P4Command.cpp
jtilander/niftyp4win
457e2973e3b5c109d76138c5032c486f18276910
[ "BSD-2-Clause" ]
3
2016-09-09T01:57:01.000Z
2021-05-14T22:38:32.000Z
src/gui/p4api/P4Command.cpp
jtilander/niftyp4win
457e2973e3b5c109d76138c5032c486f18276910
[ "BSD-2-Clause" ]
null
null
null
src/gui/p4api/P4Command.cpp
jtilander/niftyp4win
457e2973e3b5c109d76138c5032c486f18276910
[ "BSD-2-Clause" ]
null
null
null
// // Copyright 1997 Nicholas J. Irias. All rights reserved. // // // Class CP4Command - an async wrapper for P4 commands #include "stdafx.h" #define TRACE_HERE #include "P4Win.h" #include "p4command.h" #include "getpwddlg.h" #include "mainfrm.h" #include "GuiClientUser.h" #include "Cmd_Login.h" #include "md5.h" #include <process.h> const CString g_fPassword = _T("-P "); #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // MultiProcessorSleep reg setting: 0==off; ODD == GUI sleep; > EVEN == worker sleep static int m_MultiProcessorSleep = 0; // Prototype for taskthread // UINT TaskThread( LPVOID pParam ); int P4KeepAlive::IsAlive() { if (global_cancel) { global_cancel = 0; return 0; } else return 1; } IMPLEMENT_DYNCREATE(CP4Command, CObject) CP4Command::CP4Command(CGuiClient *client /* =NULL */) : m_pClient(client) { m_pStrListIn= NULL; m_UsedTagged=FALSE; m_RanInit=FALSE; m_ClosedConn=TRUE; m_PWD_DlgCancelled=FALSE; m_ServerKey=0; m_HaveServerLock = FALSE; m_HitMaxFileSeeks= FALSE; m_RedoOpenedFilter=FALSE; m_FatalError = m_FatalErrorCleared = m_TriggerError = m_IgnorePermissionErrs = FALSE; if(m_pClient != NULL) { m_IsChildTask=TRUE; } else { // There is no longer any need to call enviro.Reload(); enviro is no longer a global variable m_IsChildTask=FALSE; m_pClient = new CGuiClient(); ASSERT ( m_pClient ); } // set the array to grow by MAX_P4ARGS, but don't actually set size m_args.SetSize(0, MAX_P4ARGS); m_argsA.SetSize(0, MAX_P4ARGS); m_TaskName=_T("Command base class"); m_Function=_T("Function unassigned"); m_pTaskThread = NULL; m_ReplyWnd=NULL; m_MultiProcessorSleep = GET_P4REGPTR()->GetMultiProcessorSleep(); if (m_MultiProcessorSleep & 0x01) m_MultiProcessorSleep = 0 - m_MultiProcessorSleep; } CP4Command::~CP4Command() { Error e; CloseConn(&e); // delete ANSI arg strings for(int i = 0; i < m_argsA.GetSize(); i++) delete m_argsA.GetAt(i); // Make sure the caption bar gets updated if the user // changed a setting if( m_Asynchronous ) { // can't use MainFrame()-> construct // because mainfram might have closed. CMainFrame * mainWnd = MainFrame(); if (mainWnd) mainWnd->UpdateCaption(!(m_FatalError || m_FatalErrorCleared)); } } void CP4Command::CloseConn(Error *e) { if(!m_ClosedConn) { // we're through with the clientuser, let it point back to parent command, if any m_pClient->PopCommandPtr(this); if(!m_IsChildTask) { if( m_RanInit ) { try { m_pClient->Final(e); if (e->Test()) { CString msg= FormatError(e); if (e->IsFatal()) { if (msg.Find(_T("TCP receive interrupted by client")) != -1) { m_FatalError = TRUE; msg = LoadStringResource(IDS_INTERRUPTEDBYCLIENT); } TheApp()->StatusAdd(msg, SV_ERROR); } XTRACE(msg); } } catch(...) { // Probably called Final for a client // that never was connected ASSERT(0); } } delete m_pClient; m_pClient = 0; } m_ClosedConn=TRUE; } else if (!m_IsChildTask && m_pClient) delete m_pClient; XTRACE(_T("Task %s Connection Closed\n"), GetTaskName( )); } BOOL CP4Command::Init(HWND replyWnd, BOOL asynch, BOOL holdLock/*=FALSE*/, int key/*=0*/) { // We need a reply window ASSERT( m_pClient != NULL || IsWindow(replyWnd) ); m_ReplyWnd= replyWnd; m_Asynchronous= asynch; if( key != 0 ) { m_ServerKey= key; m_HaveServerLock= TRUE; } m_HoldServerLock=holdLock; XTRACE(_T("Task %s Initialized\n"), GetTaskName( )); return TRUE; } BOOL CP4Command::Run() { if(!m_IsChildTask) { // In general, no command can start unless SERVER_BUSY() is false // or the command carries the key in m_pSingleLock. The exception is: // // IsQueueable() and we are are running with m_Asynchronous // This means the command is capable of carrying all relevant context // information and can afford to sit in a queue after a task thread // is spawned. if( !m_HaveServerLock && SERVER_BUSY() ) { if( !( IsQueueable() && m_Asynchronous ) ) { XTRACE(_T("Run() bailing out: %s\n"), m_TaskName); return FALSE; } } } if(m_Asynchronous) { ASSERT(!m_IsChildTask); if( !IsQueueable() && SERVER_BUSY() && !m_HaveServerLock ) { ASSERT(0); CString bloodInUrine; bloodInUrine.FormatMessage( IDS_P4WIN_UNRECOVERABLE_ERROR__COMMAND_IS_s, m_TaskName); AfxMessageBox( bloodInUrine, MB_ICONSTOP ); // this is not excessive, since we will likely GPF if we try // to continue, and we'll never know why we gpf'd ExitProcess(1); } if( m_HaveServerLock ) AsyncExecCommand(); else { XTRACE(_T("Queuing Task: %s\n"), GetTaskName( )); QUEUE_COMMAND(this); } } else { // Dont try to lock the server. If its the primary thread, // we wont be starting any other commands. If we are a // child command under another async command, it already // took out a lock XTRACE(_T("Task %s Running Synchronous\n"), GetTaskName( )); ExecCommand(); XTRACE(_T("Task %s Completed Synchronous\n"), GetTaskName( )); } return TRUE; } //////////////////////////////////////////////////////// // P4 argument collection int CP4Command::AddArg( LPCTSTR arg ) { ASSERT(arg != NULL); ASSERT( m_args.GetSize() < MAX_P4ARGS ); m_args.Add(arg); return m_args.GetSize(); } int CP4Command::AddArg( int arg ) { ASSERT( m_args.GetSize() < MAX_P4ARGS ); CString sArg; sArg.Format(_T("%d"),arg); m_args.Add(sArg); return m_args.GetSize(); } void CP4Command::ClearArgs( int baseArgs) { if(m_args.GetSize() > baseArgs) m_args.RemoveAt(baseArgs, m_args.GetSize() - baseArgs); } BOOL CP4Command::NextListArgs() { ClearArgs(m_BaseArgs); // Clear all but the base args ASSERT(m_posStrListIn != NULL); // Pull another 10 files off the list for(int i=0; m_posStrListIn != NULL && i<20; i++) AddArg(m_pStrListIn->GetNext(m_posStrListIn)); // Caller knows not to call again when the list is empty if(m_posStrListIn == NULL) m_pStrListIn->RemoveAll(); return FALSE; // if we returned TRUE, it would immediately terminate command } /* _________________________________________________________________ It takes no less than three functions to neatly run commands asynchronously: 1) AsyncExecCommand() spawns the worker thread and returns immediately 2) TaskThread(), a non-member function, launders the execution to member function ExecCommand(). This intermediate step is required because the "this" pointer gets in the way of sending a member function pointer to AfxBeginThread() 3) ExecCommand() actually does the work, under an independent thread, but with full member function access to class property _________________________________________________________________ */ void CP4Command::AsyncExecCommand() { // Set priority below normal to avoid gui freeze up m_pTaskThread=AfxBeginThread(TaskThread, (LPVOID) this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED, NULL); m_pTaskThread->m_bAutoDelete=TRUE; // Tinker w/ priority here if reqd m_pTaskThread->ResumeThread(); if (m_MultiProcessorSleep < 0) Sleep(0 - m_MultiProcessorSleep); } BOOL CP4Command::InitConnection() { XTRACE(_T("Task %s Initializing Connection\n"), GetTaskName( )); ASSERT(m_ClosedConn == TRUE); m_pClient->PushCommandPtr(this); m_ClosedConn=FALSE; if(m_IsChildTask) { m_pClient->SetVersion(((CP4winApp *) AfxGetApp())->m_version); m_pClient->SetVar( "prog", "NiftyP4Win"); m_pClient->SetVar("enableStreams"); m_pClient->SetProtocol("enableStreams", ""); return TRUE; } else { Error e; e.Clear(); if(m_UsedTagged) m_pClient->UseTaggedProtocol(); else m_pClient->UseSpecdefsProtocol(); m_pClient->Init(&e); if(!e.Test()) { m_RanInit=TRUE; // Allow the user to Cancel the command if desired global_cancel = 0; // don't want a stale value! m_pClient->SetBreak( &m_cb ); // Notify that we are p4win m_pClient->SetVersion(((CP4winApp *) AfxGetApp())->m_version); m_pClient->SetVar( "prog", "NiftyP4Win"); // Enable the streams m_pClient->SetVar("enableStreams"); m_pClient->SetProtocol("enableStreams", ""); // Record the permanent client if we havent already, then // set the client to the active client // CString client= m_pClient->GetClient().Text(); if( client.Compare( GET_P4REGPTR()->GetP4Client(TRUE)) != 0) GET_P4REGPTR()->SetP4Client( client, FALSE, TRUE, FALSE ); client= GET_P4REGPTR()->GetP4Client(); m_pClient->SetClient( client); // Record the permanent user if we havent already, then // set the user to the active user // note: user must be set before calling m_pClient->GetPassword().Text(); // CString user= CharToCString(m_pClient->GetUser().Text()); if( user.Compare( GET_P4REGPTR()->GetP4User(TRUE)) != 0) GET_P4REGPTR()->SetP4User( user, FALSE, TRUE, FALSE ); user= GET_P4REGPTR()->GetP4User(); m_pClient->SetUser(user); // Record the permanent password if we havent already, then // set the password to the active password // CString password = m_pClient->GetPassword().Text(); if( password.Compare( GET_P4REGPTR()->GetP4UserPassword(TRUE)) != 0) { // Note that a Perm password is actually set only if it has not yet been set // this is because we no longer write passwords to the Registry (3rd arg). GET_P4REGPTR()->SetP4Password( password, FALSE, TRUE, FALSE ); // set Perm } int lev; if ((lev = GET_SERVERLEVEL()) >= 18) { m_pClient->SetPassword( _T("") ); // use the ticket for 2004.2 and later } else if (!lev) // must be a new port { GET_P4REGPTR()->SetP4Password( password, TRUE, FALSE, FALSE ); // also set Temp } else { password= GET_P4REGPTR()->GetP4UserPassword(); m_pClient->SetPassword( password ); } // Record the hostname CString hostname= m_pClient->GetHost().Text(); GET_P4REGPTR()->SetHostname(hostname); } else { m_ErrorTxt= RemoveTabs( FormatError(&e) ); m_FatalError=TRUE; // Sometimes a blatantly wrong port results in the error msg being fired // back too fast for cmainframe to receive it, so pause for a few millisecs Sleep(500); } return !e.Test(); } } void CP4Command::ExecCommand() { BOOL done=FALSE; m_FatalError=FALSE; // Initialize connection if(!InitConnection()) { TheApp()->StatusAdd(m_ErrorTxt, SV_ERROR); done=TRUE; } // Prerequisite commands run here if(!done) PreProcess(done); // Loop to enable list processing while(!done) { // Check for possible abort request if(APP_ABORTING()) { ReleaseServerLock(); ExitThread(0); } // Clear any error m_ErrorTxt.Empty(); m_FatalError=m_SyntaxError=FALSE; { // a bit of ugliness in order to provide SetArgv with // 8-bit strings... int i; for(i = 0; i < m_argsA.GetSize(); i++) { delete m_argsA.GetAt(i); } m_argsA.SetSize(m_args.GetSize()); for(i = 0; i < m_args.GetSize(); i++) { CharString cs = CharFromCString(m_args[i]); char *argA = new char[strlen(cs)+1]; strcpy(argA, cs); m_argsA.SetAt(i, argA); } } m_Function = m_args[0]; // Show the command in the output pane if the user wants it if ( GET_P4REGPTR()->ShowCommandTrace( ) ) TheApp()->StatusAdd( CString ( "Executing " ) + GetP4Command( ) ); // Run the command - run it in a loop so it is restartable BOOL restart; // if true, we need to loop back and try again do { restart = m_RetryUnicodeMode = false; m_pClient->SetArgv( m_args.GetSize() - 1, m_argsA.GetData() + 1 ); m_pClient->Run( CharFromCString(m_Function) ); #ifdef UNICODE if(m_RetryUnicodeMode) { m_pClient->SetTrans(); restart = true; } else #endif if (PWDRequired() && (GET_PWD_ERROR() || GET_NOPWD_SET() || GET_PWDNOTALLOW())) // Password Error? { CString password; BOOL permanent = FALSE; BOOL need2login= FALSE; if (GET_PWD_ERROR()) { while (!MainFrameCWnd) // wait until MainFrame is intitialzed Sleep(100); CGetPwdDlg dlg(MainFrameCWnd); // force Pswd dialog to be a child of MainFrame if(dlg.DoModal( ) == IDCANCEL) // popup the Password dialog { m_PWD_DlgCancelled = TRUE; // they canceled // Clear the error so we don't ask unnecessarily if they switch users next SET_PWD_ERROR(FALSE); break; // break out of the loop } password = dlg.GetPassword(); // get the clear-text password if (GET_SECURITYLEVEL() >= 2) // if high security, forget any password { GET_P4REGPTR()->SetP4Password(_T(""), TRUE, TRUE, TRUE); SetEnvironmentVariable(_T("P4PASSWD"), NULL); } else { permanent = dlg.IsWriteToRegistry(); // if not perm & is a 2004.2+ server, we have to clear any reg entry if (!permanent && GET_SERVERLEVEL() >= 18) { GET_P4REGPTR()->SetP4Password(_T(""), TRUE, TRUE, TRUE); SetEnvironmentVariable(_T("P4PASSWD"), NULL); } } } else if (GET_PWDNOTALLOW()) { SET_PWDNOTALLOW(FALSE); password = GET_P4REGPTR()->GetP4UserPassword(); if (GET_SECURITYLEVEL() >= 2) // if high security, forget any password GET_P4REGPTR()->SetP4Password(_T(""), TRUE, FALSE, FALSE); } else // we need to login using the password they set { SET_NOPWD_SET(FALSE); // clear the error password = GET_P4REGPTR()->GetP4UserPassword(); need2login = TRUE; if (GET_SECURITYLEVEL() >= 2) // if high security, forget the password GET_P4REGPTR()->SetP4Password(_T(""), TRUE, FALSE, FALSE); } int err = 0; if (need2login || GET_SERVERLEVEL() >= 18) // 2004.1 server or later? { BOOL b = false; CCmd_Login *pCmd = new CCmd_Login; // run p4 login CString portStr = m_pClient->GetPort().Text(); // get current port pCmd->GetClient()->SetPort(portStr); // run login against cur port CString userStr = m_pClient->GetUser().Text(); // get current user pCmd->GetClient()->SetUser(userStr); // run login against cur user // In certain cases we have to temporialy 'unbusy' the server if (!m_ServerKey && !m_Asynchronous && SERVER_BUSY()) { ((CP4winApp *) AfxGetApp())->m_CS.ClearServerBusy(); b = true; // remeber we 'unbusied' the server } pCmd->Init(NULL, RUN_SYNC, (m_ServerKey ? HOLD_LOCK : LOSE_LOCK), m_ServerKey); pCmd->Run(password); // run the login command err = pCmd->GetError(); delete pCmd; if (b) // if we 'unbusied' the server, mark it busy again ((CP4winApp *) AfxGetApp())->m_CS.SetServerBusy(); m_pClient->SetPassword(_T("")); // clear any old ticket or password } else // 2003.2 server or earlier { MD5 md5; // hash the clear-text StrBuf foo; foo.Set(CharFromCString(password)); StrPtr *sptr; sptr = &foo; md5.Update(*sptr); md5.Final(foo); password = CharToCString(foo.Text()); GET_P4REGPTR()->SetP4Password( password, TRUE, permanent, permanent ); m_pClient->SetPassword(password); // finally add the pswd to the client obj } if (!err) // were there any problems (i.e. did p4 login run ok?) { SET_PWD_ERROR(FALSE); // clear the error indicators SET_NOPWD_SET(FALSE); SET_PWDNOTALLOW(FALSE); m_FatalError = false; restart = true; // and restart the original command if ( GET_P4REGPTR()->ShowCommandTrace( ) ) TheApp()->StatusAdd( CString ( "Re-executing " ) + GetP4Command( ) ); } } } while(restart); if( m_FatalError ) done = TRUE; else ProcessResults(done); } // Follow-up commands run here if(!m_FatalError) PostProcess(); // Make sure server status gets cleared BEFORE the interface thread // can act on a completion message if(!m_IsChildTask) { Error e; // Clear server busy status if(m_Asynchronous && !m_HoldServerLock) ReleaseServerLock(); // Clear any password error if the PWD worked if(!m_FatalError && PWDRequired()) { SET_PWD_ERROR(FALSE); SET_NOPWD_SET(FALSE); SET_PWDNOTALLOW(FALSE); if (GET_SERVERLEVEL() >= 18) // 2004.1 server or later? { // clear password to force ticket use GET_P4REGPTR()->SetP4Password( _T(""), FALSE, TRUE, FALSE ); // set Prem GET_P4REGPTR()->SetP4Password( _T(""), TRUE, FALSE, FALSE ); // also set Temp } } // Make sure the connection closed, or NT3.51 will bite it when // next command is init'ed CloseConn(&e); if (e.Test() && !e.IsFatal()) // Fatals are taken care of in CloseConn { CString msg = FormatError(&e); if (msg.Find(_T("WSAECONNRESET")) != -1) // WSAECONNRESETs are fatal m_FatalError = TRUE; TheApp()->StatusAdd(msg, m_FatalError ? SV_ERROR : SV_WARNING); } // Finally, post back to ui thread if(m_ReplyWnd != NULL) ::PostMessage( m_ReplyWnd, m_ReplyMsg, (WPARAM) this, 0); } } /* _________________________________________________________________ At this point, the command is ready to run, so blast ahead. The control over what command can run or be queued is in the Run() member function. See CP4CommandStatus for queue management. At present, only 3 commands are queueable (and have IsQueueable() override functions). Those commands can sit in queue for some time, and should not encounter errors upon return. All relevant context information is carried by a queueable command. For a command sequence that must not be interruptible, call the first command's Init() with HOLD_LOCK. When that command returns, use GetServerKey() to grab the key, and pass that key into the next command in the sequence via Init(). The last command should be run with LOSE_KEY in its Init(), or alternatively ReleaseServerLock() can be called to drop the lock and re-enable the queue. _________________________________________________________________ */ UINT TaskThread( LPVOID pParam ) { CP4Command *pCmd = ( CP4Command * ) pParam; { // pCmd may be deleted by the time ExecCommand returns // so we can't be using it afterwards. #ifdef _DEBUG // to aid in debugging prematurely deleted commands // this string must be cleaned up before calling AfxEndThread // or a memory leak will result, hence the extra curly braces. CString taskName(pCmd->GetTaskName()); XTRACE(_T("Async Task: %s Beginning\n"), taskName); #endif if (m_MultiProcessorSleep > 0) Sleep(m_MultiProcessorSleep); pCmd->ExecCommand( ); #ifdef _DEBUG XTRACE(_T("Async Task: %s Complete\n"), taskName); #endif } AfxEndThread( 0 ); return 0; } /////////////////////////////////////// // Default handlers for server output void CP4Command::OnOutputInfo(char level, LPCTSTR data, LPCTSTR msg) { // Check for possible abort request if(APP_ABORTING() && m_Asynchronous) { ReleaseServerLock(); ExitThread(0); } TheApp()->StatusAdd(msg, SV_WARNING); } void CP4Command::OnOutputStat( StrDict *varList ) { // Only specific commands use this function ASSERT(0); } void CP4Command::OnOutputText(LPCTSTR data, int length) { // Only specific commands use this function ASSERT(0); } void CP4Command::OnOutputError(char level, LPCTSTR errBuf, LPCTSTR errMsg) { if(APP_ABORTING() && m_Asynchronous) { ReleaseServerLock(); ExitThread(0); } // Most if not all "errors" returned here are info messages // P4_OPENED "//depot/... - file(s) not opened anywhere." // CString txt( errBuf ); CString msg( errMsg ); if (( txt.Find( _T("Perforce password") ) > -1 ) || ( txt.Find( _T("please login") ) > -1 )) { SET_PWD_ERROR(TRUE); TheApp()->StatusAdd( msg, SV_WARNING ); m_ErrorTxt= LoadStringResource(IDS_OPERATION_CANNOT_COMPLETED_BECAUSE_BAD_PASSWORD); m_FatalError=TRUE; return; } if ( txt.Find( _T("Password not allowed at this server security level") ) > -1 ) { SET_PWDNOTALLOW(TRUE); m_ErrorTxt= msg; m_FatalError=TRUE; return; } if ((txt.Find(_T("Password must be set ")) > -1) || (txt.Find(_T("server requires the password to be reset")) > -1)) { m_FatalError=TRUE; HWND hWnd= AfxGetMainWnd()->GetSafeHwnd(); if( hWnd != NULL ) { TheApp()->StatusAdd( m_ErrorTxt = msg, SV_WARNING ); BOOL b = false; // In certain cases we have to temporialy 'unbusy' the server if (!m_ServerKey && !m_Asynchronous && SERVER_BUSY()) { ((CP4winApp *) AfxGetApp())->m_CS.ClearServerBusy(); b = true; // remeber we 'unbusied' the server } if (IDOK == ::SendMessage(hWnd, WM_USERPSWDDLG, (WPARAM)TRUE, (LPARAM)m_ServerKey)) { m_pClient->SetPassword(GET_P4REGPTR()->GetP4UserPassword()); SET_NOPWD_SET(TRUE); } if (b) // if we 'unbusied' the server, mark it busy again ((CP4winApp *) AfxGetApp())->m_CS.SetServerBusy(); return; } } #ifdef UNICODE if (txt.Find(_T("Unicode clients require a unicode enabled server.") ) > -1 ) { SET_UNICODE(FALSE); m_RetryUnicodeMode = TRUE; return; } else if (txt.Find(_T("Unicode server permits only unicode enabled clients.") ) > -1 ) { SET_UNICODE(TRUE); CString charset= GET_P4REGPTR()->GetP4Charset(); if(charset.IsEmpty()) { m_ErrorTxt= _T("Unicode server permits only unicode enabled clients. You must set P4CHARSET to use this server"); m_FatalError=TRUE; TheApp()->StatusAdd( m_ErrorTxt, SV_WARNING ); return; } m_RetryUnicodeMode = TRUE; return; } #endif if( txt.Find( _T("Request too large") ) > -1 && txt.Find(_T("maxresults")) > -1 ) { if (txt != msg) TheApp()->StatusAdd( msg, SV_WARNING ); int semicolon= txt.Find(_T(";")); if( semicolon > -1 ) txt= txt.Left( semicolon ); txt+= LoadStringResource(IDS_TO_FULLY_REFRESH_THE_DISPLAY_YOU_NEED_TO_ADJUST_MAXRESULTS); txt+= GET_P4REGPTR()->GetP4User(); txt+= LoadStringResource(IDS_quote_nl_SEE_P4WIN_HELP_FOR_INFO_REGARDING_MAXRESULTS); TheApp()->StatusAdd( txt, SV_ERROR ); m_FatalError=TRUE; return; } if (( txt.Find( _T("You don't have permission") ) > -1 ) || ( txt.Find( _T("no permission for operation") ) > -1 )) { if (m_IgnorePermissionErrs) return; TheApp()->StatusAdd( msg, SV_WARNING ); m_FatalError=TRUE; return; } if(txt.Find(_T(" - over license quota")) != -1) { m_ErrorTxt=txt; // save off the error message first int i = msg.Find('\n'); int j = msg.Find('\n', i+1); if (i < j && i != -1) { txt = msg.Left(i+1) + msg.Mid(j); msg = txt; // have to use a temp variable } TheApp()->StatusAdd(msg, SV_WARNING ); m_FatalError=TRUE; return; } if(txt.Find(_T("Client template (-t) only allowed for new client")) != -1) { TheApp()->StatusAdd(LoadStringResource(IDS_CREATE_CLIENT_FROM_TEMPLATE_ONLY_ALLOWED_FOR_NEW_CLIENT), SV_WARNING ); m_FatalError=TRUE; return; } if( txt.Find( _T("Must create client ")) != -1 || txt.Find( _T(" - use 'client' command to create it.") ) != -1 ) { PostClientError(); m_FatalError = TRUE; return; } else if ((TheApp()->m_RunClientWizOnly) && (txt.Find(_T(" not opened on this client")) == -1) && (txt.Find(_T(" not in client view")) == -1)) { HWND hWnd= AfxGetMainWnd()->m_hWnd; if( hWnd != NULL ) ::PostMessage(hWnd, WM_COMMAND, ID_APP_EXIT, 0); } if( GET_SERVERLEVEL() > 0 && GET_SERVERLEVEL() < 3 ) { TheApp()->StatusAdd( LoadStringResource(IDS_ERROR_P4WIN_REQUIRES_PERFORCE_SERVER_97_3_OR_NEWER), SV_ERROR ); m_FatalError = TRUE; return; } if ( txt.Find( _T("Purely numeric name not allowed") ) > -1 ) m_FatalErrorCleared=TRUE; // Subclasses of CP4Command should call HandledCmdSpecificError // // If a known error was not encountered, we still report the // problem to the status window, but not with the SV_ERROR // display code. Otherwise, if the error/warning occurrs // a few hundred times, the user has to click 'OK' a few too // many times for comfort. We also don't set m_FatalError, // because there on occasion is a message sent to OutputError // that is not fatal.. // CString sErrBuf(errBuf); CString sErrMsg(errMsg); if( !HandledCmdSpecificError( sErrBuf, sErrMsg )) { TheApp()->StatusAdd( errMsg, SV_WARNING ); } } BOOL CP4Command::HandledCmdSpecificError(LPCTSTR errBuf, LPCTSTR errMsg) { return FALSE; } void CP4Command::OnErrorPause(LPCTSTR errBuf, Error *e) { // Check for possible abort request if(APP_ABORTING() && m_Asynchronous) { ReleaseServerLock(); ExitThread(0); } TheApp()->StatusAdd(errBuf, SV_ERROR); } void CP4Command::ProcessResults(BOOL& done) { // Note: for commands without input lists, this default will // do absolutely nothing if(m_pStrListIn == NULL || m_pStrListIn->IsEmpty()) done = TRUE; else if(!done) done = NextListArgs(); } void CP4Command::PreProcess(BOOL& done) { // Do nothing by default } void CP4Command::PostProcess() { // Do nothing by default } void CP4Command::DeleteResults() { // Do nothing by default } void CP4Command::OnInputData(StrBuf *strBuf, Error *e) { // object violently by default ASSERT(0); } int CP4Command::OnResolve( ClientMerge *m, Error *e ) { // object violently by default ASSERT(0); return CMS_QUIT; } void CP4Command::OnPrompt( const StrPtr &msg, StrBuf &rsp, int noEcho, Error *e ) { ASSERT(0); } /* _________________________________________________________________ put the client commands in the status pane, so we can debug. since the users can see them, substitute asterisks for the password if there is one. hey! sometimes the command is blank, and the args are 0. like for ostat. _________________________________________________________________ */ CString CP4Command::GetP4Command( ) { CString msg ; BOOL debug= FALSE; #ifdef _DEBUG debug=TRUE; #endif if( !debug && m_TaskName == _T("Password") ) msg= _T("p4 passwd"); else { int args = m_args.GetSize() ; while ( args-- ) msg = CString ( _T(" ") ) + m_args[ args ] + msg; msg = _T("p4") + msg; } return msg; } void CP4Command::SetServerKey(int lock) { ASSERT(lock); m_ServerKey= lock; m_HaveServerLock=TRUE; } int CP4Command::GetServerKey() { ASSERT(m_HaveServerLock); return m_ServerKey; } BOOL CP4Command::GetServerLock(DWORD timeout) { ASSERT(!m_HaveServerLock); if(m_Asynchronous) { XTRACE(_T("Async Task: %s Attempting lock...\n"), GetTaskName()); m_HaveServerLock=GET_SERVER_LOCK( m_ServerKey ); #ifdef _DEBUG if(m_HaveServerLock) XTRACE(_T("Async Task: %s Got lock...\n"), GetTaskName()); else XTRACE(_T("Async Task: %s Failed to lock...\n"), GetTaskName()); #endif } else // What is a syncro task doing getting a lock? ASSERT(0); return m_HaveServerLock; } void CP4Command::ReleaseServerLock() { if(m_Asynchronous) { ASSERT(m_HaveServerLock); XTRACE(_T("Async Task: %s Releasing lock\n"), GetTaskName()); RELEASE_SERVER_LOCK( m_ServerKey); m_HaveServerLock=FALSE; m_ServerKey=0; } // else // What is a syncro task doing releasing a lock? // ASSERT(0); // since ReleaseServerLock is called by command clients that // can't determine if the command is syncro, can't faile here } void CP4Command::PostClientError() { // Attempt to activate the clients pane, and let the UI know that the // error was due to a bad client HWND hWnd= AfxGetMainWnd()->m_hWnd; if( hWnd != NULL ) ::PostMessage(hWnd, WM_CLIENTERROR, 0, 0); }
28.620058
118
0.62337
[ "object" ]
2325736aa5eebe68909b692674d45a903d3cdb56
649
cpp
C++
DP/palindrome_partition.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
DP/palindrome_partition.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
DP/palindrome_partition.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool is_pal(const string &s, int i, int j) { int low = i; int high = j; while(low < high) { if(s[low] != s[high]) { return false; } low++; high--; } return true; } int minCut(string A) { int n = A.size(); vector<int> dp(n + 1, INT_MAX); dp[0] = 0; for(int i = 1; i <= n; ++i) { if(is_pal(A, 0, i - 1)) { dp[i] = 0; continue; } for(int j = i; j >= 1; --j) { if(is_pal(A, j - 1, i - 1)) { dp[i] = min(dp[i], 1 + dp[j - 1]); } } } return (dp[n] == INT_MAX) ? n : dp[n]; } int main(void) { string s; cin >> s; cout << minCut(s) << endl; return 0; }
14.108696
44
0.485362
[ "vector" ]
23267859f4d7bec6fdaa761a95b9852ced6ea134
7,998
cc
C++
src/yb/encryption/encryption_util.cc
polarweasel/yugabyte-db
9064eca9dc35769cf6b034e537ee42efed03c47d
[ "Apache-2.0", "CC0-1.0" ]
4
2019-07-19T12:55:40.000Z
2021-03-25T15:59:09.000Z
src/yb/encryption/encryption_util.cc
00mjk/yugabyte-db
968b5229a736acc0c30bfabaf9f535fa60c3e878
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/encryption/encryption_util.cc
00mjk/yugabyte-db
968b5229a736acc0c30bfabaf9f535fa60c3e878
[ "Apache-2.0", "CC0-1.0" ]
1
2021-08-23T10:06:40.000Z
2021-08-23T10:06:40.000Z
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/encryption/encryption_util.h" #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/ssl.h> #include <memory> #include <boost/pointer_cast.hpp> #include "yb/gutil/endian.h" #include "yb/encryption/cipher_stream.h" #include "yb/encryption/encryption.pb.h" #include "yb/encryption/header_manager.h" #include "yb/util/atomic.h" #include "yb/util/flag_tags.h" #include "yb/util/logging.h" #include "yb/util/random_util.h" #include "yb/util/status_format.h" DEFINE_int64(encryption_counter_min, 0, "Minimum value (inclusive) for the randomly generated 32-bit encryption counter at " "the beginning of a file"); TAG_FLAG(encryption_counter_min, advanced); TAG_FLAG(encryption_counter_min, hidden); DEFINE_int64(encryption_counter_max, 0x7fffffffLL, "Maximum value (inclusive) for the randomly generated 32-bit encryption counter at " "the beginning of a file. Setting to 2147483647 by default to reduce the probability " "of #3707 until it is fixed. This only reduces the key size by 1 bit but eliminates " "the encryption overflow issue for files up to 32 GiB in size."); TAG_FLAG(encryption_counter_max, advanced); TAG_FLAG(encryption_counter_max, hidden); DEFINE_test_flag(bool, encryption_use_openssl_compatible_counter_overflow, true, "Overflow into the rest of the initialization vector when computing counter" "increment for newly created keys.") namespace yb { namespace encryption { namespace { std::vector<std::unique_ptr<std::mutex>> crypto_mutexes; } // anonymous namespace constexpr uint32_t kDefaultKeySize = 16; void EncryptionParams::ToEncryptionParamsPB(EncryptionParamsPB* encryption_header) const { encryption_header->set_data_key(key, key_size); encryption_header->set_nonce(nonce, kBlockSize - 4); encryption_header->set_counter(counter); encryption_header->set_openssl_compatible_counter_overflow(openssl_compatible_counter_overflow); } Result<EncryptionParamsPtr> EncryptionParams::FromEncryptionParamsPB( const EncryptionParamsPB& encryption_header) { auto encryption_params = std::make_unique<EncryptionParams>(); memcpy(encryption_params->key, encryption_header.data_key().c_str(), encryption_header.data_key().size()); memcpy(encryption_params->nonce, encryption_header.nonce().c_str(), kBlockSize - 4); encryption_params->counter = encryption_header.counter(); auto size = encryption_header.data_key().size(); RETURN_NOT_OK(IsValidKeySize(size)); encryption_params->key_size = size; encryption_params->openssl_compatible_counter_overflow = encryption_header.openssl_compatible_counter_overflow(); return encryption_params; } Result<EncryptionParamsPtr> EncryptionParams::FromSlice(const Slice& s) { auto params = std::make_unique<EncryptionParams>(); Slice mutable_s(s); memcpy(params->nonce, s.data(), sizeof(params->nonce)); memcpy(&params->counter, s.data() + sizeof(params->nonce), sizeof(params->counter)); mutable_s.remove_prefix(sizeof(params->nonce) + sizeof(params->counter)); RETURN_NOT_OK(IsValidKeySize(mutable_s.size())); memcpy(params->key, mutable_s.data(), mutable_s.size()); params->key_size = mutable_s.size(); return params; } EncryptionParamsPtr EncryptionParams::NewEncryptionParams() { auto encryption_params = std::make_unique<EncryptionParams>(); RAND_bytes(encryption_params->key, kDefaultKeySize); RAND_bytes(encryption_params->nonce, kBlockSize - 4); RAND_bytes(boost::reinterpret_pointer_cast<uint8_t>(&encryption_params->counter), 4); const int64_t ctr_min = GetAtomicFlag(&FLAGS_encryption_counter_min); const int64_t ctr_max = GetAtomicFlag(&FLAGS_encryption_counter_max); if (0 <= ctr_min && ctr_min <= ctr_max && ctr_max <= std::numeric_limits<uint32_t>::max()) { encryption_params->counter = ctr_min + encryption_params->counter % (ctr_max - ctr_min + 1); } else { YB_LOG_EVERY_N_SECS(WARNING, 10) << "Invalid encrypted counter range: " << "[" << ctr_min << ", " << ctr_max << "] specified by --encryption_counter_{min,max}, " << "falling back to using the full unsigned 32-bit integer range."; } encryption_params->key_size = kDefaultKeySize; encryption_params->openssl_compatible_counter_overflow = FLAGS_TEST_encryption_use_openssl_compatible_counter_overflow; return encryption_params; } Status EncryptionParams::IsValidKeySize(uint32_t size) { if (size != 16 && size != 24 && size != 32) { return STATUS_SUBSTITUTE( InvalidArgument, "After parsing nonce and counter, expect 16, 24, or 32 bytes, found $0", size); } return Status::OK(); } bool EncryptionParams::Equals(const EncryptionParams& other) { return memcmp(key, other.key, other.key_size) == 0 && memcmp(nonce, other.nonce, sizeof(nonce)) == 0 && counter == other.counter && key_size == other.key_size && openssl_compatible_counter_overflow == other.openssl_compatible_counter_overflow; } void* EncryptionBuffer::GetBuffer(uint32_t size_needed) { if (size_needed > size) { size = size_needed; if (buffer) { free(buffer); } buffer = malloc(size_needed); } return buffer; } EncryptionBuffer::~EncryptionBuffer() { if (buffer) { free(buffer); } } EncryptionBuffer* EncryptionBuffer::Get() { static thread_local EncryptionBuffer encryption_buffer; return &encryption_buffer; } Result<uint32_t> GetHeaderSize(SequentialFile* file, HeaderManager* header_manager) { if (!header_manager) { return STATUS(InvalidArgument, "header_manager argument must be non null."); } Slice encryption_info; auto metadata_start = header_manager->GetEncryptionMetadataStartIndex(); auto buf = static_cast<uint8_t*>(EncryptionBuffer::Get()->GetBuffer(metadata_start)); RETURN_NOT_OK(file->Read(metadata_start, &encryption_info, buf)); auto status = VERIFY_RESULT(header_manager->GetFileEncryptionStatusFromPrefix(encryption_info)); return status.is_encrypted ? (status.header_size + metadata_start) : 0; } class OpenSSLInitializer { public: OpenSSLInitializer() { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); OpenSSL_add_all_ciphers(); } ~OpenSSLInitializer() { ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(nullptr); SSL_COMP_free_compression_methods(); } }; OpenSSLInitializer& InitOpenSSL() { static OpenSSLInitializer initializer; return initializer; } Status CompleteCreateEncryptionInfoForWrite(const std::string& header, std::unique_ptr<EncryptionParams> encryption_params, std::unique_ptr<BlockAccessCipherStream>* stream, uint32_t* header_size) { // Since file doesn't exist or this overwrites, append key to the name and create. *stream = std::make_unique<BlockAccessCipherStream>(std::move(encryption_params)); RETURN_NOT_OK((*stream)->Init()); if (header.size() > std::numeric_limits<uint32_t>::max()) { return STATUS_FORMAT(Corruption, "Invalid encryption header size: $0", header.size()); } *header_size = static_cast<uint32_t>(header.size()); return Status::OK(); } } // namespace encryption } // namespace yb
37.549296
100
0.729932
[ "vector" ]
232a3d1224a858c36131ae7bebc54cccc93c94e3
1,301
cpp
C++
InsertDeleteGetRandomO(1).cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
3
2017-11-27T03:01:50.000Z
2021-03-13T08:14:00.000Z
InsertDeleteGetRandomO(1).cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
InsertDeleteGetRandomO(1).cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
class RandomizedSet { public: /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if (hash_table_.count(val)) return false; hash_table_[val] = (int)nums_.size(); nums_.push_back(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { auto it = hash_table_.find(val); if (it == hash_table_.end()) return false; int idx = it->second; hash_table_.erase(it); if (nums_.back() != val) { nums_[idx] = nums_.back(); hash_table_[nums_.back()] = idx; } nums_.pop_back(); return true; } /** Get a random element from the set. */ int getRandom() { return nums_[rand() % nums_.size()]; } private: vector<int> nums_; unordered_map<int, int> hash_table_; }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
28.911111
109
0.588778
[ "object", "vector" ]
232f3ad8accd39ef9360e3d9d4541454986171d8
1,908
cpp
C++
Failed/failed-1251A.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Failed/failed-1251A.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Failed/failed-1251A.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
/* Author : Qazi Fahim Farhan (@fahimfarhan) */ /* May the CodeForces be with you! */ #include <bits/stdc++.h> using namespace std; #define PI 2*acos(0) //typedef long long int ll; #define ll long long int // other popular ones=> int64_t, uint64_t => use for 10^18 ll MODULO = 1e9+7; bool myAssert(bool b); void testDrivenDevelopment(); int start(int argc=0, char const *argv[] = NULL); // int n,m;s vector<int> *g; bool *isvisited; int main(int argc, char const *argv[]) { /* code */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* cout << setprecision(8); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll T; string s; char ch; cin>>T; while(T--){ cin>>s; set<char> st; vector<char> v; if(s.size() == 1){ st.insert(s[0]); } else if(s.size() == 2){ if(s[0]!=s[1]){ st.insert(s[0]); st.insert(s[1]); } }else{ if(s[0]!=s[1]){ st.insert(s[0]); } for(int i=1; i<s.size()-1; i++){ ch = s[i]; if( (ch != s[i+1]) && (ch!=s[i-1])){ st.insert(ch); } } if(s[s.size()-1] != s[s.size()-2]){ st.insert(s[s.size()-1]); } } for(auto x:st){ //v.push_back(x); cout<<x<<""; } //sort(v.begin(), v.end()); cout<<"\n"; } return 0; } /** Dread it, run from it, destiny arrives all the same ! I find your lack of faith in the CodeForces disturbing! >_< Love you 3000 ! Keep It Simple Stupid (KISS)! Good Hunting 47! */ /** AC I - Redemption AC II - Revenge AC: Brotherhood - Justice AC: Revelation - Answers AC III - Freedom AC IV - Glory AC Rogue - Betrayal AC Unity - Love AC Syndicate - Family AC Origins - Beginnings */
22.714286
89
0.509434
[ "vector" ]
2334a1b57f29ec20f49b919d2149d1b7e8001f00
4,711
cpp
C++
Source/JavaScriptCore/API/glib/JSAPIWrapperObjectGLib.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/JavaScriptCore/API/glib/JSAPIWrapperObjectGLib.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/JavaScriptCore/API/glib/JSAPIWrapperObjectGLib.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2018 Igalia S.L. * Copyright (C) 2013-2018 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. 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 INC. 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 "config.h" #include "JSAPIWrapperObject.h" #include "JSCGLibWrapperObject.h" #include "JSCInlines.h" #include "JSCallbackObject.h" #include "Structure.h" #include <wtf/NeverDestroyed.h> class JSAPIWrapperObjectHandleOwner final : public JSC::WeakHandleOwner { public: void finalize(JSC::Handle<JSC::Unknown>, void*) final; bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&, const char**) final; }; static JSAPIWrapperObjectHandleOwner* jsAPIWrapperObjectHandleOwner() { static NeverDestroyed<JSAPIWrapperObjectHandleOwner> jsWrapperObjectHandleOwner; return &jsWrapperObjectHandleOwner.get(); } void JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*) { auto* wrapperObject = static_cast<JSC::JSAPIWrapperObject*>(handle.get().asCell()); if (!wrapperObject->wrappedObject()) return; JSC::Heap::heap(wrapperObject)->releaseSoon(std::unique_ptr<JSC::JSCGLibWrapperObject>(static_cast<JSC::JSCGLibWrapperObject*>(wrapperObject->wrappedObject()))); JSC::WeakSet::deallocate(JSC::WeakImpl::asWeakImpl(handle.slot())); } bool JSAPIWrapperObjectHandleOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, JSC::SlotVisitor& visitor, const char**) { JSC::JSAPIWrapperObject* wrapperObject = JSC::jsCast<JSC::JSAPIWrapperObject*>(handle.get().asCell()); // We use the JSGlobalObject when processing weak handles to prevent the situation where using // the same wrapped object in multiple global objects keeps all of the global objects alive. if (!wrapperObject->wrappedObject()) return false; return visitor.vm().heap.isMarked(wrapperObject->structure()->globalObject()) && visitor.containsOpaqueRoot(wrapperObject->wrappedObject()); } namespace JSC { template <> const ClassInfo JSCallbackObject<JSAPIWrapperObject>::s_info = { "JSAPIWrapperObject", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSCallbackObject) }; template<> const bool JSCallbackObject<JSAPIWrapperObject>::needsDestruction = true; template <> IsoSubspace* JSCallbackObject<JSAPIWrapperObject>::subspaceForImpl(VM& vm, SubspaceAccess mode) { switch (mode) { case SubspaceAccess::OnMainThread: return vm.apiWrapperObjectSpace<SubspaceAccess::OnMainThread>(); case SubspaceAccess::Concurrently: return vm.apiWrapperObjectSpace<SubspaceAccess::Concurrently>(); } RELEASE_ASSERT_NOT_REACHED(); return nullptr; } template <> Structure* JSCallbackObject<JSAPIWrapperObject>::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto) { return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), &s_info); } JSAPIWrapperObject::JSAPIWrapperObject(VM& vm, Structure* structure) : Base(vm, structure) { } void JSAPIWrapperObject::finishCreation(VM& vm) { Base::finishCreation(vm); WeakSet::allocate(this, jsAPIWrapperObjectHandleOwner(), 0); // Balanced in JSAPIWrapperObjectHandleOwner::finalize. } void JSAPIWrapperObject::setWrappedObject(void* wrappedObject) { ASSERT(!m_wrappedObject); m_wrappedObject = wrappedObject; } void JSAPIWrapperObject::visitChildren(JSCell* cell, JSC::SlotVisitor& visitor) { Base::visitChildren(cell, visitor); } } // namespace JSC
40.612069
172
0.762259
[ "object" ]
233d71a19068769286ee9790eb29e2adb3236bd2
1,713
hpp
C++
include/statement.hpp
wyk9787/G-compiler
dcdd3f7a5f80cd7dc1e28c74bbe3a84ace1dd7ab
[ "MIT" ]
null
null
null
include/statement.hpp
wyk9787/G-compiler
dcdd3f7a5f80cd7dc1e28c74bbe3a84ace1dd7ab
[ "MIT" ]
null
null
null
include/statement.hpp
wyk9787/G-compiler
dcdd3f7a5f80cd7dc1e28c74bbe3a84ace1dd7ab
[ "MIT" ]
null
null
null
#ifndef STATEMENT_HPP #define STATEMENT_HPP #include <string> #include <vector> #include "c_expression.hpp" #include "c_type.hpp" class Stmt { public: virtual std::string string_of_stmt() = 0; }; class SDecl : public Stmt { private: std::string name; ctyp::Shared_Typ t; cexp::Shared_Exp e; public: SDecl(std::string _name, ctyp::Shared_Typ _t, cexp::Shared_Exp _e); std::string string_of_stmt(); }; class SIf : public Stmt { private: cexp::Shared_Exp e; std::vector<Shared_Stmt> b1; std::vector<Shared_Stmt> b2; public: SIf(cexp::Shared_Exp _e, std::vector<Shared_Stmt> _b1, std::vector<Shared_Stmt> b2); std::string string_of_stmt(); }; class SWhile : public Stmt { private: cexp::Shared_Exp e; std::vector<Shared_Stmt> b; public: SWhile(cexp::Shared_Exp _e, std::vector<Shared_Stmt> _b); std::string string_of_stmt(); }; class SRet : public Stmt { private: cexp::Shared_Exp e; public: SRet(cexp::Shared_Exp _e); std::string string_of_stmt(); }; class SPrint : public Stmt { private: cexp::Shared_Exp e; public: SPrint(cexp::Shared_Exp _e); std::string string_of_stmt(); }; class SAssign : public Stmt { private: std::string name; cexp::Shared_Exp e; public: SAssign(std::string _name, cexp::Shared_Exp _e); std::string string_of_stmt(); }; class SDef : public Stmt { private: ctyp::Shared_Typ t; std::string name; public: SDef(ctyp::Shared_Typ _t, std::string _name); std::string string_of_stmt(); }; class SStruct : public Stmt { private: std::string name; Shared_Stmt s1; Shared_Stmt s2; public: SStruct(std::string _name, Shared_Stmt _s1, Shared_Stmt _s2); std::string string_of_stmt(); }; #endif
17.659794
69
0.692936
[ "vector" ]
233f85b1423e880b582197947c128217e886ea05
7,556
cpp
C++
dbbrain/src/v20191016/model/DescribeDBDiagReportTasksRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
dbbrain/src/v20191016/model/DescribeDBDiagReportTasksRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
dbbrain/src/v20191016/model/DescribeDBDiagReportTasksRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/dbbrain/v20191016/model/DescribeDBDiagReportTasksRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Dbbrain::V20191016::Model; using namespace std; DescribeDBDiagReportTasksRequest::DescribeDBDiagReportTasksRequest() : m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_instanceIdsHasBeenSet(false), m_sourcesHasBeenSet(false), m_healthLevelsHasBeenSet(false), m_taskStatusesHasBeenSet(false), m_offsetHasBeenSet(false), m_limitHasBeenSet(false), m_productHasBeenSet(false) { } string DescribeDBDiagReportTasksRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_startTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_instanceIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceIds"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_instanceIds.begin(); itr != m_instanceIds.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_sourcesHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Sources"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_sources.begin(); itr != m_sources.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_healthLevelsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HealthLevels"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_healthLevels.c_str(), allocator).Move(), allocator); } if (m_taskStatusesHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskStatuses"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_taskStatuses.c_str(), allocator).Move(), allocator); } if (m_offsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Offset"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_offset, allocator); } if (m_limitHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Limit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_limit, allocator); } if (m_productHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Product"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_product.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string DescribeDBDiagReportTasksRequest::GetStartTime() const { return m_startTime; } void DescribeDBDiagReportTasksRequest::SetStartTime(const string& _startTime) { m_startTime = _startTime; m_startTimeHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; } string DescribeDBDiagReportTasksRequest::GetEndTime() const { return m_endTime; } void DescribeDBDiagReportTasksRequest::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } vector<string> DescribeDBDiagReportTasksRequest::GetInstanceIds() const { return m_instanceIds; } void DescribeDBDiagReportTasksRequest::SetInstanceIds(const vector<string>& _instanceIds) { m_instanceIds = _instanceIds; m_instanceIdsHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::InstanceIdsHasBeenSet() const { return m_instanceIdsHasBeenSet; } vector<string> DescribeDBDiagReportTasksRequest::GetSources() const { return m_sources; } void DescribeDBDiagReportTasksRequest::SetSources(const vector<string>& _sources) { m_sources = _sources; m_sourcesHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::SourcesHasBeenSet() const { return m_sourcesHasBeenSet; } string DescribeDBDiagReportTasksRequest::GetHealthLevels() const { return m_healthLevels; } void DescribeDBDiagReportTasksRequest::SetHealthLevels(const string& _healthLevels) { m_healthLevels = _healthLevels; m_healthLevelsHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::HealthLevelsHasBeenSet() const { return m_healthLevelsHasBeenSet; } string DescribeDBDiagReportTasksRequest::GetTaskStatuses() const { return m_taskStatuses; } void DescribeDBDiagReportTasksRequest::SetTaskStatuses(const string& _taskStatuses) { m_taskStatuses = _taskStatuses; m_taskStatusesHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::TaskStatusesHasBeenSet() const { return m_taskStatusesHasBeenSet; } int64_t DescribeDBDiagReportTasksRequest::GetOffset() const { return m_offset; } void DescribeDBDiagReportTasksRequest::SetOffset(const int64_t& _offset) { m_offset = _offset; m_offsetHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::OffsetHasBeenSet() const { return m_offsetHasBeenSet; } int64_t DescribeDBDiagReportTasksRequest::GetLimit() const { return m_limit; } void DescribeDBDiagReportTasksRequest::SetLimit(const int64_t& _limit) { m_limit = _limit; m_limitHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::LimitHasBeenSet() const { return m_limitHasBeenSet; } string DescribeDBDiagReportTasksRequest::GetProduct() const { return m_product; } void DescribeDBDiagReportTasksRequest::SetProduct(const string& _product) { m_product = _product; m_productHasBeenSet = true; } bool DescribeDBDiagReportTasksRequest::ProductHasBeenSet() const { return m_productHasBeenSet; }
26.985714
104
0.721281
[ "vector", "model" ]
23427eeb822b6811329b5db0f46e35dcdda4b3b4
19,273
cc
C++
components/omnibox/common/omnibox_features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/omnibox/common/omnibox_features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/omnibox/common/omnibox_features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 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 "components/omnibox/common/omnibox_features.h" #include "build/build_config.h" namespace omnibox { const auto enabled_by_default_desktop_only = #if defined(OS_ANDROID) || defined(OS_IOS) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif ; // Allows Omnibox to dynamically adjust number of offered suggestions to fill in // the space between Omnibox an the soft keyboard. The number of suggestions // shown will be no less than minimum for the platform (eg. 5 for Android). const base::Feature kAdaptiveSuggestionsCount{ "OmniboxAdaptiveSuggestionsCount", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to hide the scheme from steady state URLs displayed in the // toolbar. It is restored during editing. const base::Feature kHideFileUrlScheme{ "OmniboxUIExperimentHideFileUrlScheme", // Android and iOS don't have the File security chip, and therefore still // need to show the file scheme. enabled_by_default_desktop_only}; // Feature used to enable local entity suggestions. Similar to rich entities but // but location specific. E.g., typing 'starbucks near' could display the local // entity suggestion 'starbucks near disneyland \n starbucks * Anaheim, CA'. const base::Feature kOmniboxLocalEntitySuggestions{ "OmniboxLocalEntitySuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable swapping the rows on answers. const base::Feature kOmniboxReverseAnswers{"OmniboxReverseAnswers", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable matching short words to bookmarks for suggestions. const base::Feature kOmniboxShortBookmarkSuggestions{ "OmniboxShortBookmarkSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to force on the experiment of transmission of tail suggestions // from GWS to this client, currently testing for desktop. const base::Feature kOmniboxTailSuggestions{ "OmniboxTailSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that enables the tab-switch suggestions corresponding to an open // tab, for a button or dedicated suggestion. Enabled by default on Desktop // and iOS. const base::Feature kOmniboxTabSwitchSuggestions{ "OmniboxTabSwitchSuggestions", #if defined(OS_ANDROID) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to enable various experiments on keyword mode, UI and // suggestions. const base::Feature kExperimentalKeywordMode{"OmniboxExperimentalKeywordMode", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature to enable clipboard provider to suggest searching for copied images. const base::Feature kEnableClipboardProviderImageSuggestions{ "OmniboxEnableClipboardProviderImageSuggestions", #if defined(OS_IOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature to enable the search provider to send a request to the suggest // server on focus. This allows the suggest server to warm up, by, for // example, loading per-user models into memory. Having a per-user model // in memory allows the suggest server to respond more quickly with // personalized suggestions as the user types. const base::Feature kSearchProviderWarmUpOnFocus{ "OmniboxWarmUpSearchProviderOnFocus", #if defined(OS_IOS) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to display the title of the current URL match. const base::Feature kDisplayTitleForCurrentUrl{ "OmniboxDisplayTitleForCurrentUrl", #if !defined(OS_IOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature used to always swap the title and URL. const base::Feature kUIExperimentSwapTitleAndUrl{ "OmniboxUIExperimentSwapTitleAndUrl", #if defined(OS_IOS) || defined(OS_ANDROID) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to enable speculatively starting a service worker associated // with the destination of the default match when the user's input looks like a // query. const base::Feature kSpeculativeServiceWorkerStartOnQueryInput{ "OmniboxSpeculativeServiceWorkerStartOnQueryInput", base::FEATURE_ENABLED_BY_DEFAULT }; // Feature used to fetch document suggestions. const base::Feature kDocumentProvider{"OmniboxDocumentProvider", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to autocomplete bookmark, history, and document suggestions when // the user input is a prefix of their titles, as opposed to their URLs. const base::Feature kAutocompleteTitles{"OmniboxAutocompleteTitles", base::FEATURE_DISABLED_BY_DEFAULT}; // Returns whether IsInstantExtendedAPIEnabled should be ignored when deciding // the number of Google-provided search suggestions. const base::Feature kOmniboxDisableInstantExtendedLimit{ "OmniboxDisableInstantExtendedLimit", #if defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Show the search engine logo in the omnibox on Android (desktop already does // this). const base::Feature kOmniboxSearchEngineLogo{"OmniboxSearchEngineLogo", base::FEATURE_ENABLED_BY_DEFAULT}; // Feature used to allow users to remove suggestions from clipboard. const base::Feature kOmniboxRemoveSuggestionsFromClipboard{ "OmniboxRemoveSuggestionsFromClipboard", #if defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature to debounce drive requests from the document provider. const base::Feature kDebounceDocumentProvider{ "OmniboxDebounceDocumentProvider", base::FEATURE_DISABLED_BY_DEFAULT}; // Preserves the default match against change when providers return results // asynchronously. This prevents the default match from changing after the user // finishes typing. Without this feature, if the default match is updated right // when the user presses Enter, the user may go to a surprising destination. const base::Feature kOmniboxPreserveDefaultMatchAgainstAsyncUpdate{ "OmniboxPreserveDefaultMatchAgainstAsyncUpdate", base::FEATURE_ENABLED_BY_DEFAULT}; // Demotes the relevance scores when comparing suggestions based on the // suggestion's |AutocompleteMatchType| and the user's |PageClassification|. // This feature's main job is to contain the DemoteByType parameter. const base::Feature kOmniboxDemoteByType{"OmniboxDemoteByType", base::FEATURE_DISABLED_BY_DEFAULT}; // A special flag, enabled by default, that can be used to disable all new // search features (e.g. zero suggest). const base::Feature kNewSearchFeatures{"OmniboxNewSearchFeatures", base::FEATURE_ENABLED_BY_DEFAULT}; // Feature used to cap max zero suggestions shown according to the param // OmniboxMaxZeroSuggestMatches. If omitted, // OmniboxUIExperimentMaxAutocompleteMatches will be used instead. If present, // OmniboxMaxZeroSuggestMatches will override // OmniboxUIExperimentMaxAutocompleteMatches when |from_omnibox_focus| is true. const base::Feature kMaxZeroSuggestMatches{"OmniboxMaxZeroSuggestMatches", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to cap max suggestions shown according to the params // UIMaxAutocompleteMatches and UIMaxAutocompleteMatchesByProvider. const base::Feature kUIExperimentMaxAutocompleteMatches{ "OmniboxUIExperimentMaxAutocompleteMatches", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to cap the number of URL-type matches shown within the // Omnibox. If enabled, the number of URL-type matches is limited (unless // there are no more non-URL matches available.) If enabled, there is a // companion parameter - OmniboxMaxURLMatches - which specifies the maximum // desired number of URL-type matches. const bool kOmniboxMaxURLMatchesEnabledByDefault = #if defined(OS_IOS) || defined(OS_ANDROID) false; #else true; #endif const base::Feature kOmniboxMaxURLMatches{ "OmniboxMaxURLMatches", kOmniboxMaxURLMatchesEnabledByDefault ? base::FEATURE_ENABLED_BY_DEFAULT : base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to cap max suggestions to a dynamic limit based on how many URLs // would be shown. E.g., show up to 10 suggestions if doing so would display no // URLs; else show up to 8 suggestions if doing so would include 1 or more URLs. const base::Feature kDynamicMaxAutocomplete{"OmniboxDynamicMaxAutocomplete", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, when the user clears the whole omnibox text (i.e. via Backspace), // Chrome will request remote ZeroSuggest suggestions for the OTHER page // classification (contextual web). const base::Feature kClobberTriggersContextualWebZeroSuggest{ "OmniboxClobberTriggersContextualWebZeroSuggest", base::FEATURE_DISABLED_BY_DEFAULT}; // Disable this flag to prevent focus gestures (e.g. clicks, taps, Ctrl+L) from // triggering ZeroSuggest for the OTHER page classification (contextual web). // This is used to experiment with alternate ZeroSuggest triggers like clobber. // // Note, this flag is Enabled by default, as on-focus is the standard // ZeroSuggest trigger. This flag doesn't affect the NTP or SERP. // We don't want to accidentally unlaunch on-focus NTP ZeroSuggest. const base::Feature kFocusGestureTriggersContextualWebZeroSuggest{ "OmniboxFocusGestureTriggersContextualWebZeroSuggest", base::FEATURE_ENABLED_BY_DEFAULT}; // If enabled, ranks the local zero-prefix suggestions based on frecency // (combined frequency and recency). const base::Feature kOmniboxLocalZeroSuggestFrecencyRanking{ "OmniboxLocalZeroSuggestFrecencyRanking", base::FEATURE_DISABLED_BY_DEFAULT}; // Used to adjust the age threshold since the last visit in order to consider a // normalized keyword search term as a zero-prefix suggestion. If disabled, the // default value of history::kLowQualityMatchAgeLimitInDays is used. If enabled, // the age threshold is determined by this feature's companion parameter, // OmniboxFieldTrial::kOmniboxLocalZeroSuggestAgeThresholdParam. const base::Feature kOmniboxLocalZeroSuggestAgeThreshold{ "OmniboxLocalZeroSuggestAgeThreshold", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that configures ZeroSuggestProvider using the "ZeroSuggestVariant" // per-page-classification parameter. // // Generally speaking - do NOT use this for future server-side experiments. // Instead, create your a new narrowly scoped base::Feature for each experiment. // // Because our Field Trial system can only configure this base::Feature in a // single study, and does not merge parameters, using this creates conflicts. const base::Feature kOnFocusSuggestions{"OmniboxOnFocusSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables on-focus suggestions on the Open Web, that are contextual to the // current URL. Will only work if user is signed-in and syncing, or is // otherwise eligible to send the current page URL to the suggest server. // // There's multiple flags here for multiple backend configurations: // - Default (search queries) // - On-Content Suggestions const base::Feature kOnFocusSuggestionsContextualWeb{ "OmniboxOnFocusSuggestionsContextualWeb", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOnFocusSuggestionsContextualWebOnContent{ "OmniboxOnFocusSuggestionsContextualWebOnContent", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables Reactive Zero-Prefix Suggestions (rZPS) on the NTP, for the Omnibox // and Realbox respectively. Note: enabling this feature merely makes // ZeroSuggestProvider send the request. There are additional requirements, // like the user being signed-in, and the suggest server having rZPS enabled. const base::Feature kReactiveZeroSuggestionsOnNTPOmnibox{ "OmniboxReactiveZeroSuggestionsOnNTPOmnibox", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kReactiveZeroSuggestionsOnNTPRealbox{ "OmniboxReactiveZeroSuggestionsOnNTPRealbox", base::FEATURE_DISABLED_BY_DEFAULT}; // Allow suggestions to be shown to the user on the New Tab Page upon focusing // URL bar (the omnibox). const base::Feature kZeroSuggestionsOnNTP{"OmniboxZeroSuggestionsOnNTP", base::FEATURE_ENABLED_BY_DEFAULT}; // Allow suggestions to be shown to the user on the New Tab Page upon focusing // the real search box. const base::Feature kZeroSuggestionsOnNTPRealbox{ "OmniboxZeroSuggestionsOnNTPRealbox", base::FEATURE_ENABLED_BY_DEFAULT}; // Allow on-focus query refinements to be shown on the default SERP. const base::Feature kZeroSuggestionsOnSERP{"OmniboxZeroSuggestionsOnSERP", base::FEATURE_ENABLED_BY_DEFAULT}; // Features to provide non personalized head search suggestion from a compact // on device model. More specifically, feature name with suffix Incognito / // NonIncognito will only controls behaviors under incognito / non-incognito // mode respectively. const base::Feature kOnDeviceHeadProviderIncognito{ "OmniboxOnDeviceHeadProviderIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOnDeviceHeadProviderNonIncognito{ "OmniboxOnDeviceHeadProviderNonIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, changes the way Google-provided search suggestions are scored by // the backend. Note that this Feature is only used for triggering a server- // side experiment config that will send experiment IDs to the backend. It is // not referred to in any of the Chromium code. const base::Feature kOmniboxExperimentalSuggestScoring{ "OmniboxExperimentalSuggestScoring", base::FEATURE_DISABLED_BY_DEFAULT}; // If disabled, terms with no wordstart matches disqualify the suggestion unless // they occur in the URL host. If enabled, terms with no wordstart matches are // allowed but not scored. E.g., both inputs 'java script' and 'java cript' will // match a suggestion titled 'javascript' and score equivalently. const base::Feature kHistoryQuickProviderAllowButDoNotScoreMidwordTerms{ "OmniboxHistoryQuickProviderAllowButDoNotScoreMidwordTerms", base::FEATURE_ENABLED_BY_DEFAULT}; // If disabled, midword matches are ignored except in the URL host, and input // terms with no wordstart matches are scored 0, resulting in an overall score // of 0. If enabled, midword matches are allowed and scored when they begin // immediately after the previous match ends. E.g. 'java script' will match a // suggestion titled 'javascript' but the input 'java cript' won't. const base::Feature kHistoryQuickProviderAllowMidwordContinuations{ "OmniboxHistoryQuickProviderAllowMidwordContinuations", base::FEATURE_ENABLED_BY_DEFAULT}; // If enabled, shows slightly more compact suggestions, allowing the // kAdaptiveSuggestionsCount feature to fit more suggestions on screen. const base::Feature kCompactSuggestions{"OmniboxCompactSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, defers keyboard popup when user highlights the omnibox until // the user taps the Omnibox again. extern const base::Feature kDeferredKeyboardPopup{ "OmniboxDeferredKeyboardPopup", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, expands autocompletion to possibly (depending on params) include // suggestion titles and non-prefixes as opposed to be restricted to URL // prefixes. Will also adjust the location bar UI and omnibox text selection to // accommodate the autocompletions. const base::Feature kRichAutocompletion{"OmniboxRichAutocompletion", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that enables Search Ready Omnibox in invognito. const base::Feature kOmniboxSearchReadyIncognito{ "OmniboxSearchReadyIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that puts a single row of buttons on suggestions with actionable // elements like keywords, tab-switch buttons, and Pedals. const base::Feature kOmniboxSuggestionButtonRow{ "OmniboxSuggestionButtonRow", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable Pedal suggestions. const base::Feature kOmniboxPedalSuggestions{"OmniboxPedalSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable the keyword search button. const base::Feature kOmniboxKeywordSearchButton{ "OmniboxKeywordSearchButton", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables using an Android RecyclerView to render the suggestions dropdown // instead of a ListView. const base::Feature kOmniboxSuggestionsRecyclerView{ "OmniboxSuggestionsRecyclerView", base::FEATURE_DISABLED_BY_DEFAULT}; // Allows long Omnibox suggestions to wrap around to next line. const base::Feature kOmniboxSuggestionsWrapAround{ "OmniboxSuggestionsWrapAround", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, uses WebUI to render the omnibox suggestions popup, similar to // how the NTP "fakebox" is implemented. const base::Feature kWebUIOmniboxPopup{"WebUIOmniboxPopup", base::FEATURE_DISABLED_BY_DEFAULT}; // When enabled, use Assistant for omnibox voice query recognition instead of // Android's built-in voice recognition service. Only works on Android. const base::Feature kOmniboxAssistantVoiceSearch{ "OmniboxAssistantVoiceSearch", base::FEATURE_DISABLED_BY_DEFAULT}; // When enabled, provides an omnibox context menu option that prevents URL // elisions. const base::Feature kOmniboxContextMenuShowFullUrls{ "OmniboxContextMenuShowFullUrls", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to reveal the path, query and ref from steady state URLs // on hover. const base::Feature kRevealSteadyStateUrlPathQueryAndRefOnHover{ "OmniboxUIExperimentRevealSteadyStateUrlPathQueryAndRefOnHover", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to hide the path, query and ref from steady state URLs // on interaction with the page. const base::Feature kHideSteadyStateUrlPathQueryAndRefOnInteraction{ "OmniboxUIExperimentHideSteadyStateUrlPathQueryAndRefOnInteraction", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to possibly elide not just the path, query, and ref from steady // state URLs, but also subdomains beyond the registrable domain, depending on // whether the hostname fails lookalike checks. Has no effect unless // kRevealSteadyStateUrlPathQueryAndRefOnHover and/or // kHideSteadyStateUrlPathQueryAndRefOnInteraction are enabled. const base::Feature kMaybeElideToRegistrableDomain{ "OmniboxUIExperimentElideToRegistrableDomain", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace omnibox
46.892944
80
0.775074
[ "render", "model" ]
2343f887a683d812e4989b96b056d37b1cfccf45
1,867
cpp
C++
main/maximal-square/maximal-square.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/maximal-square/maximal-square.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/maximal-square/maximal-square.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
class Solution { public: static int maximalSquare(const vector<vector<char>>& matrix); }; namespace { vector<vector<int>> make_grid(const int height, const int width) { return vector<vector<int>>(height, vector<int>(width)); } } int Solution::maximalSquare(const vector<vector<char>>& matrix) { const auto height = static_cast<int>(matrix.size()); if (!height) return 0; const auto width = static_cast<int>(matrix.front().size()); if (!width) return 0; assert(height > 0 && width > 0); auto vertical = make_grid(height, width); auto horizontal = make_grid(height, width); auto square = make_grid(height, width); auto acc = 0; // top-left corner (i = 0, j = 0) if (matrix[0][0] != '0') vertical[0][0] = horizontal[0][0] = square[0][0] = acc = 1; // rest of the topmost row (i = 0, j > 0) for (auto j = 1; j != width; ++j) { if (matrix[0][j] != '0') { vertical[0][j] = square[0][j] = acc = 1; horizontal[0][j] = horizontal[0][j - 1] + 1; } } for (auto i = 1; i != height; ++i) { // rest of the leftmost column (i > 0, j = 0) if (matrix[i][0] != '0') { vertical[i][0] = vertical[i - 1][0] + 1; horizontal[i][0] = square[i][0] = 1; acc = max(acc, 1); } // rest of the matrix (i > 0, j > 0) for (auto j = 1; j != width; ++j) { if (matrix[i][j] != '0') { vertical[i][j] = vertical[i - 1][j] + 1; horizontal[i][j] = horizontal[i][j - 1] + 1; square[i][j] = min({vertical[i][j], horizontal[i][j], square[i - 1][j - 1] + 1}); acc = max(acc, square[i][j]); } } } return acc * acc; }
29.634921
68
0.476165
[ "vector" ]
234554d697507aeabb1473dbbfb7f0599dcf0f65
8,271
cpp
C++
ev_apps/tls_client/tls_client.cpp
shpal2000/tlspack
37fa976f55df452745ee4e2dfcdba86facdb2529
[ "MIT" ]
null
null
null
ev_apps/tls_client/tls_client.cpp
shpal2000/tlspack
37fa976f55df452745ee4e2dfcdba86facdb2529
[ "MIT" ]
null
null
null
ev_apps/tls_client/tls_client.cpp
shpal2000/tlspack
37fa976f55df452745ee4e2dfcdba86facdb2529
[ "MIT" ]
null
null
null
#include "tls_client.hpp" tls_client_app::tls_client_app(json app_json , tls_client_stats* zone_app_stats , ev_sockstats* zone_sock_stats) { client_config_init (app_json); m_app_stats = new tls_client_stats(); auto cs_grp_list = app_json["cs_grp_list"]; m_cs_group_count = 0; m_cs_group_index = 0; for (auto it = cs_grp_list.begin(); it != cs_grp_list.end(); ++it) { auto cs_grp_cfg = it.value (); const char* cs_grp_label = cs_grp_cfg["cs_grp_label"].get<std::string>().c_str(); int cs_grp_enable = cs_grp_cfg["enable"].get<int>(); if (cs_grp_enable == 0) { continue; } tls_client_stats* cs_grp_stats = new tls_client_stats(); set_app_stats (cs_grp_stats, cs_grp_label); std::vector<ev_sockstats*> *cs_grp_stats_arr = new std::vector<ev_sockstats*> (); cs_grp_stats_arr->push_back (cs_grp_stats); cs_grp_stats_arr->push_back (m_app_stats); cs_grp_stats_arr->push_back (zone_app_stats); cs_grp_stats_arr->push_back (zone_sock_stats); tls_client_cs_grp* next_cs_grp = new tls_client_cs_grp (cs_grp_cfg, cs_grp_stats_arr); next_cs_grp->m_ssl_ctx = SSL_CTX_new(TLS_client_method()); int status = 0; if (next_cs_grp->m_version == sslv3) { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, SSL3_VERSION); status = SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, SSL3_VERSION); } else if (next_cs_grp->m_version == tls1) { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, TLS1_VERSION); status = SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, TLS1_VERSION); } else if (next_cs_grp->m_version == tls1_1) { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, TLS1_1_VERSION); status = SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, TLS1_1_VERSION); } else if (next_cs_grp->m_version == tls1_2) { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, TLS1_2_VERSION); status = SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, TLS1_2_VERSION); } else if (next_cs_grp->m_version == tls1_3) { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, TLS1_3_VERSION); } else { status = SSL_CTX_set_min_proto_version (next_cs_grp->m_ssl_ctx, SSL3_VERSION); status = SSL_CTX_set_max_proto_version (next_cs_grp->m_ssl_ctx, TLS1_3_VERSION); } if (status){ } if (next_cs_grp->m_version == tls_all) { next_cs_grp->m_cipher2 = cs_grp_cfg["cipher2"].get<std::string>().c_str(); SSL_CTX_set_ciphersuites (next_cs_grp->m_ssl_ctx , next_cs_grp->m_cipher2.c_str()); SSL_CTX_set_cipher_list (next_cs_grp->m_ssl_ctx , next_cs_grp->m_cipher.c_str()); } else if (next_cs_grp->m_version == tls1_3) { SSL_CTX_set_ciphersuites (next_cs_grp->m_ssl_ctx , next_cs_grp->m_cipher.c_str()); } else { SSL_CTX_set_cipher_list (next_cs_grp->m_ssl_ctx , next_cs_grp->m_cipher.c_str()); } SSL_CTX_set_verify(next_cs_grp->m_ssl_ctx, SSL_VERIFY_NONE, 0); SSL_CTX_set_mode(next_cs_grp->m_ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE); SSL_CTX_set_session_cache_mode(next_cs_grp->m_ssl_ctx , SSL_SESS_CACHE_OFF); status = SSL_CTX_set1_groups_list(next_cs_grp->m_ssl_ctx , "P-521:P-384:P-256"); SSL_CTX_set_dh_auto(next_cs_grp->m_ssl_ctx, 1); m_cs_groups.push_back (next_cs_grp); m_cs_group_count++; } } tls_client_app::~tls_client_app() { } void tls_client_app::run_iter(bool tick_sec) { if (m_cs_group_count == 0){ return; } ev_app::run_iter (tick_sec); if (tick_sec) { m_app_stats->tick_sec(); } for (int i=0; i < get_new_conn_count(); i++) { tls_client_cs_grp* cs_grp = m_cs_groups [m_cs_group_index]; m_cs_group_index++; if (m_cs_group_index == m_cs_group_count) { m_cs_group_index = 0; } ev_sockaddrx* client_addr = cs_grp->get_next_clnt_addr (); if (client_addr) { tls_client_socket* client_socket = (tls_client_socket*) new_tcp_connect (&client_addr->m_addr , cs_grp->get_server_addr() , cs_grp->m_stats_arr , client_addr->m_portq , &cs_grp->m_sock_opt); if (client_socket) { m_client_curr_conn_count++; client_socket->m_app = this; client_socket->m_cs_grp = cs_grp; } else { printf ("new_tcp_connect fail!\n"); } } else { printf ("get_next_clnt_addr fail!\n"); } } } ev_socket* tls_client_app::alloc_socket() { return new tls_client_socket(); } void tls_client_app::free_socket(ev_socket* ev_sock) { delete ev_sock; } void tls_client_socket::ssl_init () { m_ssl = SSL_new (m_cs_grp->m_ssl_ctx); if (m_ssl){ set_as_ssl_client (m_ssl); SSL_set_tlsext_host_name (m_ssl, "www.google.com"); } else { //stats abort (); } } void tls_client_socket::on_establish () { // printf ("on_establish\n"); ssl_init (); } void tls_client_socket::on_write () { // printf ("on_write\n"); if (m_bytes_written < m_cs_grp->m_cs_data_len) { int next_chunk = m_cs_grp->m_cs_data_len - m_bytes_written; int next_chunk_target = m_cs_grp->m_write_chunk; if (next_chunk_target == 0) { next_chunk_target = m_app->get_next_chunk_size (); } if ( next_chunk > next_chunk_target){ next_chunk = next_chunk_target; } if ( next_chunk > m_cs_grp->m_write_buffer_len){ next_chunk = m_cs_grp->m_write_buffer_len; } write_next_data (m_cs_grp->m_write_buffer, 0, next_chunk, true); } else { disable_wr_notification (); } } void tls_client_socket::on_wstatus (int bytes_written, int write_status) { // printf ("on_wstatus\n"); if (write_status == WRITE_STATUS_NORMAL) { m_bytes_written += bytes_written; if (m_bytes_written == m_cs_grp->m_cs_data_len) { if (m_cs_grp->m_close == close_reset){ abort (); } else { switch (m_cs_grp->m_close_notify) { case close_notify_no_send: write_close (); break; case close_notify_send: write_close (SSL_SEND_CLOSE_NOTIFY); break; case close_notify_send_recv: write_close (SSL_SEND_RECEIVE_CLOSE_NOTIFY); break; } } } } else { abort (); } } void tls_client_socket::on_read () { // printf ("on_read\n"); read_next_data (m_cs_grp->m_read_buffer, 0, m_cs_grp->m_read_buffer_len, true); } void tls_client_socket::on_rstatus (int bytes_read, int read_status) { // printf ("on_rstatus\n"); if (bytes_read == 0) { if (read_status != READ_STATUS_TCP_CLOSE) { abort (); } } else { m_bytes_read += bytes_read; } } void tls_client_socket::on_finish () { // printf ("on_free\n"); if (m_ssl) { SSL_free (m_ssl); m_ssl = nullptr; } }
31.329545
99
0.571636
[ "vector" ]
2345bc6d1610ba6523c368a723a49d87bc0d2fbb
12,386
cpp
C++
src/script/standard.cpp
commerceblock/elements
7c11ad9caf541e94e6100a9daae100efe1fbc85c
[ "MIT" ]
11
2018-05-04T17:29:53.000Z
2020-08-08T22:03:59.000Z
src/script/standard.cpp
commerceblock/elements
7c11ad9caf541e94e6100a9daae100efe1fbc85c
[ "MIT" ]
160
2018-04-20T16:45:33.000Z
2021-02-20T15:17:10.000Z
src/script/standard.cpp
commerceblock/elements
7c11ad9caf541e94e6100a9daae100efe1fbc85c
[ "MIT" ]
3
2019-03-28T06:44:24.000Z
2020-01-22T20:27:04.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "validation.h" #include <boost/foreach.hpp> using namespace std; typedef vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; bool fAcceptRegisteraddress = DEFAULT_ACCEPT_REGISTERADDRESS; unsigned nMaxRegisteraddressBytes = MAX_OP_REGISTERADDRESS_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_REGISTERADDRESS_V0: return "registeraddress_v0"; case TX_DEREGISTERADDRESS_V0: return "deregisteraddress_v0"; case TX_REGISTERADDRESS_V1: return "registeraddress_v1"; case TX_DEREGISTERADDRESS_V1: return "deregisteraddress_v1"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; case TX_TRUE: return "true"; case TX_FEE: return "fee"; case TX_LOCKED_MULTISIG: return "lockedmultisig"; } return NULL; } /** Check push data opcode is between 1 and 5 bytes for OP_CHECKLOCKTIMEVERIFY argument */ static constexpr bool IsCheckLockTimeSize(opcodetype opcode) { return opcode >=1 && opcode <= 5; } static bool MatchLocked(const CScript& script, valtype& locktime) { opcodetype opcode1; vector<unsigned char> vch1; CScript::const_iterator pc1 = script.begin(); // Attempt to parse locktime parameter of OP_CHECKLOCKTIMEVERIFY if (!script.GetOp(pc1, opcode1, vch1)) return false; if (IsCheckLockTimeSize(opcode1) && script.size() >= (size_t)(3 + opcode1) && script[1 + opcode1] == OP_CHECKLOCKTIMEVERIFY && script[2 + opcode1] == OP_DROP) { const CScriptNum nLockTime(vch1, true, 5); locktime = nLockTime.getvch(); return true; } return false; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } if (scriptPubKey == CScript()) { typeRet = TX_FEE; return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == 20) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == 32) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } return false; } //Register address transaction std::vector<unsigned char> radata; int raversion; bool rawhitelist; if(scriptPubKey.IsRegisteraddress(raversion, radata, rawhitelist)){ if(raversion == 0){ if(rawhitelist){ typeRet = TX_REGISTERADDRESS_V0; } else { typeRet = TX_DEREGISTERADDRESS_V0; } } else if(raversion == 1){ if(rawhitelist){ typeRet = TX_REGISTERADDRESS_V1; } else { typeRet = TX_DEREGISTERADDRESS_V1; } } vSolutionsRet.push_back(radata); return true; } if (scriptPubKey == CScript() << OP_TRUE) { typeRet = TX_TRUE; return true; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } // Before checking for multisig, check if script is locked and if that is // the case skip the LOCKTIME OP_CHECKLOCKTIMEVERIFY OP_DROP of the script bool fIsLocked = false; CScript scriptPubKeyLocked; if (MatchLocked(scriptPubKey, data)) { fIsLocked = true; scriptPubKeyLocked = CScript(scriptPubKey.begin() + 3 + data.size(), scriptPubKey.end()); vSolutionsRet.push_back(std::move(data)); // push lock time data } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(fIsLocked ? scriptPubKeyLocked : scriptPubKey, required, keys)) { typeRet = fIsLocked ? TX_LOCKED_MULTISIG : TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA || typeRet == TX_FEE || typeRet == TX_REGISTERADDRESS_V0 || typeRet == TX_DEREGISTERADDRESS_V0 || typeRet == TX_REGISTERADDRESS_V1 || typeRet == TX_DEREGISTERADDRESS_V1){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); BOOST_FOREACH(const CPubKey& key, keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { unsigned char h160[20]; CHash160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160); ret << OP_0 << std::vector<unsigned char>(&h160[0], &h160[20]); return ret; } else if (typ == TX_PUBKEYHASH) { ret << OP_0 << vSolutions[0]; return ret; } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); ret << OP_0 << ToByteVector(hash); return ret; }
32.339426
160
0.650896
[ "vector" ]