blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
8e52c41b4ef6752e827ee75e017dcdaf79d44b63
a48b49c869283d4fbd6902f30c6df0fa922bfdb6
/oldSocialHat/SocialHat.ino
032c45fd1779c38fa356ba60c5320acf4c074522
[]
no_license
jakeschievink/SocialHat
2fbb941afa6eb19bfedd8bc508ca61918946bb11
33c94832649d4f14c504e353b2ba3f27bc25fceb
refs/heads/master
2020-05-18T01:06:11.810953
2014-11-01T23:19:55
2014-11-01T23:19:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,227
ino
#include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <EEPROM.h> #include "EEPROMAnything.h" #include "Scroll.h" #include "Pictures.cpp" Scroll scrollscreen(9, 10, 11, 13, 12); char message[200]; bool imagedisplayed = false; bool interTrigger = false; typedef enum {SCROLL, IMAGE} mode; const int buttonPin = 8; const unsigned char* pictures[] = {oledtest, Google, CopyLeft}; uint pictureCounter = 0; mode currentmode = SCROLL; void setup() { Serial.begin(9600); pinMode(buttonPin, INPUT); attachInterrupt(buttonPin, stateChange, HIGH); scrollscreen.init(); EEPROM_readAnything(1, message); scrollscreen.setMessage(message); Serial.println(message); } void loop() { if(currentmode == SCROLL){ scrollscreen.startScroll(); checkSerial(); } if(currentmode == IMAGE && !imagedisplayed){ displayImage(); imagedisplayed = true; } if(interTrigger == true){ delay(10); interTrigger = false; imagedisplayed = false; if(currentmode == IMAGE){ currentmode = SCROLL; }else{ currentmode = IMAGE; } } } void displayImage(){ scrollscreen.disp.clearDisplay(); scrollscreen.disp.drawBitmap(0,0, pictures[pictureCounter], 128, 64, 1); if(pictureCounter < (sizeof(pictures)/ sizeof(pictures[0]))-1){ pictureCounter++; }else{ pictureCounter=0; } scrollscreen.disp.display(); } void stateChange(){ interTrigger = true; } void checkSerial(){ bool firstRead = false; char option; char tmpMsg[200]; if(Serial.available() > 0){ if(!firstRead){ option = Serial.read(); firstRead = true; Serial.println(option); } recieveChars().toCharArray(tmpMsg, 100); Serial.print(tmpMsg); scrollscreen.setMessage(tmpMsg); Serial.println(EEPROM_writeAnything(1, tmpMsg)); } } String recieveChars(){ String content = ""; char character; while(Serial.available()) { character = Serial.read(); content.concat(character); Serial.println((byte)character); } if(content != ""){ return content; } }
[ "jakeschievink@gmail.com" ]
jakeschievink@gmail.com
2a8fae1a8ed8c2dc5f464711bb82a26f1dc2bab1
5a8b9a20f7c498981eb4ea33c1cba4b9554440b4
/Xindows/src/site/text/selrensv.h
9522be36edd1bd9f2c8eef281799775a838b306a
[]
no_license
mensong/IE5.5_vs2008
82ae91b3e45d312589b6fb461ceef5608dfb2f6b
6149654180d0f422355e38b0c5d8e84e6e8c6a0c
refs/heads/master
2022-05-01T07:32:15.727457
2018-11-14T03:07:51
2018-11-14T03:07:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,623
h
#ifndef __XINDOWS_SITE_TEXT_SELRENSV_H__ #define __XINDOWS_SITE_TEXT_SELRENSV_H__ int OldCompare ( IMarkupPointer * p1, IMarkupPointer * p2 ); struct PointerSegment { CMarkupPointer* _pStart; CMarkupPointer* _pEnd; HIGHLIGHT_TYPE _HighlightType; int _cpStart; int _cpEnd; BOOL _fFiredSelectionNotify; // Has the SelectionNotification been fired on this segment }; struct HighlightSegment { int _cpStart; int _cpEnd; DWORD _dwHighlightType; }; #define WM_BEGINSELECTION (WM_USER+1201) // Posted by Selection to say we've begun a selection #define START_TEXT_SELECTION 1 #define START_CONTROL_SELECTION 2 class CSelectionRenderingServiceProvider { public: DECLARE_MEMCLEAR_NEW_DELETE() CSelectionRenderingServiceProvider(CDocument* pDoc); ~CSelectionRenderingServiceProvider(); // ISelectionRenderServices Interface STDMETHOD(AddSegment)( IMarkupPointer* pStart, IMarkupPointer* pEnd, HIGHLIGHT_TYPE HighlightType, int* iSegmentIndex); STDMETHOD(AddElementSegment)( IHTMLElement* pElement, int* iSegmentIndex); STDMETHOD(MovePointersToSegment)( int iSegmentIndex, IMarkupPointer* pStart, IMarkupPointer* pEnd); STDMETHOD(GetElementSegment)( int iSegmentIndex, IHTMLElement** ppElement); STDMETHOD(MoveSegmentToPointers)( int iSegmentIndex, IMarkupPointer* pStart, IMarkupPointer* pEnd, HIGHLIGHT_TYPE HighlightType); STDMETHOD(SetElementSegment)( int iSegmentIndex, IHTMLElement* pElement); STDMETHOD( GetSegmentCount)( int* piSegmentCount, SELECTION_TYPE* peType); STDMETHOD(ClearSegment)( int iSegmentIndex, BOOL fInvalidate); STDMETHOD(ClearSegments)(BOOL fInvalidate); STDMETHOD(ClearElementSegments)(); VOID GetSelectionChunksForLayout( CFlowLayout* pFlowLayout, CPtrAry<HighlightSegment*>* paryHighlight, int* pCpMin, int* pCpMax); HRESULT InvalidateSegment( CMarkupPointer* pStart, CMarkupPointer*pEnd, CMarkupPointer* pNewStart, CMarkupPointer* pNewEnd , BOOL fSelected, BOOL fFireOM=TRUE); HRESULT UpdateSegment( CMarkupPointer* pOldStart, CMarkupPointer* pOldEnd, CMarkupPointer* pNewStart, CMarkupPointer* pNewEnd); BOOL IsElementSelected(CElement* pElement); CElement* GetSelectedElement(int iElementIndex); HRESULT GetFlattenedSelection( int iSegmentIndex, int& cpStart, int& cpEnd, SELECTION_TYPE& eType); VOID HideSelection(); VOID ShowSelection(); VOID InvalidateSelection(BOOL fSelectionOn, BOOL fFireOM); private: VOID ConstructSelectionRenderCache(); BOOL IsLayoutCompletelyEnclosed( CLayout* pLayout, CMarkupPointer* pStart, CMarkupPointer* pEnd); CDocument* _pDoc; CPtrAry<PointerSegment*>* _parySegment; // Array of all segments CPtrAry<CElement*>* _paryElementSegment; // Array of Element Segments. HRESULT NotifyBeginSelection(WPARAM wParam); long _lContentsVersion; // Use this to compare when we need to invalidate BOOL _fSelectionVisible:1; // Is Selection Visible ? BOOL _fPendingInvalidate:1; // Pending Invalidation. BOOL _fPendingFireOM:1; // Value for fFireOM on Pending Inval. BOOL _fInUpdateSegment:1; // Are we updating the segments. }; #endif //__XINDOWS_SITE_TEXT_SELRENSV_H__
[ "mail0668@gmail.com" ]
mail0668@gmail.com
e4f9283d1f122b5342e17a597ce18e4d26591a3c
5e0e71cfae09eaac12d8fe929eda9b1d0630764e
/AADC/src/aadcUser/MarkerDetector/stdafx.h
8bb5f6de2e3aea58f255edc4c9d42488236292d6
[ "BSD-2-Clause" ]
permissive
viettung92/AADC
418232e01587757e17e036f146167e037fef069c
ac25f2a7e66ef9d8f9430921baf6ddcac97d6540
refs/heads/master
2020-10-02T02:25:24.123886
2020-01-15T14:57:53
2020-01-15T14:57:53
227,669,243
1
0
null
null
null
null
UTF-8
C++
false
false
2,202
h
/********************************************************************* Copyright (c) 2018 Audi Autonomous Driving Cup. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: ?This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.? 4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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. **********************************************************************/ #pragma once #ifdef WIN32 #include <windows.h> #endif //adtf #include <adtf3.h> #include <adtf_platform_inc.h> #include <a_utils_platform_inc.h> #include <adtf_systemsdk.h> #include <stdlib.h> #include <opencv2/opencv.hpp> #include <opencv2/aruco.hpp> #include <aadc_structs.h> #include <aadc_user_structs.h> //user includes #include <aadc_types.h> using namespace std;
[ "hoang.viettung@gmx.de" ]
hoang.viettung@gmx.de
e15e0190faaa4749c2d9e144a8a911437b95660a
8291fc32d222d7cd8f4ff8cd3179ce63181cafdc
/cpp_module_05/ex03/Bureaucrat.cpp
170580d0c0001a99d6c9b7df852d2b3fc7552173
[]
no_license
FrenkenFlores/CPP_Module
d09d5b15ee79053c2d817492e9b9102fb0b56078
8d9458cb02bd2c4e67febe9df46d502772e6d627
refs/heads/main
2023-04-10T08:11:56.738638
2021-04-14T22:22:41
2021-04-14T22:22:41
344,802,483
0
0
null
null
null
null
UTF-8
C++
false
false
3,215
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Bureaucrat.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fflores <fflores@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/30 06:06:24 by fflores #+# #+# */ /* Updated: 2021/03/30 06:06:25 by fflores ### ########.fr */ /* */ /* ************************************************************************** */ #include "Bureaucrat.hpp" Bureaucrat::Bureaucrat() { std::cout << "Default constructor called " << std::endl; return; } Bureaucrat::Bureaucrat(std::string name, int grade) : _name(name), _grade(grade) { if (_grade < 1) throw GradeTooHighException(); else if (_grade > 150) throw GradeTooLowException(); std::cout << "Constructor called " << std::endl; return; } Bureaucrat::Bureaucrat(const Bureaucrat &src) : _name(src.getName()), _grade(src.getGrade()){ if (_grade < 1) throw GradeTooHighException(); else if (_grade > 150) throw GradeTooLowException(); std::cout << "Copy constructor called " << std::endl; return; } Bureaucrat & Bureaucrat::operator=(const Bureaucrat &rhs) { _grade = rhs._grade; if (_grade < 1) throw GradeTooHighException(); else if (_grade > 150) throw GradeTooLowException(); std::cout << "Assignation operator called " << std::endl; return (*this); } std::ostream & operator<<(std::ostream &out, const Bureaucrat &src) { out << "<" << src.getName() << "> has grade <" << src.getGrade() << ">" << std::endl; return (out); } Bureaucrat::~Bureaucrat() { std::cout << "Destructor called " << std::endl; return; } std::string Bureaucrat::getName() const{ return (_name); } int Bureaucrat::getGrade() const{ return (_grade); } void Bureaucrat::setGrade(int grade) { _grade = grade; return ; } void Bureaucrat::incrementGrade() { _grade--; if (_grade < 1) throw GradeTooHighException(); std::cout << "Grade been incremented and it equals " << getGrade() << std::endl; return; } void Bureaucrat::decrementGrade() { _grade++; if (_grade > 150) throw GradeTooLowException(); std::cout << "Grade been decremented and it equals " << getGrade() << std::endl; return; } void Bureaucrat::signForm(Form &form) { if (_grade <= form.getSignGrade()) { form.beSigned(*this); std::cout << "<" << _name << "> signs <" << form.getTarget() << ">" << std::endl; } else std::cout << "<" << _name << "> can't sign <" << form.getTarget() << "> because the form needs a higher grade" << std::endl; return; } void Bureaucrat::executeForm(Form const &form) { try { std::cout << "<" << _name << "> executes <" << form.getTarget() << ">" << std::endl; form.execute(*this); } catch(const std::exception& e) { std::cout << e.what() << std::endl; } }
[ "saifualdin.evloev@gmail.com" ]
saifualdin.evloev@gmail.com
fc9cfb96b5077731a05df4c864ec915e9704957d
e5b48f9f4669f050d6fd699e7f4f4566c9c52402
/GroupEntry.cpp
14ebc5e8784cec3e5d936f9b78d67f9fca6790ee
[]
no_license
sayrun/SOboe
f3b3a6e6fb789098d9482651d903eacff5d4f931
787348ce2b6ffaa21219fc41e350750290bad2f7
refs/heads/master
2021-01-10T04:02:46.603279
2016-04-08T21:47:59
2016-04-08T21:47:59
50,247,995
0
0
null
null
null
null
UTF-8
C++
false
false
2,253
cpp
#include "stdafx.h" #include "SOboe.h" #include "GroupEntry.h" BOOL CGroupData::SetGroupData( const GROUPDATA* pstGroupData, int nSize) { if( NULL == pstGroupData)return FALSE; if( nSize < pstGroupData->nSize)return FALSE; if( _GROUPSTRUCT_VER100 < pstGroupData->unStructVersion)return FALSE; m_nParentGroup = pstGroupData->nParentGroup; m_nGroupStatus = pstGroupData->nGroupStatus; m_cStrGroupName = &( ( LPCSTR)pstGroupData)[ pstGroupData->nOffsetGroupName]; if( m_cStrGroupName.IsEmpty()) { m_nParentGroup = -1; return FALSE; } return TRUE; } BOOL CEntryData::SetEntryData( const ENTRYDATA* pstEntryData, int nSize) { if( NULL == pstEntryData)return FALSE; if( nSize < pstEntryData->nSize)return FALSE; if( _ENTRYSTRUCT_VER100 < pstEntryData->unStructVersion)return FALSE; if( m_pstEntryData) { free( m_pstEntryData); m_pstEntryData = NULL; m_nEntryDataSize = 0; } m_pstEntryData = ( ENTRYDATA*)malloc( nSize); if( m_pstEntryData) { m_nEntryDataSize = nSize; CopyMemory( m_pstEntryData, pstEntryData, nSize); return TRUE; } return FALSE; } BOOL CEntryData::operator==( const CEntryData& cEntryData) const { if( NULL == m_pstEntryData && NULL == cEntryData.m_pstEntryData)return TRUE; if( NULL == m_pstEntryData)return FALSE; if( NULL == cEntryData.m_pstEntryData)return FALSE; // if( m_pstEntryData->nSize != cEntryData.m_pstEntryData->nSize)return FALSE; if( GetNxlID() != cEntryData.GetNxlID())return FALSE; CSOboeApp* pcSOboe = ( CSOboeApp*)AfxGetApp(); ASSERT( pcSOboe); CNetExLib* pcNetExLib; pcNetExLib = pcSOboe->GetNetExLib( pcSOboe->FindNxlID( GetNxlID())); if( pcNetExLib) { return pcNetExLib->CompareEntryData( *this, cEntryData); } return FALSE; } const CEntryData& CEntryData::operator=( const CEntryData& cEntryData) { if( m_pstEntryData) { free( m_pstEntryData); m_pstEntryData = NULL; m_nEntryDataSize = 0; } if( NULL != cEntryData.m_pstEntryData) { if( 0 < cEntryData.m_nEntryDataSize) { m_pstEntryData = ( ENTRYDATA*)malloc( cEntryData.m_nEntryDataSize); if( m_pstEntryData) { m_nEntryDataSize = cEntryData.m_nEntryDataSize; CopyMemory( m_pstEntryData, cEntryData.m_pstEntryData, cEntryData.m_nEntryDataSize); } } } return *this; }
[ "sayrun@hotmail.co.jp" ]
sayrun@hotmail.co.jp
bf9274f25d4fd06e54a9cd469ad293b8a3eb6e2a
9eed36ccf2be5585685f9531e595c1d14fd8ef76
/extern/3rd/PcapPlusPlus-19.12/Pcap++/src/RawSocketDevice.cpp
c44590723929610ba0b9e6913a62f40b132eb6cb
[ "WTFPL", "Unlicense" ]
permissive
Cyweb-unknown/eft-packet-1
756ab75b96e658a0b2044e09389b7a06d285c971
925da44fc1f49e4fe6b17e79248714ada4ea451d
refs/heads/master
2022-10-27T11:47:09.454465
2020-06-13T14:41:43
2020-06-13T14:41:43
272,038,457
1
1
WTFPL
2020-06-13T15:46:17
2020-06-13T15:46:16
null
UTF-8
C++
false
false
13,573
cpp
#include "RawSocketDevice.h" #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) #include <winsock2.h> #include <ws2tcpip.h> #endif #ifdef LINUX #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <linux/if_ether.h> #include <netpacket/packet.h> #include <ifaddrs.h> #include <net/if.h> #endif #include <string.h> #include "Logger.h" #include "IpUtils.h" #include "SystemUtils.h" #include "Packet.h" #include "EthLayer.h" namespace pcpp { #define RAW_SOCKET_BUFFER_LEN 65536 #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) #ifndef SIO_RCVALL /* SIO_RCVALL defined on w2k and later. Not defined in Mingw32 */ /* 0x98000001 = _WSAIOW(IOC_VENDOR,1) */ # define SIO_RCVALL 0x98000001 #endif // SIO_RCVALL class WinSockInitializer { private: static bool m_IsInitialized; public: static void initialize() { if (m_IsInitialized) return; // Load Winsock WSADATA wsaData; int res = WSAStartup(MAKEWORD(2,2), &wsaData); if (res != 0) { LOG_ERROR("WSAStartup failed with error code: %d", res); m_IsInitialized = false; } m_IsInitialized = true; } }; bool WinSockInitializer::m_IsInitialized = false; #endif // defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) struct SocketContainer { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) SOCKET fd; #elif LINUX int fd; int interfaceIndex; std::string interfaceName; #endif }; RawSocketDevice::RawSocketDevice(const IPAddress& interfaceIP) : IDevice(), m_Socket(NULL) { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) WinSockInitializer::initialize(); m_InterfaceIP = interfaceIP.clone(); m_SockFamily = (m_InterfaceIP->getType() == IPAddress::IPv4AddressType ? IPv4 : IPv6); #elif LINUX m_InterfaceIP = interfaceIP.clone(); m_SockFamily = Ethernet; #else m_InterfaceIP = NULL; m_SockFamily = Ethernet; #endif } RawSocketDevice::~RawSocketDevice() { close(); if (m_InterfaceIP != NULL) delete m_InterfaceIP; } RawSocketDevice::RecvPacketResult RawSocketDevice::receivePacket(RawPacket& rawPacket, bool blocking, int timeout) { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) if (!isOpened()) { LOG_ERROR("Device is not open"); return RecvError; } SOCKET fd = ((SocketContainer*)m_Socket)->fd; char* buffer = new char[RAW_SOCKET_BUFFER_LEN]; memset(buffer, 0, RAW_SOCKET_BUFFER_LEN); // value of 0 timeout means disabling timeout if (timeout < 0) timeout = 0; u_long blockingMode = (blocking? 0 : 1); ioctlsocket(fd, FIONBIO, &blockingMode); DWORD timeoutVal = timeout * 1000; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeoutVal, sizeof(timeoutVal)); //recvfrom(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0, (struct sockaddr*)&sockAddr,(socklen_t*)&sockAddrLen); int bufferLen = recv(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0); if (bufferLen < 0) { delete [] buffer; int errorCode = 0; RecvPacketResult error = getError(errorCode); if (error == RecvError) LOG_ERROR("Error reading from recvfrom. Error code is %d", errorCode); return error; } if (bufferLen > 0) { timeval time; gettimeofday(&time, NULL); rawPacket.setRawData((const uint8_t*)buffer, bufferLen, time, LINKTYPE_DLT_RAW1); return RecvSuccess; } LOG_ERROR("Buffer length is zero"); delete [] buffer; return RecvError; #elif LINUX if (!isOpened()) { LOG_ERROR("Device is not open"); return RecvError; } int fd = ((SocketContainer*)m_Socket)->fd; char* buffer = new char[RAW_SOCKET_BUFFER_LEN]; memset(buffer, 0, RAW_SOCKET_BUFFER_LEN); // value of 0 timeout means disabling timeout if (timeout < 0) timeout = 0; // set blocking or non-blocking flag int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { LOG_ERROR("Cannot get socket flags"); return RecvError; } flags = (blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK)); if (fcntl(fd, F_SETFL, flags) != 0) { LOG_ERROR("Cannot set socket non-blocking flag"); return RecvError; } // set timeout on socket struct timeval timeoutVal; timeoutVal.tv_sec = timeout; timeoutVal.tv_usec = 0; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeoutVal, sizeof(timeoutVal)); int bufferLen = recv(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0); if (bufferLen < 0) { delete [] buffer; int errorCode = errno; RecvPacketResult error = getError(errorCode); if (error == RecvError) LOG_ERROR("Error reading from recvfrom. Error code is %d", errorCode); return error; } if (bufferLen > 0) { timeval time; gettimeofday(&time, NULL); rawPacket.setRawData((const uint8_t*)buffer, bufferLen, time, LINKTYPE_ETHERNET); return RecvSuccess; } LOG_ERROR("Buffer length is zero"); delete [] buffer; return RecvError; #else LOG_ERROR("Raw socket are not supported on this platform"); return RecvError; #endif } int RawSocketDevice::receivePackets(RawPacketVector& packetVec, int timeout, int& failedRecv) { if (!isOpened()) { LOG_ERROR("Device is not open"); return 0; } long curSec, curNsec; clockGetTime(curSec, curNsec); int packetCount = 0; failedRecv = 0; long timeoutSec = curSec + timeout; while (curSec < timeoutSec) { RawPacket* rawPacket = new RawPacket(); if (receivePacket(*rawPacket, true, timeoutSec-curSec) == RecvSuccess) { packetVec.pushBack(rawPacket); packetCount++; } else { failedRecv++; delete rawPacket; } clockGetTime(curSec, curNsec); } return packetCount; } bool RawSocketDevice::sendPacket(const RawPacket* rawPacket) { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) LOG_ERROR("Sending packets with raw socket are not supported on Windows"); return 0; #elif LINUX if (!isOpened()) { LOG_ERROR("Device is not open"); return false; } Packet packet((RawPacket*)rawPacket, OsiModelDataLinkLayer); if (!packet.isPacketOfType(pcpp::Ethernet)) { LOG_ERROR("Can't send non-Ethernet packets"); return false; } int fd = ((SocketContainer*)m_Socket)->fd; sockaddr_ll addr; memset(&addr, 0, sizeof(struct sockaddr_ll)); addr.sll_family = htons(PF_PACKET); addr.sll_protocol = htons(ETH_P_ALL); addr.sll_halen = 6; addr.sll_ifindex = ((SocketContainer*)m_Socket)->interfaceIndex; EthLayer* ethLayer = packet.getLayerOfType<EthLayer>(); MacAddress dstMac = ethLayer->getDestMac(); dstMac.copyTo((uint8_t*)&(addr.sll_addr)); if (::sendto(fd, ((RawPacket*)rawPacket)->getRawData(), ((RawPacket*)rawPacket)->getRawDataLen(), 0, (struct sockaddr*)&addr, sizeof(addr)) == -1) { LOG_ERROR("Failed to send packet. Error was: '%s'", strerror(errno)); return false; } return true; #else LOG_ERROR("Raw socket are not supported on this platform"); return 0; #endif } int RawSocketDevice::sendPackets(const RawPacketVector& packetVec) { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) LOG_ERROR("Sending packets with raw socket are not supported on Windows"); return false; #elif LINUX if (!isOpened()) { LOG_ERROR("Device is not open"); return 0; } int fd = ((SocketContainer*)m_Socket)->fd; sockaddr_ll addr; memset(&addr, 0, sizeof(struct sockaddr_ll)); addr.sll_family = htons(PF_PACKET); addr.sll_protocol = htons(ETH_P_ALL); addr.sll_halen = 6; addr.sll_ifindex = ((SocketContainer*)m_Socket)->interfaceIndex; int sendCount = 0; for (RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++) { Packet packet(*iter, OsiModelDataLinkLayer); if (!packet.isPacketOfType(pcpp::Ethernet)) { LOG_DEBUG("Can't send non-Ethernet packets"); continue; } EthLayer* ethLayer = packet.getLayerOfType<EthLayer>(); MacAddress dstMac = ethLayer->getDestMac(); dstMac.copyTo((uint8_t*)&(addr.sll_addr)); if (::sendto(fd, (*iter)->getRawData(), (*iter)->getRawDataLen(), 0, (struct sockaddr*)&addr, sizeof(addr)) == -1) { LOG_DEBUG("Failed to send packet. Error was: '%s'", strerror(errno)); continue; } sendCount++; } return sendCount; #else LOG_ERROR("Raw socket are not supported on this platform"); return false; #endif } bool RawSocketDevice::open() { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) if (!m_InterfaceIP->isValid()) { LOG_ERROR("IP address is not valid"); return false; } int family = (m_SockFamily == IPv4 ? AF_INET : AF_INET6); SOCKET fd = socket(family, SOCK_RAW, IPPROTO_IP); if ((int)fd == SOCKET_ERROR) { int error = WSAGetLastError(); std::string additionalMessage = ""; if (error == WSAEACCES) additionalMessage = ", you may not be running with administrative privileges which is required for opening raw sockets on Windows"; LOG_ERROR("Failed to create raw socket. Error code was %d%s", error, additionalMessage.c_str()); return false; } void* localAddr = NULL; struct sockaddr_in localAddrIPv4; struct sockaddr_in6 localAddrIPv6; size_t localAddrSize = 0; if (m_SockFamily == IPv4) { localAddrIPv4.sin_family = family; int res = inet_pton(family, m_InterfaceIP->toString().c_str(), &localAddrIPv4.sin_addr.s_addr); if (res <= 0) { LOG_ERROR("inet_pton failed, probably IP address provided is in bad format"); closesocket(fd); return false; } localAddrIPv4.sin_port = 0; // Any local port will do localAddr = &localAddrIPv4; localAddrSize = sizeof(localAddrIPv4); } else { localAddrIPv6.sin6_family = family; int res = inet_pton(AF_INET6, m_InterfaceIP->toString().c_str(), &localAddrIPv6.sin6_addr.s6_addr); if (res <= 0) { LOG_ERROR("inet_pton failed, probably IP address provided is in bad format"); closesocket(fd); return false; } localAddrIPv6.sin6_port = 0; // Any local port will do localAddrIPv6.sin6_scope_id = 0; localAddr = &localAddrIPv6; localAddrSize = sizeof(localAddrIPv6); } if (bind(fd, (struct sockaddr *)localAddr, localAddrSize) == SOCKET_ERROR) { LOG_ERROR("Failed to bind to interface. Error code was '%d'", WSAGetLastError()); closesocket(fd); return false; } int n = 1; DWORD dwBytesRet; if (WSAIoctl(fd, SIO_RCVALL, &n, sizeof(n), NULL, 0, &dwBytesRet, NULL, NULL) == SOCKET_ERROR) { LOG_ERROR("Call to WSAIotcl(%ul) failed with error code %d", SIO_RCVALL, WSAGetLastError()); closesocket(fd); return false; } m_Socket = new SocketContainer(); ((SocketContainer*)m_Socket)->fd = fd; m_DeviceOpened = true; return true; #elif LINUX if (!m_InterfaceIP->isValid()) { LOG_ERROR("IP address is not valid"); return false; } int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (fd < 0) { LOG_ERROR("Failed to create raw socket. Error code was %d", errno); return false; } // find interface name and index from IP address struct ifaddrs* addrs; getifaddrs(&addrs); std::string ifaceName = ""; int ifaceIndex = -1; for (struct ifaddrs* curAddr = addrs; curAddr != NULL; curAddr = curAddr->ifa_next) { if (curAddr->ifa_addr && (curAddr->ifa_flags & IFF_UP)) { if (curAddr->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* sockAddr = (struct sockaddr_in*)(curAddr->ifa_addr); char addrAsCharArr[32]; inet_ntop(curAddr->ifa_addr->sa_family, (void *)&(sockAddr->sin_addr), addrAsCharArr, sizeof(addrAsCharArr)); if (!strcmp(m_InterfaceIP->toString().c_str(), addrAsCharArr)) { ifaceName = curAddr->ifa_name; ifaceIndex = if_nametoindex(curAddr->ifa_name); } } else if (curAddr->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* sockAddr = (struct sockaddr_in6*)(curAddr->ifa_addr); char addrAsCharArr[40]; inet_ntop(curAddr->ifa_addr->sa_family, (void *)&(sockAddr->sin6_addr), addrAsCharArr, sizeof(addrAsCharArr)); if (!strcmp(m_InterfaceIP->toString().c_str(), addrAsCharArr)) { ifaceName = curAddr->ifa_name; ifaceIndex = if_nametoindex(curAddr->ifa_name); } } } } freeifaddrs(addrs); if (ifaceName == "" || ifaceIndex < 0) { LOG_ERROR("Cannot detect interface name or index from IP address"); ::close(fd); return false; } // bind raw socket to interface struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifaceName.c_str()); if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) == -1) { LOG_ERROR("Cannot bind raw socket to interface '%s'", ifaceName.c_str()); ::close(fd); return false; } m_Socket = new SocketContainer(); ((SocketContainer*)m_Socket)->fd = fd; ((SocketContainer*)m_Socket)->interfaceIndex = ifaceIndex; ((SocketContainer*)m_Socket)->interfaceName = ifaceName; m_DeviceOpened = true; return true; #else LOG_ERROR("Raw socket are not supported on this platform"); return false; #endif } void RawSocketDevice::close() { if (m_Socket != NULL && isOpened()) { SocketContainer* sockContainer = (SocketContainer*)m_Socket; #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) closesocket(sockContainer->fd); #elif LINUX ::close(sockContainer->fd); #endif delete sockContainer; m_Socket = NULL; m_DeviceOpened = false; } } RawSocketDevice::RecvPacketResult RawSocketDevice::getError(int& errorCode) const { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) errorCode = WSAGetLastError(); if (errorCode == WSAEWOULDBLOCK) return RecvWouldBlock; if (errorCode == WSAETIMEDOUT) return RecvTimeout; return RecvError; #elif LINUX if ((errorCode == EAGAIN) || (errorCode == EWOULDBLOCK)) return RecvWouldBlock; return RecvError; #else return RecvError; #endif } }
[ "koraydemirci86@gmail.com" ]
koraydemirci86@gmail.com
e521583358cd02e95c53306d6597579fc0363c12
90cef3c0759f9463da3d6bb79834ee7793678166
/opengesnative/src/main/jni/nativeDraw.cpp
028fe5cf41a6a2c93764ece0b9e20a64dd5d4487
[]
no_license
Linus-Smith/OpengGL-ES
86dccad34c823563b9215b4edd93a9cd6bdb9d0b
def9d5b7428d4db34e8249d5bc58fc455fc88ee1
refs/heads/master
2021-01-11T03:59:05.322698
2017-09-05T12:10:53
2017-09-05T12:10:53
71,265,255
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
cpp
#include "nativeDraw.h" #include "common/esUtil.h" void onSurfaceCreated() { mProgram = esLoadProgram(vShader, fShader); shIndex.mvpMatrix = glGetUniformLocation(mProgram, "uMVPMatrix"); shIndex.position = glGetAttribLocation(mProgram, "aPosition"); shIndex.color = glGetAttribLocation(mProgram, "aColor"); mModeMatrix = (ESMatrix *) malloc(sizeof(ESMatrix)); mPMatrox = (ESMatrix *) malloc(sizeof(ESMatrix)); esMatrixLoadIdentity(mModeMatrix); esMatrixLoadIdentity(mPMatrox); bufferId = (GLuint *) malloc(BUFFER_COUNT); vaoId = (GLuint *)malloc(VAO_COUNT); glGenBuffers(BUFFER_COUNT, bufferId); glBindBuffer(GL_ARRAY_BUFFER, bufferId[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(shaderData), shaderData, GL_STATIC_DRAW); } void onSurfaceChanged(JNIEnv env, jobject obj, int width, int height) { LOGD("onSurfaceChanged %d %d", width, height); glViewport(0, 0, width, height); glGenVertexArrays(VAO_COUNT, vaoId); GLfloat rea = width / height; esOrtho(mPMatrox, -rea, rea, -1, 1, 1, 10); ESMatrix * mvpMatrix = (ESMatrix *) malloc(sizeof(ESMatrix)); esMatrixLoadIdentity(mvpMatrix); esMatrixMultiply(mvpMatrix, mModeMatrix, mPMatrox); glUniform4fv(shIndex.mvpMatrix, 1, ( GLfloat * ) &mvpMatrix->m[0][0]); glBindVertexArray(vaoId[0]); glBindBuffer(GL_ARRAY_BUFFER, bufferId[0]); glEnableVertexAttribArray(shIndex.position); glVertexAttribPointer(shIndex.position, 3, GL_FLOAT, GL_FALSE, sizeof(shaderData[0]), 0); glVertexAttrib4f(shIndex.color, 1.0f, 0.4f, 0.6f, 0.4f); glBindVertexArray(0); } void onDrawFrame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(mProgram); glBindVertexArray(vaoId[0]); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); }
[ "chyangbast@yeah.net" ]
chyangbast@yeah.net
d64caeb017e88dc89ce02f04189ed456dc358910
941576c946628eeda4424c450396598908be2094
/ChakraDemoApp/Chakra.h
69c81f725d2ddec5910ce28b087b4f0a62dda7fe
[]
no_license
mslavchev/chakra-wp81
6f4b8e6a7dc7536a87dce31d65d3822b331bd06d
951de7277183c88e593544849e32e013537483ad
refs/heads/master
2016-08-07T19:48:53.691951
2014-09-10T13:26:14
2014-09-10T13:26:14
23,870,194
0
0
null
null
null
null
UTF-8
C++
false
false
223
h
#include "jsrt.h" namespace ChakraDemoApp { class Chakra { public: Chakra(); Platform::String^ GetGreeting(); ~Chakra(); private: JsRuntimeHandle m_runtime; JsContextRef m_context; }; }
[ "meslav@hotmail.com" ]
meslav@hotmail.com
694e370c5ac4b7fb9ea81c1c650ba561a066095d
2b4bd3b3a18759c1d25476bda3be3f8aee8ca371
/PAT/Advanced/1008.cpp
fb4bf740bf6430018f4512e6212a2964eaf86d48
[]
no_license
cusion/Algorithm
54318d208e1c8aaece9053b98d8641e279c63444
8c826399285aa3fee88031fe84a610a56c542147
refs/heads/master
2016-09-10T18:35:43.740494
2014-10-14T06:57:28
2014-10-14T06:57:28
16,759,961
1
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
#include <cstdio> #include <iostream> using namespace std; int main() { int n; cin >> n; int req; int cur = 0; int time = 0; for (int i = 0; i < n; ++i) { scanf("%d", &req); if (req == cur) { time += 5; } else if (req < cur) { time += (cur-req)*4 + 5; } else { time += (req-cur)*6 + 5; } cur = req; } cout << time << endl; return 0; }
[ "kuixiong@gmail.com" ]
kuixiong@gmail.com
574c65bb4faab48d825cce120665c99823c7f7b4
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/v8/torque-generated/src/objects/feedback-cell-tq-csa.cc
20681e8daf91dbea734a1cfd6aac204d90f41885
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
15,607
cc
#include "src/builtins/builtins-array-gen.h" #include "src/builtins/builtins-bigint-gen.h" #include "src/builtins/builtins-collections-gen.h" #include "src/builtins/builtins-constructor-gen.h" #include "src/builtins/builtins-data-view-gen.h" #include "src/builtins/builtins-iterator-gen.h" #include "src/builtins/builtins-promise-gen.h" #include "src/builtins/builtins-promise.h" #include "src/builtins/builtins-proxy-gen.h" #include "src/builtins/builtins-regexp-gen.h" #include "src/builtins/builtins-string-gen.h" #include "src/builtins/builtins-typed-array-gen.h" #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins.h" #include "src/codegen/code-factory.h" #include "src/heap/factory-inl.h" #include "src/objects/arguments.h" #include "src/objects/bigint.h" #include "src/objects/elements-kind.h" #include "src/objects/free-space.h" #include "src/objects/js-break-iterator.h" #include "src/objects/js-collator.h" #include "src/objects/js-date-time-format.h" #include "src/objects/js-display-names.h" #include "src/objects/js-generator.h" #include "src/objects/js-list-format.h" #include "src/objects/js-locale.h" #include "src/objects/js-number-format.h" #include "src/objects/js-objects.h" #include "src/objects/js-plural-rules.h" #include "src/objects/js-promise.h" #include "src/objects/js-regexp-string-iterator.h" #include "src/objects/js-relative-time-format.h" #include "src/objects/js-segment-iterator.h" #include "src/objects/js-segmenter.h" #include "src/objects/js-weak-refs.h" #include "src/objects/objects.h" #include "src/objects/ordered-hash-table.h" #include "src/objects/property-array.h" #include "src/objects/property-descriptor-object.h" #include "src/objects/source-text-module.h" #include "src/objects/stack-frame-info.h" #include "src/objects/synthetic-module.h" #include "src/objects/template-objects.h" #include "src/torque/runtime-support.h" #include "torque-generated/src/builtins/array-copywithin-tq-csa.h" #include "torque-generated/src/builtins/array-every-tq-csa.h" #include "torque-generated/src/builtins/array-filter-tq-csa.h" #include "torque-generated/src/builtins/array-find-tq-csa.h" #include "torque-generated/src/builtins/array-findindex-tq-csa.h" #include "torque-generated/src/builtins/array-foreach-tq-csa.h" #include "torque-generated/src/builtins/array-from-tq-csa.h" #include "torque-generated/src/builtins/array-isarray-tq-csa.h" #include "torque-generated/src/builtins/array-join-tq-csa.h" #include "torque-generated/src/builtins/array-lastindexof-tq-csa.h" #include "torque-generated/src/builtins/array-map-tq-csa.h" #include "torque-generated/src/builtins/array-of-tq-csa.h" #include "torque-generated/src/builtins/array-reduce-right-tq-csa.h" #include "torque-generated/src/builtins/array-reduce-tq-csa.h" #include "torque-generated/src/builtins/array-reverse-tq-csa.h" #include "torque-generated/src/builtins/array-shift-tq-csa.h" #include "torque-generated/src/builtins/array-slice-tq-csa.h" #include "torque-generated/src/builtins/array-some-tq-csa.h" #include "torque-generated/src/builtins/array-splice-tq-csa.h" #include "torque-generated/src/builtins/array-unshift-tq-csa.h" #include "torque-generated/src/builtins/array-tq-csa.h" #include "torque-generated/src/builtins/base-tq-csa.h" #include "torque-generated/src/builtins/bigint-tq-csa.h" #include "torque-generated/src/builtins/boolean-tq-csa.h" #include "torque-generated/src/builtins/builtins-string-tq-csa.h" #include "torque-generated/src/builtins/collections-tq-csa.h" #include "torque-generated/src/builtins/cast-tq-csa.h" #include "torque-generated/src/builtins/convert-tq-csa.h" #include "torque-generated/src/builtins/console-tq-csa.h" #include "torque-generated/src/builtins/data-view-tq-csa.h" #include "torque-generated/src/builtins/frames-tq-csa.h" #include "torque-generated/src/builtins/frame-arguments-tq-csa.h" #include "torque-generated/src/builtins/growable-fixed-array-tq-csa.h" #include "torque-generated/src/builtins/internal-coverage-tq-csa.h" #include "torque-generated/src/builtins/iterator-tq-csa.h" #include "torque-generated/src/builtins/math-tq-csa.h" #include "torque-generated/src/builtins/number-tq-csa.h" #include "torque-generated/src/builtins/object-fromentries-tq-csa.h" #include "torque-generated/src/builtins/object-tq-csa.h" #include "torque-generated/src/builtins/promise-abstract-operations-tq-csa.h" #include "torque-generated/src/builtins/promise-all-tq-csa.h" #include "torque-generated/src/builtins/promise-all-element-closure-tq-csa.h" #include "torque-generated/src/builtins/promise-constructor-tq-csa.h" #include "torque-generated/src/builtins/promise-finally-tq-csa.h" #include "torque-generated/src/builtins/promise-misc-tq-csa.h" #include "torque-generated/src/builtins/promise-race-tq-csa.h" #include "torque-generated/src/builtins/promise-reaction-job-tq-csa.h" #include "torque-generated/src/builtins/promise-resolve-tq-csa.h" #include "torque-generated/src/builtins/promise-then-tq-csa.h" #include "torque-generated/src/builtins/promise-jobs-tq-csa.h" #include "torque-generated/src/builtins/proxy-constructor-tq-csa.h" #include "torque-generated/src/builtins/proxy-delete-property-tq-csa.h" #include "torque-generated/src/builtins/proxy-get-property-tq-csa.h" #include "torque-generated/src/builtins/proxy-get-prototype-of-tq-csa.h" #include "torque-generated/src/builtins/proxy-has-property-tq-csa.h" #include "torque-generated/src/builtins/proxy-is-extensible-tq-csa.h" #include "torque-generated/src/builtins/proxy-prevent-extensions-tq-csa.h" #include "torque-generated/src/builtins/proxy-revocable-tq-csa.h" #include "torque-generated/src/builtins/proxy-revoke-tq-csa.h" #include "torque-generated/src/builtins/proxy-set-property-tq-csa.h" #include "torque-generated/src/builtins/proxy-set-prototype-of-tq-csa.h" #include "torque-generated/src/builtins/proxy-tq-csa.h" #include "torque-generated/src/builtins/reflect-tq-csa.h" #include "torque-generated/src/builtins/regexp-exec-tq-csa.h" #include "torque-generated/src/builtins/regexp-match-all-tq-csa.h" #include "torque-generated/src/builtins/regexp-match-tq-csa.h" #include "torque-generated/src/builtins/regexp-replace-tq-csa.h" #include "torque-generated/src/builtins/regexp-search-tq-csa.h" #include "torque-generated/src/builtins/regexp-source-tq-csa.h" #include "torque-generated/src/builtins/regexp-split-tq-csa.h" #include "torque-generated/src/builtins/regexp-test-tq-csa.h" #include "torque-generated/src/builtins/regexp-tq-csa.h" #include "torque-generated/src/builtins/string-endswith-tq-csa.h" #include "torque-generated/src/builtins/string-html-tq-csa.h" #include "torque-generated/src/builtins/string-iterator-tq-csa.h" #include "torque-generated/src/builtins/string-pad-tq-csa.h" #include "torque-generated/src/builtins/string-repeat-tq-csa.h" #include "torque-generated/src/builtins/string-replaceall-tq-csa.h" #include "torque-generated/src/builtins/string-slice-tq-csa.h" #include "torque-generated/src/builtins/string-startswith-tq-csa.h" #include "torque-generated/src/builtins/string-substring-tq-csa.h" #include "torque-generated/src/builtins/string-substr-tq-csa.h" #include "torque-generated/src/builtins/symbol-tq-csa.h" #include "torque-generated/src/builtins/torque-internal-tq-csa.h" #include "torque-generated/src/builtins/typed-array-createtypedarray-tq-csa.h" #include "torque-generated/src/builtins/typed-array-every-tq-csa.h" #include "torque-generated/src/builtins/typed-array-filter-tq-csa.h" #include "torque-generated/src/builtins/typed-array-find-tq-csa.h" #include "torque-generated/src/builtins/typed-array-findindex-tq-csa.h" #include "torque-generated/src/builtins/typed-array-foreach-tq-csa.h" #include "torque-generated/src/builtins/typed-array-from-tq-csa.h" #include "torque-generated/src/builtins/typed-array-of-tq-csa.h" #include "torque-generated/src/builtins/typed-array-reduce-tq-csa.h" #include "torque-generated/src/builtins/typed-array-reduceright-tq-csa.h" #include "torque-generated/src/builtins/typed-array-set-tq-csa.h" #include "torque-generated/src/builtins/typed-array-slice-tq-csa.h" #include "torque-generated/src/builtins/typed-array-some-tq-csa.h" #include "torque-generated/src/builtins/typed-array-sort-tq-csa.h" #include "torque-generated/src/builtins/typed-array-subarray-tq-csa.h" #include "torque-generated/src/builtins/typed-array-tq-csa.h" #include "torque-generated/src/ic/handler-configuration-tq-csa.h" #include "torque-generated/src/objects/allocation-site-tq-csa.h" #include "torque-generated/src/objects/api-callbacks-tq-csa.h" #include "torque-generated/src/objects/arguments-tq-csa.h" #include "torque-generated/src/objects/cell-tq-csa.h" #include "torque-generated/src/objects/code-tq-csa.h" #include "torque-generated/src/objects/contexts-tq-csa.h" #include "torque-generated/src/objects/data-handler-tq-csa.h" #include "torque-generated/src/objects/debug-objects-tq-csa.h" #include "torque-generated/src/objects/descriptor-array-tq-csa.h" #include "torque-generated/src/objects/embedder-data-array-tq-csa.h" #include "torque-generated/src/objects/feedback-cell-tq-csa.h" #include "torque-generated/src/objects/feedback-vector-tq-csa.h" #include "torque-generated/src/objects/fixed-array-tq-csa.h" #include "torque-generated/src/objects/foreign-tq-csa.h" #include "torque-generated/src/objects/free-space-tq-csa.h" #include "torque-generated/src/objects/heap-number-tq-csa.h" #include "torque-generated/src/objects/heap-object-tq-csa.h" #include "torque-generated/src/objects/intl-objects-tq-csa.h" #include "torque-generated/src/objects/js-array-buffer-tq-csa.h" #include "torque-generated/src/objects/js-array-tq-csa.h" #include "torque-generated/src/objects/js-collection-iterator-tq-csa.h" #include "torque-generated/src/objects/js-collection-tq-csa.h" #include "torque-generated/src/objects/js-generator-tq-csa.h" #include "torque-generated/src/objects/js-objects-tq-csa.h" #include "torque-generated/src/objects/js-promise-tq-csa.h" #include "torque-generated/src/objects/js-proxy-tq-csa.h" #include "torque-generated/src/objects/js-regexp-string-iterator-tq-csa.h" #include "torque-generated/src/objects/js-regexp-tq-csa.h" #include "torque-generated/src/objects/js-weak-refs-tq-csa.h" #include "torque-generated/src/objects/literal-objects-tq-csa.h" #include "torque-generated/src/objects/map-tq-csa.h" #include "torque-generated/src/objects/microtask-tq-csa.h" #include "torque-generated/src/objects/module-tq-csa.h" #include "torque-generated/src/objects/name-tq-csa.h" #include "torque-generated/src/objects/oddball-tq-csa.h" #include "torque-generated/src/objects/ordered-hash-table-tq-csa.h" #include "torque-generated/src/objects/primitive-heap-object-tq-csa.h" #include "torque-generated/src/objects/promise-tq-csa.h" #include "torque-generated/src/objects/property-array-tq-csa.h" #include "torque-generated/src/objects/property-cell-tq-csa.h" #include "torque-generated/src/objects/property-descriptor-object-tq-csa.h" #include "torque-generated/src/objects/prototype-info-tq-csa.h" #include "torque-generated/src/objects/regexp-match-info-tq-csa.h" #include "torque-generated/src/objects/scope-info-tq-csa.h" #include "torque-generated/src/objects/script-tq-csa.h" #include "torque-generated/src/objects/shared-function-info-tq-csa.h" #include "torque-generated/src/objects/source-text-module-tq-csa.h" #include "torque-generated/src/objects/stack-frame-info-tq-csa.h" #include "torque-generated/src/objects/string-tq-csa.h" #include "torque-generated/src/objects/struct-tq-csa.h" #include "torque-generated/src/objects/synthetic-module-tq-csa.h" #include "torque-generated/src/objects/template-objects-tq-csa.h" #include "torque-generated/src/objects/template-tq-csa.h" #include "torque-generated/src/wasm/wasm-objects-tq-csa.h" #include "torque-generated/test/torque/test-torque-tq-csa.h" #include "torque-generated/third_party/v8/builtins/array-sort-tq-csa.h" namespace v8 { namespace internal { TNode<HeapObject> LoadFeedbackCellValue_0(compiler::CodeAssemblerState* state_, TNode<FeedbackCell> p_o) { compiler::CodeAssembler ca_(state_); compiler::CodeAssemblerParameterizedLabel<FeedbackCell> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, HeapObject> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0, p_o); if (block0.is_used()) { TNode<FeedbackCell> tmp0; ca_.Bind(&block0, &tmp0); TNode<IntPtrT> tmp1; USE(tmp1); tmp1 = FromConstexpr_intptr_constexpr_int31_0(state_, 4); TNode<HeapObject>tmp2 = CodeStubAssembler(state_).LoadReference<HeapObject>(CodeStubAssembler::Reference{tmp0, tmp1}); ca_.Goto(&block2, tmp0, tmp2); } TNode<FeedbackCell> tmp3; TNode<HeapObject> tmp4; ca_.Bind(&block2, &tmp3, &tmp4); return TNode<HeapObject>{tmp4}; } void StoreFeedbackCellValue_0(compiler::CodeAssemblerState* state_, TNode<FeedbackCell> p_o, TNode<HeapObject> p_v) { compiler::CodeAssembler ca_(state_); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, HeapObject> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, HeapObject> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0, p_o, p_v); if (block0.is_used()) { TNode<FeedbackCell> tmp0; TNode<HeapObject> tmp1; ca_.Bind(&block0, &tmp0, &tmp1); TNode<IntPtrT> tmp2; USE(tmp2); tmp2 = FromConstexpr_intptr_constexpr_int31_0(state_, 4); CodeStubAssembler(state_).StoreReference<HeapObject>(CodeStubAssembler::Reference{tmp0, tmp2}, tmp1); ca_.Goto(&block2, tmp0, tmp1); } TNode<FeedbackCell> tmp3; TNode<HeapObject> tmp4; ca_.Bind(&block2, &tmp3, &tmp4); } TNode<Int32T> LoadFeedbackCellInterruptBudget_0(compiler::CodeAssemblerState* state_, TNode<FeedbackCell> p_o) { compiler::CodeAssembler ca_(state_); compiler::CodeAssemblerParameterizedLabel<FeedbackCell> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, Int32T> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0, p_o); if (block0.is_used()) { TNode<FeedbackCell> tmp0; ca_.Bind(&block0, &tmp0); TNode<IntPtrT> tmp1; USE(tmp1); tmp1 = FromConstexpr_intptr_constexpr_int31_0(state_, 8); TNode<Int32T>tmp2 = CodeStubAssembler(state_).LoadReference<Int32T>(CodeStubAssembler::Reference{tmp0, tmp1}); ca_.Goto(&block2, tmp0, tmp2); } TNode<FeedbackCell> tmp3; TNode<Int32T> tmp4; ca_.Bind(&block2, &tmp3, &tmp4); return TNode<Int32T>{tmp4}; } void StoreFeedbackCellInterruptBudget_0(compiler::CodeAssemblerState* state_, TNode<FeedbackCell> p_o, TNode<Int32T> p_v) { compiler::CodeAssembler ca_(state_); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, Int32T> block0(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); compiler::CodeAssemblerParameterizedLabel<FeedbackCell, Int32T> block2(&ca_, compiler::CodeAssemblerLabel::kNonDeferred); ca_.Goto(&block0, p_o, p_v); if (block0.is_used()) { TNode<FeedbackCell> tmp0; TNode<Int32T> tmp1; ca_.Bind(&block0, &tmp0, &tmp1); TNode<IntPtrT> tmp2; USE(tmp2); tmp2 = FromConstexpr_intptr_constexpr_int31_0(state_, 8); CodeStubAssembler(state_).StoreReference<Int32T>(CodeStubAssembler::Reference{tmp0, tmp2}, tmp1); ca_.Goto(&block2, tmp0, tmp1); } TNode<FeedbackCell> tmp3; TNode<Int32T> tmp4; ca_.Bind(&block2, &tmp3, &tmp4); } } // namespace internal } // namespace v8
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
79cd3ca002ada3a3a9ffaf694479eed71249d196
827405b8f9a56632db9f78ea6709efb137738b9d
/CodingWebsites/LeetCode/CPP/Volume1/11.cpp
65bab5bc7aac7006c42ee04fca36729ba295dc7e
[]
no_license
MingzhenY/code-warehouse
2ae037a671f952201cf9ca13992e58718d11a704
d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7
refs/heads/master
2020-03-17T14:59:30.425939
2019-02-10T17:12:36
2019-02-10T17:12:36
133,694,119
0
0
null
null
null
null
UTF-8
C++
false
false
2,955
cpp
#include <cstdlib> #include <cstdio> #include <iostream> #include <queue> #include <algorithm> #include <vector> #include <cstring> using namespace std; class Solution { private: int n; vector<int> ST; struct A{ int id,a; A(){} A(int id,int a):id(id),a(a){} bool operator < (const A & B)const{ return a < B.a; } }; vector<A> Rank; public: int maxArea(vector<int>& height) { n = height.size(); //Sort By Height Rank = vector<A>(n); for(int i = 0 ; i < n ; ++i) Rank[i] = A(i+1,height[i]); sort(Rank.begin(),Rank.end()); //for(int i = 0 ; i < n ; ++i){ // printf("Rank[%d] = (%d,%d)\n",i,Rank[i].id,Rank[i].a); //} //Solve By Segment Tree ST_Init(); ST_Build(1,n,1); //printf("Build Done\n"); int Max = 0; for(int i = 0 ; i < n ; ++i){ //printf("i=%d\n",i); //Record Answer int LeftMost = ST_QueryLeft(1,n,1); //printf("Left Done\n"); int RightMost = ST_QueryRight(1,n,1); //printf("id = %d (L,R) = (%d,%d)\n",Rank[i].id,LeftMost,RightMost); int CurMax = Rank[i].a * max(Rank[i].id - LeftMost,RightMost - Rank[i].id); //printf("CurMax = %d\n",CurMax); Max = max(Max,CurMax); //Delete Number ST_Update(Rank[i].id,1,n,1); } ST_Clear(); return Max; } void ST_Init(){ ST = vector<int>(n << 2); } void ST_Build(int l,int r,int rt){ if(l == r){ ST[rt] = 1; return; } int m = (l + r) >> 1; ST_Build(l,m,rt << 1); ST_Build(m + 1 , r , rt << 1 | 1); ST[rt] = ST[rt << 1] + ST[rt << 1 | 1]; } void ST_Update(int X,int l,int r,int rt){ if(l == r){ ST[rt] --; return; } int m = (l + r) >> 1; if(X <= m) ST_Update(X,l,m,rt << 1); else ST_Update(X,m + 1, r, rt << 1 | 1); ST[rt]--; } int ST_QueryLeft(int l,int r,int rt){ //query the position of the leftmost 1 if(l == r) return l; int m = (l + r) >> 1; if(ST[rt << 1] > 0) return ST_QueryLeft(l,m,rt << 1); else return ST_QueryLeft(m + 1, r, rt << 1 | 1); } int ST_QueryRight(int l,int r,int rt){ //query the position of the rightmost 1 if(l == r) return l; int m = (l + r) >> 1; if(ST[rt << 1 | 1] > 0) return ST_QueryRight(m + 1, r, rt << 1 | 1); else return ST_QueryRight(l, m, rt << 1); } void ST_Clear(){ ST.clear(); } void Test(){ vector<int> V; V.push_back(1); V.push_back(2); V.push_back(4); V.push_back(3); cout<<maxArea(V)<<endl; } }; int main(){ Solution S; S.Test(); return 0; }
[ "mingzhenyan@yahoo.com" ]
mingzhenyan@yahoo.com
8c849ff4d0aefbdab49774622365c8f09e1321f5
e23ce3b3d3f471e15b2af697463adcc7f80d5140
/concepts/dutchNationalFlagAlgorithm.cpp
7f91c57e56b8afff77c178c1ef11b3ba51aa1804
[]
no_license
sirraghavgupta/cpp-data-structures-and-algorithms
27a6620f5ab306186017b9ff5c14e378c18d5ce7
6a4c18b79eaa6c406414fd2b94a54403110993f8
refs/heads/master
2020-05-16T16:34:27.702583
2019-11-30T14:52:36
2019-11-30T14:52:36
183,165,972
3
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
/*############################################################################## AUTHOR : RAGHAV GUPTA DATE : 13 june 2019 AIM : to sort an array containing only 0,1,2s in linear time expected time complexity is constant dont build the frequency array - counting sort X X X X STATUS : !!! success !!! ##############################################################################*/ #include <iostream> using namespace std; int main(){ int n; cin>>n; int arr[n]; for(int i=0; i<n; i++) cin>>arr[i]; int low=0, mid=low, high=n-1; // pointers to 3 windows of 0s, 1s and 2s while(mid<=high){ // terminating condition if(arr[mid]==1) // increment mid pointer mid++; else if(arr[mid]==0){ // swap elements and increment both pointers swap(arr[mid], arr[low]); mid++; low++; } else{ // swap elements and decrement high pointer swap(arr[mid], arr[high]); high--; } } for(int i=0; i<n; i++) // print the array cout<<arr[i]<<" "; cout<<endl; return 0; }
[ "raghav.mhc@gmail.com" ]
raghav.mhc@gmail.com
c005e6c7cdd8311ccc4c13d140066dab9832c50d
ade02ce99c8ee41a9c5267985516be106c50605a
/fit_scripts/parton_350_bukinFit.cpp
9c486be8c82a55789cc8bf92d84a203fbea27e2c
[]
no_license
KomalTauqeer/madanalysis5_ALP
800e1ff92e6430f464ec9fc6d2d135c5b52ff91b
d4550892b33b66ff57d4681a855edd6dd1a04911
refs/heads/master
2020-07-29T09:10:21.194207
2019-09-20T11:07:04
2019-09-20T11:07:04
209,741,122
0
0
null
null
null
null
UTF-8
C++
false
false
4,014
cpp
#include <TFile.h> #include <TCanvas.h> #include <TF1.h> #include <TH1F.h> void parton_350_bukinFit() { Double_t bukin(Double_t *x, Double_t *par); TFile *file = new TFile("/afs/cern.ch/work/k/ktauqeer/private/MadGraph/madanalysis5/rootFiles/parton_level_350.root","READ"); TFile *f1 = new TFile("/afs/cern.ch/work/k/ktauqeer/private/MadGraph/madanalysis5/rootFiles_fit/parton_level_350.root","RECREATE"); TCanvas* c1 = new TCanvas("c1"); TH1F* hist; file -> GetObject("hist_350",hist); hist -> Sumw2(); Double_t x = {1.}; Double_t par[6] = {1.,120.,20.-0.2,0.01,0.01}; TF1* f = new TF1("fit",bukin,250,500,6); f -> SetParameters(2.,371.5,84.83,-0.2,0.01,0.01); //TF1* f = new TF1("gauss","gausn",72,88); //f -> SetParameters(3,81.93,22.31); hist -> Fit("fit","R"); // Cosmetics gStyle -> SetOptStat(0); //gStyle-> SetOptFit(1100); //gStyle-> SetStatW(0.6); //gStyle-> SetStatH(0.6); hist -> SetTitle(""); hist -> GetXaxis() -> SetRangeUser(250,500); hist -> GetXaxis() -> SetTitle("M_{jj} [GeV]"); hist -> GetXaxis() -> SetTitleSize(0.05); hist -> GetXaxis() -> SetTitleOffset(0.8); hist -> GetYaxis() -> SetTitle("Events / (10 GeV)"); hist -> GetYaxis() -> SetTitleSize(0.05); hist -> GetYaxis() -> SetTitleOffset(0.9); hist -> SetMarkerStyle(20); hist -> SetMarkerSize(0.85); hist -> SetLineColor(1); hist -> SetLineWidth(1); hist -> Draw("PE1X0"); f -> SetFillStyle(1001); f -> Draw("fc same"); hist -> Draw("PE1X0 same"); auto leg = new TLegend(0.7,0.7,0.85,0.85); leg->AddEntry(hist,"MC data","P"); leg->AddEntry(f,"Bukin fit","l"); leg->Draw("same"); auto tbox = new TPaveText(0.7,0.4,0.85,0.6,"blNDC"); tbox -> SetFillStyle(0); tbox -> SetBorderSize(0); tbox -> SetTextAlign(12); tbox -> SetTextSize(0.030); tbox -> AddText(Form("#chi^{2}_{#nu}=%4.2f/%d",f->GetChisquare(),f->GetNDF())); tbox -> AddText(Form("#mu=%4.2f",f->GetParameter(1))); tbox -> AddText(Form("#sigma=%4.2f",f->GetParameter(2))); tbox -> Draw("same"); c1 -> SaveAs("parton_level_350_fit.pdf"); hist -> Write(); cout << "chi square = " << f -> GetChisquare() << endl; cout << "mean = " << f -> GetParameter(1) << endl; cout << "sigma = " << f -> GetParameter(2) << endl; //c1 -> SaveAs("fitted_histogram.pdf"); //file -> Close(); return; } Double_t bukin(Double_t *x, Double_t *par) { Double_t xx =x[0]; Double_t norm = par[0]; //100. Double_t x0 = par[1]; //120. Double_t sigma = par[2]; //20. Double_t xi = par[3]; //-0.2 Double_t rhoL = par[4]; //0.01 Double_t rhoR = par[5]; //0.01 double r1=0,r2=0,r3=0,r4=0,r5=0,hp=0; double x1 = 0,x2 = 0; double fit_result = 0; double consts = 2*sqrt(2*log(2.)); hp=sigma*consts; r3=log(2.); r4=sqrt(TMath::Power(xi,2)+1); r1=xi/r4; if(TMath::Abs(xi) > exp(-6.)){ r5=xi/log(r4+xi); } else r5=1; x1 = x0 + (hp / 2) * (r1-1); x2 = x0 + (hp / 2) * (r1+1); //--- Left Side if(xx < x1) { r2=rhoL*TMath::Power((xx-x1)/(x0-x1),2)-r3 + 4 * r3 * (xx-x1)/hp * r5 * r4/TMath::Power((r4-xi),2 ); } //--- Center else if(xx < x2) { if(TMath::Abs(xi) > exp(-6.)) { r2=log(1 + 4 * xi * r4 * (xx-x0)/hp)/log(1+2*xi*(xi-r4)); r2=-r3*(TMath::Power(r2,2)); } else { r2=-4*r3*TMath::Power(((xx-x0)/hp),2); } } //--- Right Side else { r2=rhoR*TMath::Power((xx-x2)/(x0-x2),2)-r3 - 4 * r3 * (xx-x2)/hp * r5 * r4/TMath::Power((r4+xi),2); } if(TMath::Abs(r2) > 100) { fit_result = 0; } else { //---- Normalize the result fit_result = exp(r2); } return norm*fit_result; }
[ "ktauqeer@lxplus791.cern.ch" ]
ktauqeer@lxplus791.cern.ch
4d90c4a8dac2d0b07f1a223cccae144c9f7b269d
a090af918e3ec59140027dbddd54aa4ca1c73910
/codechef/oct_maandi.cpp
80351d171d5d8906dab9a9287ccca4ea91ecbd75
[]
no_license
nitesh-147/Programming-Problem-Solution
b739e2a3c9cfeb2141baf1d34e43eac0435ecb2a
df7d53e0863954ddf358539d23266b28d5504212
refs/heads/master
2023-03-16T00:37:10.236317
2019-11-28T18:11:33
2019-11-28T18:11:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,817
cpp
#include <cstring> #include <cassert> #include <vector> #include <list> #include <queue> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <fstream> #include <climits> /**********TYPE CASTING**********/ #define LL long long #define L long #define D double #define LD long double #define S string #define I int #define ULL unsigned long long #define q queue<int> #define vi vector<int> #define vl vector<long> /**********INPUT**********/ #define si(a) scanf("%d",&a) #define sl(a) scanf("%ld",&a) #define s1(a) scanf("%d",&a) #define s2(a,b) scanf("%d%d",&a,&b) #define s3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define sll(a) scanf("%lld",&a) #define sd(a) scanf("%lf",&a) #define ss(a) scanf("%s",&a) #define gc() getchar() /**********OUTPUT**********/ #define p1(a) printf("%d\n",a) #define p2(a,b) printf("%d %d\n",a,b) #define pll(a) printf("%lld\n",a) #define pd(a) printf("%.10lf\n",a) #define pcs(a,n) printf("Case %d: %d\n",a,n) #define nl() printf("\n") /**********LOOP**********/ #define REV(i,e,s) for(i=e;i>=s;i--) #define FOR(i,a,b) for(i=a;i<b;i++) #define loop(n) for(int o=1;o<=n;o++) /********** min/max *******/ #define max(a,b) a>b?a:b #define min(a,b) a<b?a:b #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) mix(a,max(b,c)) #define max4(a,b,c,d) max(max(a,b),max(c,d)) #define min4(a,b,c,d) min(min(a,b),min(c,d)) /**********SHORTCUT**********/ #define len(a) a.length() #define SET(a,x) memset(a,x,sizeof a) #define VI vector<int> #define PB push_back #define SZ size() #define CLR clear() #define PB(A) push_back(A) #define clr(a,b) memset(a,b,sizeof(a)) /**********CONSTANT**********/ #define MIN INT_MIN #define PI 2acos(-1.0) #define INF 2<<15 #define MOD 1000000007 #define MAX 1000001 using namespace std; /* LL gcd(LL a,LL b) { if(b==0)return a; return gcd(b,a%b); } LL bigmod(LL p,LL e,LL M) { if(e==0)return 1; if(e%2==0) { LL t=bigmod(p,e/2,M); return (t*t)%M; } return (bigmod(p,e-1,M)*p)%M; } LL modinverse(LL a,LL M) { return bigmod(a,M-2,M); } bool is_prime[MAX]; L prime[MAX]; bool sieve() { long i,j; prime[0]=2; int k=1; int sq=(sqrt(MAX)); for(i=3; i<=sq; i+=2) { if(!is_prime[i]) { for(j=i*i; j<=MAX; j+=(2*i)) is_prime[j]=1; } } for(j=3; j<=MAX; j+=2) { if(!is_prime[j]) { prime[k++]=j; } } } long NOD(long n) { int i,j,k; long sq=sqrt(n); long res=1; for(i=0; prime[i]<=sq; i++) { int cnt=1; if(n%prime[i]==0) { while(n%prime[i]==0) { cnt++; n=n/prime[i]; if(n==1) break; } res*=cnt; sq=sqrt(n); } } if(n>1) res*=2; return res; } */ bool go(LL n) { while(n>0) { int rem=n%10; if(rem==7 || rem==4) return true; n=n/10; } return false; } int main() { // FILE * fin, * fout; // fin=fopen("input.txt","r"); // fout=fopen("output.txt","w"); int i,j,k; LL n; I t; scanf("%d",&t); while(t--) { scanf("%lld",&n); LL sq=sqrt(n); LL cnt=0; for(i=1; i<=sq; i++) { if(n%i==0) { bool get=go(i); if(get) cnt++; get=go(n/i); if(get) cnt++; } } printf("%ld\n",cnt); } return 0; }
[ "milonju01@gmail.com" ]
milonju01@gmail.com
710d6fcd39dc50fd9e8c34a2e66eee41380c0cfd
657ebf2ff96c18b90bd8fe52b40a75a658fa8587
/json_setting/my_template/version_1/{__name__.cpp}.cpp
90193759469d93ab964bd7c9da34855f565c32a4
[]
no_license
yapinxxx/VSCode
1a31c147a2229a4388cfd1e000e3dbcbaf84e4ba
e6830bb873eed314394f625fd41f99e536bb4f26
refs/heads/master
2022-11-29T08:21:45.932623
2020-08-10T13:47:48
2020-08-10T13:47:48
269,321,479
0
0
null
null
null
null
UTF-8
C++
false
false
91
cpp
#include <iostream> using namespace std; int main() { cin.get(); return 0; }
[ "yapin.style@gmail.com" ]
yapin.style@gmail.com
635b6445f2eab3926291a5d570d4a14d93005d88
6697cd726d4cd3744ae52a7d5618f4ad107befba
/CP/1500/gen.cpp
86e611228170311beea7f7f9433072050547c004
[]
no_license
Saifu0/Competitive-Programming
4385777115d5d83ba5140324c309db1e6c16f4af
ecc1c05f1a85636c57f7f6609dd6a002f220c0b0
refs/heads/master
2022-12-15T09:11:53.907652
2020-09-08T08:20:44
2020-09-08T08:20:44
293,743,953
0
0
null
null
null
null
UTF-8
C++
false
false
2,638
cpp
#include<bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int rand(int l, int r){ uniform_int_distribution<int> uid(l, r); return uid(rng); } // Random n numbers between l and r void num(int l, int r, int n) { for (int i = 0; i < n; ++i) { cout << rand(l,r) << " "; } } //Random n string number b/w l and r void string_num(int l,int r,int n){ for (int i = 0; i < n; ++i) { cout << to_string(rand(l,r)); } } //Random n real numbers between l and r with dig decimal places void real(int l, int r, int dig, int n) { for (int i = 0; i < n; ++i) { cout << rand(l,r) <<"."<<rand(0,pow(10,dig)-1)<< " "; } } // Random n strings of length l void str(int l, int n) { for (int i = 0; i < n; ++i) { for(int j = 0; j < l; ++j) { int v = rand(1,150); if(v%3==0) cout<<(char)rand('a','z'); else if(v%3==1) cout<<(char)rand('A','Z'); else cout<<rand(0,9); } cout<<" "; } } // Random n strings of max length l void strmx(int mxlen, int n) { for (int i = 0; i < n; ++i) { int l = rand(1,mxlen); for(int j = 0; j < l; ++j) { int v = rand(1,150); if(3%3==0) cout<<(char)rand('a','z'); else if(v%3==1) cout<<(char)rand('A','Z'); else cout<<rand(0,9); } cout<<" "; } } // Random tree of n nodes void tree(int n) { int prufer[n-2]; for ( int i = 0; i < n; i++ ){ prufer[i] = rand(1,n); } int m = n-2; int vertices = m + 2; int vertex_set[vertices]; for (int i = 0; i < vertices; i++) vertex_set[i] = 0; for (int i = 0; i < vertices - 2; i++) vertex_set[prufer[i] - 1] += 1; int j = 0; for (int i = 0; i < vertices - 2; i++) { for (j = 0; j < vertices; j++) { if (vertex_set[j] == 0) { vertex_set[j] = -1; cout << (j + 1) << " " << prufer[i] << '\n'; vertex_set[prufer[i] - 1]--; break; } } } j = 0; for (int i = 0; i < vertices; i++) { if (vertex_set[i] == 0 && j == 0) { cout << (i + 1) << " "; j++; } else if (vertex_set[i] == 0 && j == 1) cout << (i + 1) << "\n"; } } signed main() { int n=rand(1,10),q=rand(-10,10); cout << n << " " << q << endl; for(int i=0;i<n;i++){ int l=rand(-5,5); cout << l << " "; } cout << endl; }
[ "43892879+Saifu0@users.noreply.github.com" ]
43892879+Saifu0@users.noreply.github.com
1126d6ecfd1b7441addafb1ec15008eff933f02e
2639807d92c8ecd54b6e135660752a922a1b6e10
/branches/shader/Fog/Core/Arch/Atomic_msc_intrin.h
fe3c30a1eb0873e1cb943e0b94be79b38bd18453
[ "LicenseRef-scancode-boost-original", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "MIT", "X11", "HPND" ]
permissive
prepare/fog
b9fe3e5d409790ad49760901787d29a9a9195eed
a554c3dd422ee34130be9c5edfb521ec940ef139
refs/heads/master
2020-07-18T11:33:23.604140
2016-11-16T13:06:53
2016-11-16T13:06:53
73,920,391
0
1
null
null
null
null
UTF-8
C++
false
false
5,231
h
// [Fog-Core Library - Public API] // // [License] // MIT, See COPYING file in package // [Dependencies] #include <Fog/Core/Build.h> // [Guard] #if !defined(FOG_IDE) && !defined(_FOG_CORE_ATOMIC_H) #error "Fog::Atomic::MSC_INTRIN - Only Fog/Core/Atomic.h can include this file." #else // Always use compiler intrinsics if available. #if defined(FOG_CC_MSVC) && FOG_CC_MSVC >= 1400 # include <intrin.h> # pragma intrinsic (_InterlockedIncrement) # pragma intrinsic (_InterlockedCompareExchange) # pragma intrinsic (_InterlockedDecrement) # pragma intrinsic (_InterlockedExchange) # pragma intrinsic (_InterlockedExchangeAdd) # if FOG_ARCH_BITS == 64 # pragma intrinsic (_InterlockedIncrement64) # pragma intrinsic (_InterlockedCompareExchange64) # pragma intrinsic (_InterlockedDecrement64) # pragma intrinsic (_InterlockedExchange64) # pragma intrinsic (_InterlockedExchangeAdd64) # endif // FOG_ARCH_BITS == 64 # define _MSINTRIN_(func) _##func #else # define _MSINTRIN_(func) func #endif // FOG_CC_MSVC namespace Fog { // ============================================================================ // [Fog::AtomicInt32] // ============================================================================ //! @internal struct AtomicInt32 { typedef int32_t Type; static FOG_INLINE void set(int32_t* atomic, int32_t value) { _MSINTRIN_(InterlockedExchange)((LONG volatile*)atomic, (LONG)value); } static FOG_INLINE int32_t setXchg(int32_t* atomic, int32_t value) { return (int32_t)_MSINTRIN_(InterlockedExchange)((LONG volatile*)atomic, (LONG)value); } static FOG_INLINE bool cmpXchg(int32_t* atomic, int32_t compar, int32_t value) { return (bool)(_MSINTRIN_(InterlockedCompareExchange)((LONG*)atomic, (LONG)value, (LONG)compar) == (LONG)compar); } static FOG_INLINE int32_t get(const int32_t* atomic) { return *(volatile const int32_t *)atomic; } static FOG_INLINE void inc(int32_t* atomic) { _MSINTRIN_(InterlockedIncrement)((LONG*)atomic); } static FOG_INLINE void dec(int32_t* atomic) { _MSINTRIN_(InterlockedDecrement)((LONG*)atomic); } static FOG_INLINE void add(int32_t* atomic, int32_t value) { _MSINTRIN_(InterlockedExchangeAdd)((LONG*)atomic, (LONG)value); } static FOG_INLINE void sub(int32_t* atomic, int32_t value) { _MSINTRIN_(InterlockedExchangeAdd)((LONG*)atomic, (LONG)((value ^ 0xFFFFFFFF) + 1U)); } static FOG_INLINE int32_t addXchg(int32_t* atomic, int32_t value) { return (int32_t)_MSINTRIN_(InterlockedExchangeAdd)((LONG*)atomic, (LONG)value); } static FOG_INLINE int32_t subXchg(int32_t* atomic, int32_t value) { return (int32_t)_MSINTRIN_(InterlockedExchangeAdd)((LONG*)atomic, (LONG)((value ^ 0xFFFFFFFF) + 1U)); } static FOG_INLINE bool deref(int32_t* atomic) { return _MSINTRIN_(InterlockedDecrement)((LONG*)atomic) == 0; } }; // Specialize. template<> struct AtomicOperationHelper<4> : public AtomicInt32 {}; // ============================================================================ // [Fog::AtomicInt64] // ============================================================================ #if FOG_ARCH_BITS == 64 //! @internal struct AtomicInt64 { typedef int64_t Type; static FOG_INLINE void set(int64_t* atomic, int64_t value) { _MSINTRIN_(InterlockedExchange64)((int64_t*)atomic, (int64_t)value); } static FOG_INLINE int64_t setXchg(int64_t* atomic, int64_t value) { return (int64_t)_MSINTRIN_(InterlockedExchange64)((int64_t*)atomic, (int64_t)value); } static FOG_INLINE bool cmpXchg(int64_t* atomic, int64_t compar, int64_t value) { return (bool)(_MSINTRIN_(InterlockedCompareExchange64)((int64_t*)atomic, (int64_t)value, (int64_t)compar) == (int64_t)compar); } static FOG_INLINE int64_t get(const int64_t* atomic) { return *(volatile const int64_t *)atomic; } static FOG_INLINE void inc(int64_t* atomic) { _MSINTRIN_(InterlockedIncrement64)((int64_t*)atomic); } static FOG_INLINE void dec(int64_t* atomic) { _MSINTRIN_(InterlockedDecrement64)((int64_t*)atomic); } static FOG_INLINE void add(int64_t* atomic, int64_t value) { _MSINTRIN_(InterlockedExchangeAdd64)((int64_t*)atomic, (int64_t)value); } static FOG_INLINE void sub(int64_t* atomic, int64_t value) { _MSINTRIN_(InterlockedExchangeAdd64)((int64_t*)atomic, (int64_t)((value ^ FOG_UINT64_C(0xFFFFFFFFFFFFFFFF)) + FOG_UINT64_C(1))); } static FOG_INLINE int64_t addXchg(int64_t* atomic, int64_t value) { return (int64_t)_MSINTRIN_(InterlockedExchangeAdd64)((int64_t*)atomic, (int64_t)value); } static FOG_INLINE int64_t subXchg(int64_t* atomic, int64_t value) { return (int64_t)_MSINTRIN_(InterlockedExchangeAdd64)((int64_t*)atomic, (int64_t)((value ^ FOG_UINT64_C(0xFFFFFFFFFFFFFFFF)) + FOG_UINT64_C(1))); } static FOG_INLINE bool deref(int64_t* atomic) { return _MSINTRIN_(InterlockedDecrement64)((int64_t*)atomic) == FOG_INT64_C(0); } }; // Specialize. template<> struct AtomicOperationHelper<8> : public AtomicInt64 {}; #endif // FOG_ARCH_BITS == 64 } // Fog namespace // [Cleanup] #undef _MSINTRIN_ // [Guard] #endif // _FOG_CORE_ATOMIC_H
[ "wintercoredev@gmail.com" ]
wintercoredev@gmail.com
7f409d38153d16d3ce93aece1c49410c5fdb8b23
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Targets/CommonLib/S60/src/WFTextUtil.cpp
ce008a028f7978a9eb363b36ba77e9259c94bd03
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
20,691
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd 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 "WFTextUtil.h" #include <coemain.h> #include <stdlib.h> #include <stdio.h> #include <utf.h> #include <algorithm> #include <ctype.h> #include "nav2util.h" enum TWFTextUtilPanics { EStrSepArgNull = 0, }; _LIT(KWFTextUtil, "TextUtil"); #define ASSERT_ALWAYS(cond, panic) \ __ASSERT_ALWAYS((cond), User::Panic(KWFTextUtil, (panic))) char * WFTextUtil::stripPhoneNumberL(const char *src) { if (!src) return NULL; TInt s = 0; TInt d = 0; TInt len = strlen(src); char *dst = new (ELeave) char[len+1]; /* Cannot get larger than original. */ if (src[s] == '+') { dst[d++] = src[s++]; } while (s < len) { if (src[s] >= '0' && src[s] <= '9') { /* Digit. */ dst[d++] = src[s]; } s++; } dst[d] = 0; /* Nultermination. */ return dst; } char * WFTextUtil::uint32AsStringL(uint32 num) { char *str = new (ELeave) char[16]; /* Uint32 cannot be larger than 12 characters. */ sprintf(str, "%"PRIu32, num); return str; } char * WFTextUtil::TDesCToUtf8L(const TDesC& inbuf) { char *result; HBufC8* temp; temp = HBufC8::NewLC(inbuf.Length()*4); TPtr8 temp_ptr = temp->Des(); TInt truncated = CnvUtfConverter::ConvertFromUnicodeToUtf8(temp_ptr, inbuf); if (truncated != KErrNone) { /* truncated now contains either an error or the number of */ /* characters left untranslated. */ /* Do something useful here */ } TInt len = temp->Length(); result = new (ELeave) char[len+4]; int i = 0; while (i < len) { result[i] = (*temp)[i]; i++; } result[i] = 0; CleanupStack::PopAndDestroy(temp); return result; } char * WFTextUtil::TDesCToUtf8LC(const TDesC& inbuf) { char *result = TDesCToUtf8L(inbuf); CleanupStack::PushL(result); return result; } TInt WFTextUtil::Utf8ToTDes(const char *utf8str, TDes &outBuf, int length) { if (!utf8str) { outBuf.Zero(); return 0; } TPtrC8 tmp; tmp.Set(reinterpret_cast<const unsigned char*>(utf8str), length); TInt res = CnvUtfConverter::ConvertToUnicodeFromUtf8(outBuf, tmp); return res; } TInt WFTextUtil::Utf8ToTDes(const char *utf8str, TDes &outBuf) { if (!utf8str) { outBuf.Zero(); return 0; } TPtrC8 tmp; tmp.Set(reinterpret_cast<const unsigned char*>(utf8str), strlen(utf8str)); TInt res = CnvUtfConverter::ConvertToUnicodeFromUtf8(outBuf, tmp); return res; } HBufC* WFTextUtil::Utf8Alloc(const char *utf8str) { if(!utf8str){ return NULL; } HBufC *unicodeStr = HBufC::New(strlen(utf8str)+1); if(unicodeStr){ TPtr temp_ptr = unicodeStr->Des(); /* Yes, this variable is necessary. */ TInt res = Utf8ToTDes(utf8str, temp_ptr); res = res; /* Unused at the moment */ } return unicodeStr; } HBufC* WFTextUtil::Utf8AllocL(const char *utf8str, int length) { HBufC* unicodeStr = Utf8AllocLC(utf8str, length); CleanupStack::Pop(unicodeStr); return unicodeStr; } HBufC* WFTextUtil::Utf8AllocL(const char *utf8str) { HBufC* unicodeStr = Utf8AllocLC(utf8str); CleanupStack::Pop(unicodeStr); return unicodeStr; } HBufC* WFTextUtil::Utf8ToHBufCL(const char *utf8str) { return Utf8AllocL(utf8str); } HBufC* WFTextUtil::Utf8AllocLC(const char *utf8str, int length) { if(!utf8str){ CleanupStack::PushL((TAny*)0); return NULL; } HBufC *unicodeStr = HBufC::NewL(length+1); CleanupStack::PushL(unicodeStr); TPtr temp_ptr = unicodeStr->Des(); /* Yes, this variable is necessary. */ TInt res = Utf8ToTDes(utf8str, temp_ptr, length); res = res; /* Unused at the moment */ return unicodeStr; } HBufC* WFTextUtil::Utf8AllocLC(const char *utf8str) { if(!utf8str){ CleanupStack::PushL((TAny*)0); return NULL; } HBufC *unicodeStr = HBufC::NewL(strlen(utf8str)+1); CleanupStack::PushL(unicodeStr); TPtr temp_ptr = unicodeStr->Des(); /* Yes, this variable is necessary. */ TInt res = Utf8ToTDes(utf8str, temp_ptr); res = res; /* Unused at the moment */ return unicodeStr; } HBufC* WFTextUtil::Utf8ToHBufCLC(const char *utf8str) { return Utf8AllocLC(utf8str); } TBool WFTextUtil::MatchesResourceStringL(const TDesC &string, TInt resourceId) { HBufC *tmp; TBool result = EFalse; tmp = CCoeEnv::Static()->AllocReadResourceLC( resourceId ); result = string.Find(*tmp) == 0; CleanupStack::PopAndDestroy(tmp); return result; } char* WFTextUtil::strsep(char** stringp, const char* delim) { ASSERT_ALWAYS(stringp != NULL, EStrSepArgNull); char* const token = *stringp; //token always starts at *stringp if(*stringp){ //count the characters not in delim. const size_t tokenLen = strcspn(*stringp, delim); *stringp += tokenLen; //jump to delim. if(**stringp != '\0'){ //found a delim **stringp = '\0'; //part string *stringp += 1; //start of next token. } else { //no delim *stringp = NULL; //indicate end of input. } } return token; } char* WFTextUtil::strdupLC(const char* aSrc) { if(!aSrc){ return NULL; } TInt len = strlen(aSrc) + 1; if(len > KMaxTInt/2){ User::Leave(KErrArgument); } char* result = new (ELeave) char[len]; CleanupStack::PushL(result); strcpy(result, aSrc); return result; } char* WFTextUtil::strdupL(const char* aSrc) { char* result = NULL; if(aSrc){ result = strdupLC(aSrc); CleanupStack::Pop(result); } return result; } HBufC8* WFTextUtil::DupAllocLC(const char* src) { if(!src){ CleanupStack::PushL((TAny*)0); return NULL; } HBufC8* ret = HBufC8::NewLC(strlen(src) + 4); ret->operator=(reinterpret_cast<const TUint8*>(src)); return ret; } HBufC8* WFTextUtil::DupAllocL(const char* src) { HBufC8* ret = DupAllocLC(src); CleanupStack::Pop(ret); return ret; } HBufC8* WFTextUtil::DupAlloc(const char* src) { HBufC8* ret = HBufC8::New(strlen(src) + 4); if(ret){ *ret = reinterpret_cast<const TText8*>(src); } return ret; } TBool WFTextUtil::ParseHost(const TDesC8& aArg, TDes8& aHost, TUint& aPort) { TBool ret = EFalse; // find the ':' character in the string. TInt colonPos = aArg.Find(_L8(":")); if(colonPos != KErrNotFound && colonPos > 0){ TPtrC8 host = aArg.Left(colonPos); TPtrC8 port = aArg.Mid(colonPos+1); TLex8 portParser(port); TUint uport = 0; if(portParser.Val(uport) == KErrNone && portParser.Remainder().Length() == 0){ if(aHost.MaxLength() >= host.Length()){ aPort = uport; aHost = host; ret = ETrue; } } } return ret; } TBool WFTextUtil::ParseHost(const TDesC16& aArg, TDes16& aHost, TUint& aPort) { TBool ret = EFalse; // find the ':' character in the string. TInt colonPos = aArg.Find(_L16(":")); if(colonPos != KErrNotFound && colonPos > 0){ TPtrC16 host = aArg.Left(colonPos); TPtrC16 port = aArg.Mid(colonPos+1); TLex16 portParser(port); TUint uport = 0; if(portParser.Val(uport) == KErrNone && portParser.Remainder().Length() == 0){ if(aHost.MaxLength() >= host.Length()){ aPort = uport; aHost = host; ret = ETrue; } } } return ret; } const uint32 unicodeToIso8859_1[][2] = { { 0x102, 0x41 }, // iso-8859-2:0xc3 { 0x103, 0x61 }, // iso-8859-2:0xe3 { 0x104, 0x41 }, // iso-8859-2:0xa1 { 0x105, 0x61 }, // iso-8859-2:0xb1 { 0x106, 0x43 }, // iso-8859-2:0xc6 { 0x107, 0x63 }, // iso-8859-2:0xe6 { 0x10c, 0x43 }, // iso-8859-2:0xc8 { 0x10d, 0x63 }, // iso-8859-2:0xe8 { 0x10e, 0x44 }, // iso-8859-2:0xcf { 0x10f, 0x64 }, // iso-8859-2:0xef { 0x110, 0x44 }, // iso-8859-2:0xd0 { 0x111, 0x64 }, // iso-8859-2:0xf0 { 0x118, 0x45 }, // iso-8859-2:0xca { 0x119, 0x65 }, // iso-8859-2:0xea { 0x11a, 0x45 }, // iso-8859-2:0xcc { 0x11b, 0x65 }, // iso-8859-2:0xec { 0x139, 0x4c }, // iso-8859-2:0xc5 { 0x13a, 0x6c }, // iso-8859-2:0xe5 { 0x13d, 0x4c }, // iso-8859-2:0xa5 { 0x13e, 0x6c }, // iso-8859-2:0xb5 { 0x141, 0x4c }, // iso-8859-2:0xa3 { 0x142, 0x6c }, // iso-8859-2:0xb3 { 0x143, 0x4e }, // iso-8859-2:0xd1 { 0x144, 0x6e }, // iso-8859-2:0xf1 { 0x147, 0x4e }, // iso-8859-2:0xd2 { 0x148, 0x6e }, // iso-8859-2:0xf2 { 0x150, 0x4f }, // iso-8859-2:0xd5 { 0x151, 0x6f }, // iso-8859-2:0xf5 { 0x154, 0x52 }, // iso-8859-2:0xc0 { 0x155, 0x72 }, // iso-8859-2:0xe0 { 0x158, 0x52 }, // iso-8859-2:0xd8 { 0x159, 0x72 }, // iso-8859-2:0xf8 { 0x15a, 0x53 }, // iso-8859-2:0xa6 { 0x15b, 0x73 }, // iso-8859-2:0xb6 { 0x15e, 0x53 }, // iso-8859-2:0xaa { 0x15f, 0x73 }, // iso-8859-2:0xba { 0x160, 0x53 }, // iso-8859-2:0xa9 { 0x161, 0x73 }, // iso-8859-2:0xb9 { 0x162, 0x54 }, // iso-8859-2:0xde { 0x163, 0x74 }, // iso-8859-2:0xfe { 0x164, 0x54 }, // iso-8859-2:0xab { 0x165, 0x74 }, // iso-8859-2:0xbb { 0x16e, 0x55 }, // iso-8859-2:0xd9 { 0x16f, 0x75 }, // iso-8859-2:0xf9 { 0x170, 0x55 }, // iso-8859-2:0xdb { 0x171, 0x75 }, // iso-8859-2:0xfb { 0x179, 0x5a }, // iso-8859-2:0xac { 0x17a, 0x7a }, // iso-8859-2:0xbc { 0x17b, 0x5a }, // iso-8859-2:0xaf { 0x17c, 0x7a }, // iso-8859-2:0xbf { 0x17d, 0x5a }, // iso-8859-2:0xae { 0x17e, 0x7a }, // iso-8859-2:0xbe { 0x2c7, 0x20 }, // iso-8859-2:0xb7 caron { 0x2d8, 0x20 }, // iso-8859-2:0xa2 breve { 0x2d9, 0x20 }, // iso-8859-2:0xff dot above { 0x2db, 0x20 }, // iso-8859-2:0xb2 ogonek { 0x2dd, 0x20 }, // iso-8859-2:0xbd double acute { 0x0, 0x0 }, }; char * WFTextUtil::newTDesDupL(const TDesC16 &inbuf) { #if !defined (NAV2_USE_UTF8) char *ret; int length = inbuf.Length(); int i = 0; User::LeaveIfNull(ret = new char[length+1]); while (i < length) { if (inbuf[i] > 255) { int j = 0; while (unicodeToIso8859_1[j][0]) { if (unicodeToIso8859_1[j][0] == inbuf[i]) { /* Match! */ ret[i] = unicodeToIso8859_1[j][1]; break; } j++; } if (!unicodeToIso8859_1[j][0]) { ret[i] = 0x20; /* Space. */ } } else { ret[i] = inbuf[i]; } i++; } ret[i] = 0; return ret; #else return TDesCToUtf8L(inbuf); #endif } char * WFTextUtil::newTDesDupLC(const TDesC16 &inbuf) { #if !defined (NAV2_USE_UTF8) char *ret; int length = inbuf.Length(); int i = 0; ret = new(ELeave) char[length+1]; CleanupStack::PushL(ret); while (i < length) { if (inbuf[i] > 255) { int j = 0; while (unicodeToIso8859_1[j][0]) { if (unicodeToIso8859_1[j][0] == inbuf[i]) { /* Match! */ ret[i] = unicodeToIso8859_1[j][1]; break; } j++; } if (!unicodeToIso8859_1[j][0]) { ret[i] = 0x20; /* Space. */ } } else { ret[i] = inbuf[i]; } i++; } ret[i] = 0; return ret; #else return TDesCToUtf8LC(inbuf); #endif } char* WFTextUtil::newTDesDupL(const TDesC8 &inbuf) { char* ret = newTDesDupLC(inbuf); CleanupStack::Pop(ret); return ret; } char* WFTextUtil::newTDesDupLC(const TDesC8& inbuf) { char* ret = new (ELeave) char[inbuf.Length() + 1]; CleanupStack::PushL(ret); TPtr8 ret_p(reinterpret_cast<TText8*>(ret), inbuf.Length() + 1); ret_p = inbuf; ret_p.ZeroTerminate(); return ret; } int WFTextUtil::char2TDes(TDes &dest, const char* src) { dest.Zero(); if (!src) { dest.PtrZ(); return 0; } #if !defined (NAV2_USE_UTF8) int length = strlen(src); int i = 0; //Crashes if we try to write more than maxlength in the buffer if( length >= dest.MaxLength() ) length = dest.MaxLength()-1; while (i < length) { dest.Append(uint8(src[i])); i++; } dest.PtrZ(); return length; #else return Utf8ToTDes(src, dest); #endif } int WFTextUtil::char2HBufC(HBufC *dest, const char* src) { #if !defined (NAV2_USE_UTF8) dest->Des().Zero(); if (!src) { dest->Des().PtrZ(); return 0; } int length = strlen(src); int i = 0; //Crashes if we try to write more than maxlength in the buffer if( length >= dest->Des().MaxLength() ) length = dest->Des().MaxLength()-1; while (i < length) { dest->Des().Append(uint8(src[i])); i++; } dest->Des().PtrZ(); return length; #else TPtr destPtr = dest->Des(); return Utf8ToTDes(src, destPtr); #endif } HBufC* WFTextUtil::AllocLC(const char* src) { #if !defined (NAV2_USE_UTF8) if(!src){ CleanupStack::PushL((TAny*)0); return NULL; } HBufC* ret = HBufC::NewLC(strlen(src)); TPtrC8 tmp; tmp.Set(reinterpret_cast<const unsigned char*>(src), strlen(src)); TPtr ptr = ret->Des(); TDesWiden(ptr, tmp); return ret; #else return Utf8AllocLC(src); #endif } HBufC* WFTextUtil::AllocL(const char* src) { #if !defined (NAV2_USE_UTF8) HBufC* ret = AllocLC(src); CleanupStack::Pop(ret); return ret; #else return Utf8AllocL(src); #endif } HBufC* WFTextUtil::Alloc(const char* aSrc) { #if !defined (NAV2_USE_UTF8) HBufC* ret = HBufC::New(strlen(aSrc)); if(ret){ TPtrC8 tmp; tmp.Set(reinterpret_cast<const unsigned char*>(src), strlen(src)); TPtr ptr = ret->Des(); TDesWiden(ptr, tmp); } return ret; #else return Utf8Alloc(aSrc); #endif } HBufC* WFTextUtil::AllocLC(const char* aSrc, int aLength) { #if !defined (NAV2_USE_UTF8) if(!src){ CleanupStack::PushL((TAny*)0); return NULL; } HBufC* ret = HBufC::NewLC(aLength); TPtrC8 tmp; tmp.Set(reinterpret_cast<const unsigned char*>(src), aLength); TPtr ptr = ret->Des(); TDesWiden(ptr, tmp); return ret; #else return Utf8AllocLC(aSrc, aLength); #endif } HBufC* WFTextUtil::AllocL(const char* aSrc, int aLength) { #if !defined (NAV2_USE_UTF8) HBufC* ret = AllocLC(src, aLength); CleanupStack::Pop(ret); return ret; #else return Utf8AllocL(aSrc, aLength); #endif } TBool WFTextUtil::TDesWiden(TDes16 &aDst, const TDesC8& aSrc) { TBool ret; if((ret = (aDst.MaxLength() >= aSrc.Length()))){ aDst.SetLength(aSrc.Length()); for(TInt i = 0; i < aSrc.Length(); ++i){ aDst[i] = aSrc[i]; } } return ret; } HBufC8* WFTextUtil::NarrowLC(const TDesC& aSrc) { HBufC8* ret = HBufC8::NewLC(aSrc.Length()); ret->Des().Copy(aSrc); return ret; } TBool WFTextUtil::TDesCopy(TDes& dst, const TDesC& src) { dst.Copy(src.Ptr(), std::min(dst.MaxLength(), src.Length())); return dst.MaxLength() >= src.Length(); } TBool WFTextUtil::TDesCopy(TDes8& dst, const TDesC16& src) { #ifndef NAV2_USE_UTF8 dst.Copy(src.Ptr(), std::min(dst.MaxLength(), src.Length())); return dst.MaxLength() >= src.Length(); #else return CnvUtfConverter::ConvertFromUnicodeToUtf8(dst, src); #endif } TBool WFTextUtil::TDesAppend(TDes& dst, const TDesC& src) { TInt available = dst.MaxLength() - dst.Length(); dst.Append(src.Ptr(), std::min(available, src.Length())); return available >= src.Length(); } TBool WFTextUtil::TDesAppend(TDes& dst, const char* src) { TBool ret = ETrue; if(src){ HBufC* tmp = HBufC::New(strlen(src) + 4); if(tmp){ char2HBufC(tmp, src); ret = TDesAppend(dst, *tmp); delete tmp; } else { ret = EFalse; } } return ret; } HBufC* WFTextUtil::SearchAndReplaceL(const TDesC& aSrc, const TDesC& aSearch, const TDesC& aReplace) { TPtrC lineleft(aSrc); TInt pos = 0; CPtrCArray* subs = new (ELeave) CPtrCArray(4); CleanupStack::PushL(subs); while(KErrNotFound != (pos = lineleft.Find(aSearch))){ TPtrC part(lineleft.Left(pos)); lineleft.Set(lineleft.Mid(pos + aSearch.Length())); //skip matched part subs->AppendL(part); } subs->AppendL(lineleft); TInt lengthOFSubs = 0; for(TInt q = 0; q < subs->Count(); ++q){ lengthOFSubs += (*subs)[q].Length() + aReplace.Length(); } HBufC* constructed = HBufC::NewL(lengthOFSubs); for(TInt w = 0; w < subs->Count() - 1; ++w){ constructed->Des().Append((*subs)[w]); constructed->Des().Append(aReplace); } constructed->Des().Append((*subs)[subs->Count() - 1]); CleanupStack::PopAndDestroy(subs); return constructed; } void WFTextUtil::SearchAndReplace(TDes& aSrc, TChar aSearch, TText aReplace) { TInt pos = KErrNotFound; TPtrC ptr(&aReplace, 1); while(KErrNotFound != (pos = aSrc.Locate(aSearch))){ aSrc.Replace(pos, 1, ptr); } } HBufC* WFTextUtil::SearchAndReplaceLC(const TDesC& aSrc, TChar aSearch, TText aReplace) { HBufC* dest = aSrc.AllocLC(); TPtr dest_ptr = dest->Des(); SearchAndReplace(dest_ptr, aSearch, aReplace); return dest; } TBool WFTextUtil::Equal(const TText8* aLhs, const TText8* aRhs) { return Equal(reinterpret_cast<const char*>(aLhs), reinterpret_cast<const char*>(aRhs)); } TBool WFTextUtil::Equal(const char* aLhs, const char* aRhs) { return isab::strequ(aLhs, aRhs); } #define CREATE_TPTRC8(name, from) \ TPtrC8 name(from); \ name.Set(from, User::StringLength(from)) TBool WFTextUtil::Equal(const TText8* aLhs, const TDesC16& aRhs) { CREATE_TPTRC8(lhs, aLhs); return Equal(lhs, aRhs); } TBool WFTextUtil::Equal(const TText8* aLhs, const TDesC8& aRhs) { CREATE_TPTRC8(lhs, aLhs); return Equal(lhs, aRhs); } TBool WFTextUtil::Equal(const char* aLhs, const TDesC16& aRhs) { return Equal(reinterpret_cast<const TText8*>(aLhs), aRhs); } TBool WFTextUtil::Equal(const char* aLhs, const TDesC8& aRhs) { return Equal(reinterpret_cast<const TText8*>(aLhs), aRhs); } TBool WFTextUtil::Equal(const TDesC16& aLhs, const TDesC8& aRhs) { TBool ret = EFalse; #ifdef NAV2_USE_UTF8 HBufC16* wide = HBufC::New(aRhs.Length()); if(wide){ TPtr16 wide_p = wide->Des(); CnvUtfConverter::ConvertToUnicodeFromUtf8(wide_p, aRhs); ret = (wide_p == aLhs); } delete wide; #else ret = (aLhs.Length() == aRhs.Length()); if(ret){ for(TInt i = 0; ret && i < aLhs.Length(); ++i){ ret = (aLhs[i] == aRhs[i];) } } #endif return ret; } // from mc2 void WFTextUtil::trimEnd(char* s) { if (s != NULL) { uint32 tmp = strlen(s)-1; while( isspace(s[tmp]) && (tmp > 0)) { s[tmp] = '\0'; tmp--; } } }
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
936f28c3971ae60176f3dfe89bcb7a577d87d2fb
efdd5a69e84d75d5c906c43de6efb335c80aecb9
/src/Index.re
e81c6860eba7ee5aaf678f52d63704606d53857d
[]
no_license
kennetpostigo/mangosnake
c5d713e82dc99dd79178ed2a6aa9aa2277f42205
3bf01ed1a21416089dcbf8f096fbf8ef92e84860
refs/heads/master
2021-09-06T07:38:33.706976
2018-02-03T21:43:02
2018-02-03T21:43:02
120,058,501
1
0
null
null
null
null
UTF-8
C++
false
false
52
re
ReactDOMRe.renderToElementWithId(<Canvas />, "app");
[ "kennetfpostigo@gmail.com" ]
kennetfpostigo@gmail.com
8326e5f9f6e80d5749438a935eb9e1be5347b437
8bd9ac901535033737a70fa5f677a2d23114aabf
/STL/priority.cpp
81bbd343c7b81aabe6fda91f3840c71f28141fe9
[]
no_license
Double-Wen/CPlus
5657c3e6a73d113fcc5d6f017668534924641654
b24fe08f8f254c1da4b6c23b45b78004b98fd1d4
refs/heads/master
2022-11-14T20:45:40.686160
2020-07-15T15:46:51
2020-07-15T15:46:51
258,478,082
1
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
#include <iostream> #include <queue> using namespace std; int main() { priority_queue<int> q; q.push(5); q.push(1); q.push(3); q.push(6); for(int i=0; i<4; i++) { cout << q.top() << endl; //注意优先队列和传统队列不同, //它是用堆而不是线性结构来维护的, //所以它只有top来取堆顶元素 //而不是传统的线性结构的front和back q.pop(); } return 0; }
[ "tcliuwenwen@126.com" ]
tcliuwenwen@126.com
cf76cbcac9d51ccce976f98a8cef5e4de243234c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-old-new/CMake-old-new-joern/Kitware_CMake_old_new_old_function_1439.cpp
f1d4b8115fc2b3b92633bac69f823f486335d936
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,146
cpp
int cmCTest::CoverageDirectory() { std::cout << "Performing coverage" << std::endl; std::vector<std::string> files; std::vector<std::string> cfiles; std::vector<std::string> cdirs; bool done = false; std::string::size_type cc; std::string glob; std::map<std::string, std::string> allsourcefiles; std::map<std::string, std::string> allbinaryfiles; std::string start_time = ::CurrentTime(); // Find all source files. std::string sourceDirectory = m_DartConfiguration["SourceDirectory"]; if ( sourceDirectory.size() == 0 ) { std::cerr << "Cannot find SourceDirectory key in the DartConfiguration.tcl" << std::endl; return 1; } cdirs.push_back(sourceDirectory); while ( !done ) { if ( cdirs.size() <= 0 ) { break; } glob = cdirs[cdirs.size()-1] + "/*"; //std::cout << "Glob: " << glob << std::endl; cdirs.pop_back(); if ( cmSystemTools::SimpleGlob(glob, cfiles, 1) ) { for ( cc = 0; cc < cfiles.size(); cc ++ ) { allsourcefiles[cmSystemTools::GetFilenameName(cfiles[cc])] = cfiles[cc]; } } if ( cmSystemTools::SimpleGlob(glob, cfiles, -1) ) { for ( cc = 0; cc < cfiles.size(); cc ++ ) { if ( cfiles[cc] != "." && cfiles[cc] != ".." ) { cdirs.push_back(cfiles[cc]); } } } } // find all binary files cdirs.push_back(cmSystemTools::GetCurrentWorkingDirectory()); while ( !done ) { if ( cdirs.size() <= 0 ) { break; } glob = cdirs[cdirs.size()-1] + "/*"; //std::cout << "Glob: " << glob << std::endl; cdirs.pop_back(); if ( cmSystemTools::SimpleGlob(glob, cfiles, 1) ) { for ( cc = 0; cc < cfiles.size(); cc ++ ) { allbinaryfiles[cmSystemTools::GetFilenameName(cfiles[cc])] = cfiles[cc]; } } if ( cmSystemTools::SimpleGlob(glob, cfiles, -1) ) { for ( cc = 0; cc < cfiles.size(); cc ++ ) { if ( cfiles[cc] != "." && cfiles[cc] != ".." ) { cdirs.push_back(cfiles[cc]); } } } } std::map<std::string, std::string>::iterator sit; for ( sit = allbinaryfiles.begin(); sit != allbinaryfiles.end(); sit ++ ) { const std::string& fname = sit->second; //std::cout << "File: " << fname << std::endl; if ( strcmp(fname.substr(fname.size()-3, 3).c_str(), ".da") == 0 ) { files.push_back(fname); } } if ( files.size() == 0 ) { std::cout << "Cannot find any coverage information files (.da)" << std::endl; return 1; } std::ofstream log; if (!this->OpenOutputFile("Temporary", "Coverage.log", log)) { std::cout << "Cannot open log file" << std::endl; return 1; } log.close(); if (!this->OpenOutputFile(m_CurrentTag, "Coverage.xml", log)) { std::cout << "Cannot open log file" << std::endl; return 1; } std::string opath = m_ToplevelPath + "/Testing/Temporary/Coverage"; cmSystemTools::MakeDirectory(opath.c_str()); for ( cc = 0; cc < files.size(); cc ++ ) { std::string command = "gcov -l \"" + files[cc] + "\""; std::string output; int retVal = 0; //std::cout << "Run gcov on " << files[cc] << std::flush; //std::cout << " --- Run [" << command << "]" << std::endl; bool res = true; if ( !m_ShowOnly ) { res = cmSystemTools::RunCommand(command.c_str(), output, retVal, opath.c_str(), m_Verbose); } if ( res && retVal == 0 ) { //std::cout << " - done" << std::endl; } else { //std::cout << " - fail" << std::endl; } } files.clear(); glob = opath + "/*"; if ( !cmSystemTools::SimpleGlob(glob, cfiles, 1) ) { std::cout << "Cannot found any coverage files" << std::endl; return 1; } std::map<std::string, std::vector<std::string> > sourcefiles; for ( cc = 0; cc < cfiles.size(); cc ++ ) { std::string& fname = cfiles[cc]; //std::cout << "File: " << fname << std::endl; if ( strcmp(fname.substr(fname.size()-5, 5).c_str(), ".gcov") == 0 ) { files.push_back(fname); std::string::size_type pos = fname.find(".da."); if ( pos != fname.npos ) { pos += 4; std::string::size_type epos = fname.size() - pos - strlen(".gcov"); std::string nf = fname.substr(pos, epos); //std::cout << "Substring: " << nf << std::endl; if ( allsourcefiles.find(nf) != allsourcefiles.end() || allbinaryfiles.find(nf) != allbinaryfiles.end() ) { std::vector<std::string> &cvec = sourcefiles[nf]; cvec.push_back(fname); } } } } for ( cc = 0; cc < files.size(); cc ++ ) { //std::cout << "File: " << files[cc] << std::endl; } std::map<std::string, std::vector<std::string> >::iterator it; cmCTest::tm_CoverageMap coverageresults; log << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" << "<Site BuildName=\"" << m_DartConfiguration["BuildName"] << "\" BuildStamp=\"" << m_CurrentTag << "-" << this->GetTestModelString() << "\" Name=\"" << m_DartConfiguration["Site"] << "\">\n" << "<Coverage>\n" << "\t<StartDateTime>" << start_time << "</StartDateTime>" << std::endl; int total_tested = 0; int total_untested = 0; for ( it = sourcefiles.begin(); it != sourcefiles.end(); it ++ ) { //std::cerr << "Source file: " << it->first << std::endl; std::vector<std::string> &gfiles = it->second; for ( cc = 0; cc < gfiles.size(); cc ++ ) { //std::cout << "\t" << gfiles[cc] << std::endl; std::ifstream ifile(gfiles[cc].c_str()); if ( !ifile ) { std::cout << "Cannot open file: " << gfiles[cc].c_str() << std::endl; } ifile.seekg (0, std::ios::end); int length = ifile.tellg(); ifile.seekg (0, std::ios::beg); char *buffer = new char [ length + 1 ]; ifile.read(buffer, length); buffer [length] = 0; //std::cout << "Read: " << buffer << std::endl; std::vector<cmStdString> lines; cmSystemTools::Split(buffer, lines); delete [] buffer; cmCTest::cmCTestCoverage& cov = coverageresults[it->first]; std::vector<int>& covlines = cov.m_Lines; if ( cov.m_FullPath == "" ) { covlines.insert(covlines.begin(), lines.size(), -1); if ( allsourcefiles.find(it->first) != allsourcefiles.end() ) { cov.m_FullPath = allsourcefiles[it->first]; } else if ( allbinaryfiles.find(it->first) != allbinaryfiles.end() ) { cov.m_FullPath = allbinaryfiles[it->first]; } cov.m_AbsolutePath = cov.m_FullPath; std::string src_dir = m_DartConfiguration["SourceDirectory"]; if ( src_dir[src_dir.size()-1] != '/' ) { src_dir = src_dir + "/"; } std::string::size_type spos = cov.m_FullPath.find(src_dir); if ( spos == 0 ) { cov.m_FullPath = std::string("./") + cov.m_FullPath.substr(src_dir.size()); } else { //std::cerr << "Compare -- " << cov.m_FullPath << std::endl; //std::cerr << " -- " << src_dir << std::endl; continue; } } for ( cc = 0; cc < lines.size(); cc ++ ) { std::string& line = lines[cc]; std::string sub = line.substr(0, strlen(" ######")); int count = atoi(sub.c_str()); if ( sub.compare(" ######") == 0 ) { if ( covlines[cc] == -1 ) { covlines[cc] = 0; } cov.m_UnTested ++; //std::cout << "Untested - "; } else if ( count > 0 ) { if ( covlines[cc] == -1 ) { covlines[cc] = 0; } cov.m_Tested ++; covlines[cc] += count; //std::cout << "Tested[" << count << "] - "; } //std::cout << line << std::endl; } } } //std::cerr << "Finalizing" << std::endl; cmCTest::tm_CoverageMap::iterator cit; int ccount = 0; std::ofstream cfileoutput; int cfileoutputcount = 0; char cfileoutputname[100]; std::string local_start_time = ::CurrentTime(); std::string local_end_time; for ( cit = coverageresults.begin(); cit != coverageresults.end(); cit ++ ) { if ( ccount == 100 ) { local_end_time = ::CurrentTime(); cfileoutput << "\t<EndDateTime>" << local_end_time << "</EndDateTime>\n" << "</CoverageLog>\n" << "</Site>" << std::endl; cfileoutput.close(); std::cout << "Close file: " << cfileoutputname << std::endl; ccount = 0; } if ( ccount == 0 ) { sprintf(cfileoutputname, "CoverageLog-%d.xml", cfileoutputcount++); std::cout << "Open file: " << cfileoutputname << std::endl; if (!this->OpenOutputFile(m_CurrentTag, cfileoutputname, cfileoutput)) { std::cout << "Cannot open log file: " << cfileoutputname << std::endl; return 1; } local_start_time = ::CurrentTime(); cfileoutput << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" << "<Site BuildName=\"" << m_DartConfiguration["BuildName"] << "\" BuildStamp=\"" << m_CurrentTag << "-" << this->GetTestModelString() << "\" Site=\"" << m_DartConfiguration["Site"] << "\">\n" << "<CoverageLog>\n" << "\t<StartDateTime>" << local_start_time << "</StartDateTime>" << std::endl; } //std::cerr << "Final process of Source file: " << cit->first << std::endl; cmCTest::cmCTestCoverage &cov = cit->second; std::ifstream ifile(cov.m_AbsolutePath.c_str()); if ( !ifile ) { std::cerr << "Cannot open file: " << cov.m_FullPath.c_str() << std::endl; } ifile.seekg (0, std::ios::end); int length = ifile.tellg(); ifile.seekg (0, std::ios::beg); char *buffer = new char [ length + 1 ]; ifile.read(buffer, length); buffer [length] = 0; //std::cout << "Read: " << buffer << std::endl; std::vector<cmStdString> lines; cmSystemTools::Split(buffer, lines); delete [] buffer; cfileoutput << "\t<File Name=\"" << cit->first << "\" FullPath=\"" << cov.m_FullPath << std::endl << "\">\n" << "\t\t<Report>" << std::endl; for ( cc = 0; cc < lines.size(); cc ++ ) { cfileoutput << "\t\t<Line Number=\"" << static_cast<int>(cc) << "\" Count=\"" << cov.m_Lines[cc] << "\">" << cmCTest::MakeXMLSafe(lines[cc]) << "</Line>" << std::endl; } cfileoutput << "\t\t</Report>\n" << "\t</File>" << std::endl; total_tested += cov.m_Tested; total_untested += cov.m_UnTested; float cper = 0; float cmet = 0; if ( total_tested + total_untested > 0 ) { cper = (100 * static_cast<float>(cov.m_Tested)/ static_cast<float>(cov.m_Tested + cov.m_UnTested)); cmet = ( static_cast<float>(cov.m_Tested + 10) / static_cast<float>(cov.m_Tested + cov.m_UnTested + 10)); } char cmbuff[100]; char cpbuff[100]; sprintf(cmbuff, "%.2f", cmet); sprintf(cpbuff, "%.2f", cper); log << "\t<File Name=\"" << cit->first << "\" FullPath=\"" << cov.m_FullPath << "\" Covered=\"" << (cmet>0?"true":"false") << "\">\n" << "\t\t<LOCTested>" << cov.m_Tested << "</LOCTested>\n" << "\t\t<LOCUnTested>" << cov.m_UnTested << "</LOCUnTested>\n" << "\t\t<PercentCoverage>" << cpbuff << "</PercentCoverage>\n" << "\t\t<CoverageMetric>" << cmbuff << "</CoverageMetric>\n" << "\t</File>" << std::endl; ccount ++; } if ( ccount > 0 ) { local_end_time = ::CurrentTime(); cfileoutput << "\t<EndDateTime>" << local_end_time << "</EndDateTime>\n" << "</CoverageLog>\n" << "</Site>" << std::endl; cfileoutput.close(); } int total_lines = total_tested + total_untested; float percent_coverage = 100 * static_cast<float>(total_tested) / static_cast<float>(total_lines); if ( total_lines == 0 ) { percent_coverage = 0; } std::string end_time = ::CurrentTime(); char buffer[100]; sprintf(buffer, "%.2f", percent_coverage); log << "\t<LOCTested>" << total_tested << "</LOCTested>\n" << "\t<LOCUntested>" << total_untested << "</LOCUntested>\n" << "\t<LOC>" << total_lines << "</LOC>\n" << "\t<PercentCoverage>" << buffer << "</PercentCoverage>\n" << "\t<EndDateTime>" << end_time << "</EndDateTime>\n" << "</Coverage>\n" << "</Site>" << std::endl; std::cout << "\tCovered LOC: " << total_tested << std::endl << "\tNot covered LOC: " << total_untested << std::endl << "\tTotal LOC: " << total_lines << std::endl << "\tPercentage Coverage: " << percent_coverage << "%" << std::endl; return 1; }
[ "993273596@qq.com" ]
993273596@qq.com
bdd94532a729db65e92977ef6f633a42355b1bd9
dc1dff39e8c714ac9e5202d4d07aa19fea6d7a3a
/CocosGame/MyCocosGame/cocos2d/cocos/ui/UIAbstractCheckButton.cpp
c1078b42be94e830ee8c781152fc91c0bee6bdd6
[ "Apache-2.0" ]
permissive
djj182/GoogleDemo
4bd1e12757731cc077da6423ffc4c61cd99c0321
f734543437b14702b9fb7cfd20cda48500a88b91
refs/heads/master
2023-06-08T14:35:47.774505
2020-10-14T09:15:57
2020-10-14T09:15:57
272,388,973
1
0
null
null
null
null
UTF-8
C++
false
false
20,452
cpp
/**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.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. ****************************************************************************/ #include "ui/UIAbstractCheckButton.h" #include "2d/CCSprite.h" #include "editor-support/cocostudio/CocosStudioExtension.h" NS_CC_BEGIN namespace ui { static const int BACKGROUNDBOX_RENDERER_Z = (-1); static const int BACKGROUNDSELECTEDBOX_RENDERER_Z = (-1); static const int FRONTCROSS_RENDERER_Z = (-1); static const int BACKGROUNDBOXDISABLED_RENDERER_Z = (-1); static const int FRONTCROSSDISABLED_RENDERER_Z = (-1); AbstractCheckButton::AbstractCheckButton(): _backGroundBoxRenderer(nullptr), _backGroundSelectedBoxRenderer(nullptr), _frontCrossRenderer(nullptr), _backGroundBoxDisabledRenderer(nullptr), _frontCrossDisabledRenderer(nullptr), _isSelected(true), _isBackgroundSelectedTextureLoaded(false), _isBackgroundDisabledTextureLoaded(false), _isFrontCrossDisabledTextureLoaded(false), _backGroundTexType(TextureResType::LOCAL), _backGroundSelectedTexType(TextureResType::LOCAL), _frontCrossTexType(TextureResType::LOCAL), _backGroundDisabledTexType(TextureResType::LOCAL), _frontCrossDisabledTexType(TextureResType::LOCAL), _zoomScale(0.1f), _backgroundTextureScaleX(1.0), _backgroundTextureScaleY(1.0), _backGroundFileName(""), _backGroundSelectedFileName(""), _frontCrossFileName(""), _backGroundDisabledFileName(""), _frontCrossDisabledFileName(""), _backGroundBoxRendererAdaptDirty(true), _backGroundSelectedBoxRendererAdaptDirty(true), _frontCrossRendererAdaptDirty(true), _backGroundBoxDisabledRendererAdaptDirty(true), _frontCrossDisabledRendererAdaptDirty(true) { setTouchEnabled(true); } AbstractCheckButton::~AbstractCheckButton() { } bool AbstractCheckButton::init(const std::string& backGround, const std::string& backGroundSelected, const std::string& cross, const std::string& backGroundDisabled, const std::string& frontCrossDisabled, TextureResType texType) { bool ret = true; do { if (!Widget::init()) { ret = false; break; } setSelected(false); loadTextures(backGround, backGroundSelected, cross, backGroundDisabled, frontCrossDisabled, texType); } while (0); return ret; } bool AbstractCheckButton::init() { if (Widget::init()) { setSelected(false); return true; } return false; } void AbstractCheckButton::initRenderer() { _backGroundBoxRenderer = Sprite::create(); _backGroundSelectedBoxRenderer = Sprite::create(); _frontCrossRenderer = Sprite::create(); _backGroundBoxDisabledRenderer = Sprite::create(); _frontCrossDisabledRenderer = Sprite::create(); addProtectedChild(_backGroundBoxRenderer, BACKGROUNDBOX_RENDERER_Z, -1); addProtectedChild(_backGroundSelectedBoxRenderer, BACKGROUNDSELECTEDBOX_RENDERER_Z, -1); addProtectedChild(_frontCrossRenderer, FRONTCROSS_RENDERER_Z, -1); addProtectedChild(_backGroundBoxDisabledRenderer, BACKGROUNDBOXDISABLED_RENDERER_Z, -1); addProtectedChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); } void AbstractCheckButton::loadTextures(const std::string& backGround, const std::string& backGroundSelected, const std::string& cross, const std::string& backGroundDisabled, const std::string& frontCrossDisabled, TextureResType texType) { loadTextureBackGround(backGround,texType); loadTextureBackGroundSelected(backGroundSelected,texType); loadTextureFrontCross(cross,texType); loadTextureBackGroundDisabled(backGroundDisabled,texType); loadTextureFrontCrossDisabled(frontCrossDisabled,texType); } void AbstractCheckButton::loadTextureBackGround(const std::string& backGround,TextureResType texType) { _backGroundFileName = backGround; _backGroundTexType = texType; switch (_backGroundTexType) { case TextureResType::LOCAL: _backGroundBoxRenderer->setTexture(backGround); break; case TextureResType::PLIST: _backGroundBoxRenderer->setSpriteFrame(backGround); break; default: break; } this->setupBackgroundTexture(); } void AbstractCheckButton::setupBackgroundTexture() { this->updateChildrenDisplayedRGBA(); updateContentSizeWithTextureSize(_backGroundBoxRenderer->getContentSize()); _backGroundBoxRendererAdaptDirty = true; } void AbstractCheckButton::loadTextureBackGround(SpriteFrame* spriteFrame) { _backGroundBoxRenderer->setSpriteFrame(spriteFrame); this->setupBackgroundTexture(); } void AbstractCheckButton::loadTextureBackGroundSelected(const std::string& backGroundSelected,TextureResType texType) { _backGroundSelectedFileName = backGroundSelected; _isBackgroundSelectedTextureLoaded = !backGroundSelected.empty(); _backGroundSelectedTexType = texType; switch (_backGroundSelectedTexType) { case TextureResType::LOCAL: _backGroundSelectedBoxRenderer->setTexture(backGroundSelected); break; case TextureResType::PLIST: _backGroundSelectedBoxRenderer->setSpriteFrame(backGroundSelected); break; default: break; } this->setupBackgroundSelectedTexture(); } void AbstractCheckButton::loadTextureBackGroundSelected(SpriteFrame* spriteframe) { this->_backGroundSelectedBoxRenderer->setSpriteFrame(spriteframe); this->setupBackgroundSelectedTexture(); } void AbstractCheckButton::setupBackgroundSelectedTexture() { this->updateChildrenDisplayedRGBA(); _backGroundSelectedBoxRendererAdaptDirty = true; } void AbstractCheckButton::loadTextureFrontCross(const std::string& cross,TextureResType texType) { _frontCrossFileName = cross; _frontCrossTexType = texType; switch (_frontCrossTexType) { case TextureResType::LOCAL: _frontCrossRenderer->setTexture(cross); break; case TextureResType::PLIST: _frontCrossRenderer->setSpriteFrame(cross); break; default: break; } this->setupFrontCrossTexture(); } void AbstractCheckButton::loadTextureFrontCross(SpriteFrame* spriteFrame) { this->_frontCrossRenderer->setSpriteFrame(spriteFrame); this->setupFrontCrossTexture(); } void AbstractCheckButton::setupFrontCrossTexture() { this->updateChildrenDisplayedRGBA(); _frontCrossRendererAdaptDirty = true; } void AbstractCheckButton::loadTextureBackGroundDisabled(const std::string& backGroundDisabled,TextureResType texType) { _backGroundDisabledFileName = backGroundDisabled; _isBackgroundDisabledTextureLoaded = !backGroundDisabled.empty(); _backGroundDisabledTexType = texType; switch (_backGroundDisabledTexType) { case TextureResType::LOCAL: _backGroundBoxDisabledRenderer->setTexture(backGroundDisabled); break; case TextureResType::PLIST: _backGroundBoxDisabledRenderer->setSpriteFrame(backGroundDisabled); break; default: break; } this->setupBackgroundDisable(); } void AbstractCheckButton::loadTextureBackGroundDisabled(SpriteFrame* spriteframe) { this->_backGroundBoxDisabledRenderer->setSpriteFrame(spriteframe); this->setupBackgroundDisable(); } void AbstractCheckButton::setupBackgroundDisable() { this->updateChildrenDisplayedRGBA(); _backGroundBoxDisabledRendererAdaptDirty = true; } void AbstractCheckButton::loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled,TextureResType texType) { _frontCrossDisabledFileName = frontCrossDisabled; _isFrontCrossDisabledTextureLoaded = !frontCrossDisabled.empty(); _frontCrossDisabledTexType = texType; switch (_frontCrossDisabledTexType) { case TextureResType::LOCAL: _frontCrossDisabledRenderer->setTexture(frontCrossDisabled); break; case TextureResType::PLIST: _frontCrossDisabledRenderer->setSpriteFrame(frontCrossDisabled); break; default: break; } this->setupFrontCrossDisableTexture(); } void AbstractCheckButton::loadTextureFrontCrossDisabled(SpriteFrame* spriteframe) { this->_frontCrossDisabledRenderer->setSpriteFrame(spriteframe); this->setupFrontCrossDisableTexture(); } void AbstractCheckButton::setupFrontCrossDisableTexture() { this->updateChildrenDisplayedRGBA(); _frontCrossDisabledRendererAdaptDirty = true; } void AbstractCheckButton::onPressStateChangedToNormal() { _backGroundBoxRenderer->setVisible(true); _backGroundSelectedBoxRenderer->setVisible(false); _backGroundBoxDisabledRenderer->setVisible(false); _frontCrossDisabledRenderer->setVisible(false); _backGroundBoxRenderer->setGLProgramState(this->getNormalGLProgramState()); _frontCrossRenderer->setGLProgramState(this->getNormalGLProgramState()); _backGroundBoxRenderer->setScale(_backgroundTextureScaleX, _backgroundTextureScaleY); _frontCrossRenderer->setScale(_backgroundTextureScaleX, _backgroundTextureScaleY); if (_isSelected) { _frontCrossRenderer->setVisible(true); _frontCrossRendererAdaptDirty = true; } } void AbstractCheckButton::onPressStateChangedToPressed() { _backGroundBoxRenderer->setGLProgramState(this->getNormalGLProgramState()); _frontCrossRenderer->setGLProgramState(this->getNormalGLProgramState()); if (!_isBackgroundSelectedTextureLoaded) { _backGroundBoxRenderer->setScale(_backgroundTextureScaleX + _zoomScale, _backgroundTextureScaleY + _zoomScale); _frontCrossRenderer->setScale(_backgroundTextureScaleX + _zoomScale, _backgroundTextureScaleY + _zoomScale); } else { _backGroundBoxRenderer->setVisible(false); _backGroundSelectedBoxRenderer->setVisible(true); _backGroundBoxDisabledRenderer->setVisible(false); _frontCrossDisabledRenderer->setVisible(false); } } void AbstractCheckButton::onPressStateChangedToDisabled() { if (!_isBackgroundDisabledTextureLoaded || !_isFrontCrossDisabledTextureLoaded) { _backGroundBoxRenderer->setGLProgramState(this->getGrayGLProgramState()); _frontCrossRenderer->setGLProgramState(this->getGrayGLProgramState()); } else { _backGroundBoxRenderer->setVisible(false); _backGroundBoxDisabledRenderer->setVisible(true); } _backGroundSelectedBoxRenderer->setVisible(false); _frontCrossRenderer->setVisible(false); _backGroundBoxRenderer->setScale(_backgroundTextureScaleX, _backgroundTextureScaleY); _frontCrossRenderer->setScale(_backgroundTextureScaleX, _backgroundTextureScaleY); if (_isSelected) { _frontCrossDisabledRenderer->setVisible(true); _frontCrossDisabledRendererAdaptDirty = true; } } void AbstractCheckButton::setZoomScale(float scale) { _zoomScale = scale; } float AbstractCheckButton::getZoomScale()const { return _zoomScale; } void AbstractCheckButton::setSelected(bool selected) { if (selected == _isSelected) { return; } _isSelected = selected; _frontCrossRenderer->setVisible(_isSelected); } bool AbstractCheckButton::isSelected()const { return _isSelected; } void AbstractCheckButton::onSizeChanged() { Widget::onSizeChanged(); _backGroundBoxRendererAdaptDirty = true; _backGroundSelectedBoxRendererAdaptDirty = true; _frontCrossRendererAdaptDirty = true; _backGroundBoxDisabledRendererAdaptDirty = true; _frontCrossDisabledRendererAdaptDirty = true; } void AbstractCheckButton::adaptRenderers() { if (_backGroundBoxRendererAdaptDirty) { backGroundTextureScaleChangedWithSize(); _backGroundBoxRendererAdaptDirty = false; } if (_backGroundSelectedBoxRendererAdaptDirty) { backGroundSelectedTextureScaleChangedWithSize(); _backGroundSelectedBoxRendererAdaptDirty = false; } if (_frontCrossRendererAdaptDirty) { frontCrossTextureScaleChangedWithSize(); _frontCrossRendererAdaptDirty = false; } if (_backGroundBoxDisabledRendererAdaptDirty) { backGroundDisabledTextureScaleChangedWithSize(); _backGroundBoxDisabledRendererAdaptDirty = false; } if (_frontCrossDisabledRendererAdaptDirty) { frontCrossDisabledTextureScaleChangedWithSize(); _frontCrossDisabledRendererAdaptDirty = false; } } Size AbstractCheckButton::getVirtualRendererSize() const { return _backGroundBoxRenderer->getContentSize(); } Node* AbstractCheckButton::getVirtualRenderer() { return _backGroundBoxRenderer; } void AbstractCheckButton::backGroundTextureScaleChangedWithSize() { if (_ignoreSize) { _backGroundBoxRenderer->setScale(1.0f); _backgroundTextureScaleX = _backgroundTextureScaleY = 1.0f; } else { Size textureSize = _backGroundBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxRenderer->setScale(1.0f); _backgroundTextureScaleX = _backgroundTextureScaleY = 1.0f; return; } float scaleX = _contentSize.width / textureSize.width; float scaleY = _contentSize.height / textureSize.height; _backgroundTextureScaleX = scaleX; _backgroundTextureScaleY = scaleY; _backGroundBoxRenderer->setScaleX(scaleX); _backGroundBoxRenderer->setScaleY(scaleY); } _backGroundBoxRenderer->setPosition(_contentSize.width / 2, _contentSize.height / 2); } void AbstractCheckButton::backGroundSelectedTextureScaleChangedWithSize() { if (_ignoreSize) { _backGroundSelectedBoxRenderer->setScale(1.0f); } else { Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundSelectedBoxRenderer->setScale(1.0f); return; } float scaleX = _contentSize.width / textureSize.width; float scaleY = _contentSize.height / textureSize.height; _backGroundSelectedBoxRenderer->setScaleX(scaleX); _backGroundSelectedBoxRenderer->setScaleY(scaleY); } _backGroundSelectedBoxRenderer->setPosition(_contentSize.width / 2, _contentSize.height / 2); } void AbstractCheckButton::frontCrossTextureScaleChangedWithSize() { if (_ignoreSize) { _frontCrossRenderer->setScale(1.0f); } else { Size textureSize = _frontCrossRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossRenderer->setScale(1.0f); return; } float scaleX = _contentSize.width / textureSize.width; float scaleY = _contentSize.height / textureSize.height; _frontCrossRenderer->setScaleX(scaleX); _frontCrossRenderer->setScaleY(scaleY); } _frontCrossRenderer->setPosition(_contentSize.width / 2, _contentSize.height / 2); } void AbstractCheckButton::backGroundDisabledTextureScaleChangedWithSize() { if (_ignoreSize) { _backGroundBoxDisabledRenderer->setScale(1.0f); } else { Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxDisabledRenderer->setScale(1.0f); return; } float scaleX = _contentSize.width / textureSize.width; float scaleY = _contentSize.height / textureSize.height; _backGroundBoxDisabledRenderer->setScaleX(scaleX); _backGroundBoxDisabledRenderer->setScaleY(scaleY); } _backGroundBoxDisabledRenderer->setPosition(_contentSize.width / 2, _contentSize.height / 2); } void AbstractCheckButton::frontCrossDisabledTextureScaleChangedWithSize() { if (_ignoreSize) { _frontCrossDisabledRenderer->setScale(1.0f); } else { Size textureSize = _frontCrossDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossDisabledRenderer->setScale(1.0f); return; } float scaleX = _contentSize.width / textureSize.width; float scaleY = _contentSize.height / textureSize.height; _frontCrossDisabledRenderer->setScaleX(scaleX); _frontCrossDisabledRenderer->setScaleY(scaleY); } _frontCrossDisabledRenderer->setPosition(_contentSize.width / 2, _contentSize.height / 2); } void AbstractCheckButton::copySpecialProperties(Widget *widget) { AbstractCheckButton* abstractCheckButton = dynamic_cast<AbstractCheckButton*>(widget); if (abstractCheckButton) { loadTextureBackGround(abstractCheckButton->_backGroundBoxRenderer->getSpriteFrame()); loadTextureBackGroundSelected(abstractCheckButton->_backGroundSelectedBoxRenderer->getSpriteFrame()); loadTextureFrontCross(abstractCheckButton->_frontCrossRenderer->getSpriteFrame()); loadTextureBackGroundDisabled(abstractCheckButton->_backGroundBoxDisabledRenderer->getSpriteFrame()); loadTextureFrontCrossDisabled(abstractCheckButton->_frontCrossDisabledRenderer->getSpriteFrame()); setSelected(abstractCheckButton->_isSelected); _zoomScale = abstractCheckButton->_zoomScale; _backgroundTextureScaleX = abstractCheckButton->_backgroundTextureScaleX; _backgroundTextureScaleY = abstractCheckButton->_backgroundTextureScaleY; _isBackgroundSelectedTextureLoaded = abstractCheckButton->_isBackgroundSelectedTextureLoaded; _isBackgroundDisabledTextureLoaded = abstractCheckButton->_isBackgroundDisabledTextureLoaded; _isFrontCrossDisabledTextureLoaded = abstractCheckButton->_isFrontCrossDisabledTextureLoaded; } } ResourceData AbstractCheckButton::getBackNormalFile() { ResourceData rData; rData.type = (int)_backGroundTexType; rData.file = _backGroundFileName; return rData; } ResourceData AbstractCheckButton::getBackPressedFile() { ResourceData rData; rData.type = (int)_backGroundSelectedTexType; rData.file = _backGroundSelectedFileName; return rData; } ResourceData AbstractCheckButton::getBackDisabledFile() { ResourceData rData; rData.type = (int)_backGroundDisabledTexType; rData.file = _backGroundDisabledFileName; return rData; } ResourceData AbstractCheckButton::getCrossNormalFile() { ResourceData rData; rData.type = (int)_frontCrossTexType; rData.file = _frontCrossFileName; return rData; } ResourceData AbstractCheckButton::getCrossDisabledFile() { ResourceData rData; rData.type = (int)_frontCrossDisabledTexType; rData.file = _frontCrossDisabledFileName; return rData; } } NS_CC_END
[ "junjiedong91@gmail.com" ]
junjiedong91@gmail.com
b61b78bf1e1e1b851d3c8ec85ef27fe97e8a99f3
d60fa37053a864b3d2e46c2d1b3d72b899743da9
/RecoLocalTracker/SiPixelClusterizer/test/TestWithTracks.cc
15162151df3f55c6036f72a967fb29d31b0c3d33
[]
no_license
ikrav/cmssw
ba4528655cc67ac8c549d24ec4a004f6d86c8a92
d94717c9bfaecffb9ae0b401b6f8351e3dc3432d
refs/heads/CMSSW_7_2_X
2020-04-05T23:37:55.903032
2014-08-15T07:56:46
2014-08-15T07:56:46
22,983,843
2
1
null
2016-12-06T20:56:42
2014-08-15T08:43:31
null
UTF-8
C++
false
false
56,040
cc
// File: ReadPixClusters.cc // Description: TO test the pixel clusters with tracks (full) // Author: Danek Kotlinski // Creation Date: Initial version. 3/06 // //-------------------------------------------- #include <memory> #include <string> #include <iostream> #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" //#include "DataFormats/Common/interface/Handle.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Utilities/interface/InputTag.h" #include "DataFormats/Common/interface/EDProduct.h" //#include "DataFormats/SiPixelCluster/interface/SiPixelClusterCollection.h" #include "DataFormats/SiPixelCluster/interface/SiPixelCluster.h" #include "DataFormats/TrackerRecHit2D/interface/SiPixelRecHitCollection.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/SiPixelDetId/interface/PXBDetId.h" #include "DataFormats/SiPixelDetId/interface/PXFDetId.h" #include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h" #include "DataFormats/SiPixelDetId/interface/PixelBarrelName.h" #include "Geometry/TrackerGeometryBuilder/interface/PixelGeomDetUnit.h" #include "Geometry/TrackerGeometryBuilder/interface/PixelGeomDetType.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/CommonDetUnit/interface/GeomDetType.h" #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h" //#include "Geometry/CommonTopologies/interface/PixelTopology.h" // For L1 #include "L1Trigger/GlobalTriggerAnalyzer/interface/L1GtUtils.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerObjectMapRecord.h" // For HLT #include "DataFormats/HLTReco/interface/TriggerEvent.h" #include "DataFormats/HLTReco/interface/TriggerTypeDefs.h" #include "DataFormats/Common/interface/TriggerResults.h" #include "HLTrigger/HLTcore/interface/HLTConfigProvider.h" #include "FWCore/Common/interface/TriggerNames.h" // For tracks #include "DataFormats/TrackReco/interface/Track.h" #include "TrackingTools/PatternTools/interface/Trajectory.h" //#include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h" //#include "TrackingTools/PatternTools/interface/TrajectoryFitter.h" #include "TrackingTools/TrackFitters/interface/TrajectoryStateCombiner.h" //#include "TrackingTools/TrackAssociator/interface/TrackDetectorAssociator.h" //#include "TrackingTools/TrackAssociator/interface/TrackAssociatorParameters.h" //#include "Alignment/OfflineValidation/interface/TrackerValidationVariables.h" //#include "TrackingTools/TrackAssociator/interface/TrackDetectorAssociator.h" //#include "TrackingTools/PatternTools/interface/Trajectory.h" //#include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" //#include "TrackingTools/TransientTrack/interface/TransientTrack.h" //#include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h" #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h" #include <DataFormats/VertexReco/interface/VertexFwd.h> // For luminisoty #include "DataFormats/Luminosity/interface/LumiSummary.h" #include "DataFormats/Common/interface/ConditionsInEdm.h" // To use root histos #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" // For ROOT #include <TROOT.h> #include <TChain.h> #include <TFile.h> #include <TF1.h> #include <TH2F.h> #include <TH1F.h> #include <TProfile.h> #include <TVector3.h> #define HISTOS //#define L1 //#define HLT #define VDM_STUDIES const bool isData = false; // set false for MC using namespace std; class TestWithTracks : public edm::EDAnalyzer { public: explicit TestWithTracks(const edm::ParameterSet& conf); virtual ~TestWithTracks(); virtual void analyze(const edm::Event& e, const edm::EventSetup& c); virtual void beginRun(const edm::EventSetup& iSetup); virtual void beginJob(); virtual void endJob(); private: edm::ParameterSet conf_; edm::InputTag src_; //const static bool PRINT = false; bool PRINT; float countTracks, countGoodTracks, countTracksInPix, countPVs, countEvents, countLumi; TH1D *hcharge1,*hcharge2, *hcharge3, *hcharge4, *hcharge5; // ADD FPIX TH1D *hsize1,*hsize2,*hsize3, *hsizex1,*hsizex2,*hsizex3, *hsizey1,*hsizey2,*hsizey3; TH1D *hsize4,*hsize5, // ADD FPIX *hsizex4,*hsizex5, *hsizey4,*hsizey5; TH1D *hclusPerTrk1,*hclusPerTrk2,*hclusPerTrk3,*hclusPerTrk4,*hclusPerTrk5; TH1D *hclusPerLay1,*hclusPerLay2,*hclusPerLay3; TH1D *hclusPerDisk1,*hclusPerDisk2,*hclusPerDisk3,*hclusPerDisk4; TH1D *hclusPerTrk,*hclusPerTrkB,*hclusPerTrkF; TH2F *hDetMap1, *hDetMap2, *hDetMap3; // clusters TH2F *hcluDetMap1, *hcluDetMap2, *hcluDetMap3; // MODULE PROJECTION TH2F *hpvxy, *hclusMap1, *hclusMap2, *hclusMap3; // Z vs PHI TH1D *hpvz, *hpvr, *hNumPv, *hNumPvClean; TH1D *hPt, *hEta, *hDz, *hD0,*hzdiff; TH1D *hl1a, *hl1t, *hlt1; TH1D *hclusBpix, *hpixBpix; TH1D *htracks, *htracksGood, *htracksGoodInPix; TProfile *hclumult1, *hclumult2, *hclumult3; TProfile *hclumultx1, *hclumultx2, *hclumultx3; TProfile *hclumulty1, *hclumulty2, *hclumulty3; TProfile *hcluchar1, *hcluchar2, *hcluchar3; TProfile *hclumultld1, *hclumultld2, *hclumultld3; TProfile *hclumultxld1, *hclumultxld2, *hclumultxld3; TProfile *hclumultyld1, *hclumultyld2, *hclumultyld3; TProfile *hclucharld1, *hclucharld2, *hclucharld3; TProfile *htracksls, *hpvsls, *htrackslsn, *hpvslsn, *hintgl, *hinstl, *hbeam1, *hbeam2; TProfile *hmult1, *hmult2, *hmult3; TProfile *hclusPerTrkVsEta,*hclusPerTrkVsPt,*hclusPerTrkVsls,*hclusPerTrkVsEtaB,*hclusPerTrkVsEtaF; TH1D *hlumi, *hlumi0, *hbx, *hbx0; TH1D *recHitXError1,*recHitXError2,*recHitXError3; TH1D *recHitYError1,*recHitYError2,*recHitYError3; TH1D *recHitXAlignError1,*recHitXAlignError2,*recHitXAlignError3; TH1D *recHitYAlignError1,*recHitYAlignError2,*recHitYAlignError3; TH1D *recHitXError4,*recHitXError5,*recHitXError6,*recHitXError7; TH1D *recHitYError4,*recHitYError5,*recHitYError6,*recHitYError7; TH1D *recHitXAlignError4,*recHitXAlignError5,*recHitXAlignError6,*recHitXAlignError7; TH1D *recHitYAlignError4,*recHitYAlignError5,*recHitYAlignError6,*recHitYAlignError7; TProfile *hErrorXB,*hErrorYB,*hErrorXF,*hErrorYF; TProfile *hAErrorXB,*hAErrorYB,*hAErrorXF,*hAErrorYF; #ifdef VDM_STUDIES TProfile *hcharCluls, *hcharPixls, *hsizeCluls, *hsizeXCluls; TProfile *hcharCluls1, *hcharPixls1, *hsizeCluls1, *hsizeXCluls1; TProfile *hcharCluls2, *hcharPixls2, *hsizeCluls2, *hsizeXCluls2; TProfile *hcharCluls3, *hcharPixls3, *hsizeCluls3, *hsizeXCluls3; TProfile *hclusls; // *hpixls; TProfile *hclusls1, *hclusls2,*hclusls3; TProfile *hclubx, *hpvbx, *htrackbx; // *hcharClubx, *hcharPixbx,*hsizeClubx, *hsizeYClubx; #endif }; ///////////////////////////////////////////////////////////////// // Contructor, TestWithTracks::TestWithTracks(edm::ParameterSet const& conf) // : conf_(conf), src_(conf.getParameter<edm::InputTag>( "src" )) { } : conf_(conf) { PRINT = conf.getUntrackedParameter<bool>("Verbosity",false); src_ = conf.getParameter<edm::InputTag>( "src" ); //if(PRINT) cout<<" Construct "<<endl; } // Virtual destructor needed. TestWithTracks::~TestWithTracks() { } // ------------ method called at the begining ------------ void TestWithTracks::beginRun(const edm::EventSetup& iSetup) { cout << "BeginRun, Verbosity = " <<PRINT<<endl; } // ------------ method called at the begining ------------ void TestWithTracks::beginJob() { cout << "BeginJob, Verbosity " <<PRINT<<endl; countTracks=0.; countGoodTracks=0.; countTracksInPix=0.; countPVs=0.; countEvents=0.; countLumi=0.; #ifdef HISTOS edm::Service<TFileService> fs; int sizeH=20; float lowH = -0.5; float highH = 19.5; hclusPerTrk1 = fs->make<TH1D>( "hclusPerTrk1", "Clus per track l1", sizeH, lowH, highH); hclusPerTrk2 = fs->make<TH1D>( "hclusPerTrk2", "Clus per track l2", sizeH, lowH, highH); hclusPerTrk3 = fs->make<TH1D>( "hclusPerTrk3", "Clus per track l3", sizeH, lowH, highH); hclusPerTrk4 = fs->make<TH1D>( "hclusPerTrk4", "Clus per track d1", sizeH, lowH, highH); hclusPerTrk5 = fs->make<TH1D>( "hclusPerTrk5", "Clus per track d2", sizeH, lowH, highH); hclusPerTrk = fs->make<TH1D>( "hclusPerTrk", "Clus per track", sizeH, lowH, highH); hclusPerTrkB = fs->make<TH1D>( "hclusPerTrkB", "B Clus per track", sizeH, lowH, highH); hclusPerTrkF = fs->make<TH1D>( "hclusPerTrkF", "F Clus per track", sizeH, lowH, highH); sizeH=2000; highH = 1999.5; hclusPerLay1 = fs->make<TH1D>( "hclusPerLay1", "Clus per layer l1", sizeH, lowH, highH); hclusPerLay2 = fs->make<TH1D>( "hclusPerLay2", "Clus per layer l2", sizeH, lowH, highH); hclusPerLay3 = fs->make<TH1D>( "hclusPerLay3", "Clus per layer l3", sizeH, lowH, highH); hclusPerDisk1 = fs->make<TH1D>( "hclusPerDisk1", "Clus per disk 1", sizeH, lowH, highH); hclusPerDisk2 = fs->make<TH1D>( "hclusPerDisk2", "Clus per disk 2", sizeH, lowH, highH); hclusPerDisk3 = fs->make<TH1D>( "hclusPerDisk3", "Clus per disk 3", sizeH, lowH, highH); hclusPerDisk4 = fs->make<TH1D>( "hclusPerDisk4", "Clus per disk 4", sizeH, lowH, highH); hcharge1 = fs->make<TH1D>( "hcharge1", "Clu charge l1", 400, 0.,200.); //in ke hcharge2 = fs->make<TH1D>( "hcharge2", "Clu charge l2", 400, 0.,200.); hcharge3 = fs->make<TH1D>( "hcharge3", "Clu charge l3", 400, 0.,200.); hcharge4 = fs->make<TH1D>( "hcharge4", "Clu charge d1", 400, 0.,200.); hcharge5 = fs->make<TH1D>( "hcharge5", "Clu charge d2", 400, 0.,200.); hsize1 = fs->make<TH1D>( "hsize1", "layer 1 clu size",100,-0.5,99.5); hsize2 = fs->make<TH1D>( "hsize2", "layer 2 clu size",100,-0.5,99.5); hsize3 = fs->make<TH1D>( "hsize3", "layer 3 clu size",100,-0.5,99.5); hsizex1 = fs->make<TH1D>( "hsizex1", "lay1 clu size in x", 20,-0.5,19.5); hsizex2 = fs->make<TH1D>( "hsizex2", "lay2 clu size in x", 20,-0.5,19.5); hsizex3 = fs->make<TH1D>( "hsizex3", "lay3 clu size in x", 20,-0.5,19.5); hsizey1 = fs->make<TH1D>( "hsizey1", "lay1 clu size in y", 30,-0.5,29.5); hsizey2 = fs->make<TH1D>( "hsizey2", "lay2 clu size in y", 30,-0.5,29.5); hsizey3 = fs->make<TH1D>( "hsizey3", "lay3 clu size in y", 30,-0.5,29.5); hsize4 = fs->make<TH1D>( "hsize4", "disk 1 clu size",100,-0.5,99.5); hsize5 = fs->make<TH1D>( "hsize5", "disk 2 clu size",100,-0.5,99.5); hsizex4 = fs->make<TH1D>( "hsizex4", "d1 clu size in x", 20,-0.5,19.5); hsizex5 = fs->make<TH1D>( "hsizex5", "d2 clu size in x", 20,-0.5,19.5); hsizey4 = fs->make<TH1D>( "hsizey4", "d1 clu size in y", 30,-0.5,29.5); hsizey5 = fs->make<TH1D>( "hsizey5", "d2 clu size in y", 30,-0.5,29.5); hDetMap1 = fs->make<TH2F>( "hDetMap1", "layer 1 clus map", 9,0.,9.,23,0.,23.); hDetMap2 = fs->make<TH2F>( "hDetMap2", "layer 2 clus map", 9,0.,9.,33,0.,33.); hDetMap3 = fs->make<TH2F>( "hDetMap3", "layer 3 clus map", 9,0.,9.,45,0.,45.); //hpixDetMap1 = fs->make<TH2F>( "hpixDetMap1", "pix det layer 1", // 416,0.,416.,160,0.,160.); //hpixDetMap2 = fs->make<TH2F>( "hpixDetMap2", "pix det layer 2", // 416,0.,416.,160,0.,160.); //hpixDetMap3 = fs->make<TH2F>( "hpixDetMap3", "pix det layer 3", // 416,0.,416.,160,0.,160.); hcluDetMap1 = fs->make<TH2F>( "hcluDetMap1", "clu det layer 1", 416,0.,416.,160,0.,160.); hcluDetMap2 = fs->make<TH2F>( "hcluDetMap2", "clu det layer 2", 416,0.,416.,160,0.,160.); hcluDetMap3 = fs->make<TH2F>( "hcluDetMap3", "clu det layer 3", 416,0.,416.,160,0.,160.); htracksGoodInPix = fs->make<TH1D>( "htracksGoodInPix", "count good tracks in pix",2000,-0.5,1999.5); htracksGood = fs->make<TH1D>( "htracksGood", "count good tracks",2000,-0.5,1999.5); htracks = fs->make<TH1D>( "htracks", "count tracks",2000,-0.5,1999.5); hclusBpix = fs->make<TH1D>( "hclusBpix", "count clus in bpix",200,-0.5,1999.5); hpixBpix = fs->make<TH1D>( "hpixBpix", "count pixels",200,-0.5,1999.5); hpvxy = fs->make<TH2F>( "hpvxy", "pv xy",100,-1.,1.,100,-1.,1.); hpvz = fs->make<TH1D>( "hpvz", "pv z",1000,-50.,50.); hpvr = fs->make<TH1D>( "hpvr", "pv r",100,0.,1.); hNumPv = fs->make<TH1D>( "hNumPv", "num of pv",100,0.,100.); hNumPvClean = fs->make<TH1D>( "hNumPvClean", "num of pv clean",100,0.,100.); hPt = fs->make<TH1D>( "hPt", "pt",120,0.,120.); hEta = fs->make<TH1D>( "hEta", "eta",50,-2.5,2.5); hD0 = fs->make<TH1D>( "hD0", "d0",500,0.,5.); hDz = fs->make<TH1D>( "hDz", "pt",250,-25.,25.); hzdiff = fs->make<TH1D>( "hzdiff", "PVz-Trackz",200,-10.,10.); hl1a = fs->make<TH1D>("hl1a", "l1a", 128,-0.5,127.5); hl1t = fs->make<TH1D>("hl1t", "l1t", 128,-0.5,127.5); hlt1 = fs->make<TH1D>("hlt1","hlt1",256,-0.5,255.5); hclumult1 = fs->make<TProfile>("hclumult1","cluster size layer 1",60,-3.,3.,0.0,100.); hclumult2 = fs->make<TProfile>("hclumult2","cluster size layer 2",60,-3.,3.,0.0,100.); hclumult3 = fs->make<TProfile>("hclumult3","cluster size layer 3",60,-3.,3.,0.0,100.); hclumultx1 = fs->make<TProfile>("hclumultx1","cluster x-size layer 1",60,-3.,3.,0.0,100.); hclumultx2 = fs->make<TProfile>("hclumultx2","cluster x-size layer 2",60,-3.,3.,0.0,100.); hclumultx3 = fs->make<TProfile>("hclumultx3","cluster x-size layer 3",60,-3.,3.,0.0,100.); hclumulty1 = fs->make<TProfile>("hclumulty1","cluster y-size layer 1",60,-3.,3.,0.0,100.); hclumulty2 = fs->make<TProfile>("hclumulty2","cluster y-size layer 2",60,-3.,3.,0.0,100.); hclumulty3 = fs->make<TProfile>("hclumulty3","cluster y-size layer 3",60,-3.,3.,0.0,100.); hcluchar1 = fs->make<TProfile>("hcluchar1","cluster char layer 1",60,-3.,3.,0.0,1000.); hcluchar2 = fs->make<TProfile>("hcluchar2","cluster char layer 2",60,-3.,3.,0.0,1000.); hcluchar3 = fs->make<TProfile>("hcluchar3","cluster char layer 3",60,-3.,3.,0.0,1000.); // profiles versus ladder hclumultld1 = fs->make<TProfile>("hclumultld1","cluster size layer 1",23,-11.5,11.5,0.0,100.); hclumultld2 = fs->make<TProfile>("hclumultld2","cluster size layer 2",35,-17.5,17.5,0.0,100.); hclumultld3 = fs->make<TProfile>("hclumultld3","cluster size layer 3",47,-23.5,23.5,0.0,100.); hclumultxld1 = fs->make<TProfile>("hclumultxld1","cluster x-size layer 1",23,-11.5,11.5,0.0,100.); hclumultxld2 = fs->make<TProfile>("hclumultxld2","cluster x-size layer 2",35,-17.5,17.5,0.0,100.); hclumultxld3 = fs->make<TProfile>("hclumultxld3","cluster x-size layer 3",47,-23.5,23.5,0.0,100.); hclumultyld1 = fs->make<TProfile>("hclumultyld1","cluster y-size layer 1",23,-11.5,11.5,0.0,100.); hclumultyld2 = fs->make<TProfile>("hclumultyld2","cluster y-size layer 2",35,-17.5,17.5,0.0,100.); hclumultyld3 = fs->make<TProfile>("hclumultyld3","cluster y-size layer 3",47,-23.5,23.5,0.0,100.); hclucharld1 = fs->make<TProfile>("hclucharld1","cluster char layer 1",23,-11.5,11.5,0.0,1000.); hclucharld2 = fs->make<TProfile>("hclucharld2","cluster char layer 2",35,-17.5,17.5,0.0,1000.); hclucharld3 = fs->make<TProfile>("hclucharld3","cluster char layer 3",47,-23.5,23.5,0.0,1000.); hintgl = fs->make<TProfile>("hintgl", "inst lumi vs ls ",1000,0.,3000.,0.0,10000.); hinstl = fs->make<TProfile>("hinstl", "intg lumi vs ls ",1000,0.,3000.,0.0,100.); hbeam1 = fs->make<TProfile>("hbeam1", "beam1 vs ls ",1000,0.,3000.,0.0,1000.); hbeam2 = fs->make<TProfile>("hbeam2", "beam2 vs ls ",1000,0.,3000.,0.0,1000.); htracksls = fs->make<TProfile>("htracksls","tracks with pix hits vs ls",1000,0.,3000.,0.0,10000.); hpvsls = fs->make<TProfile>("hpvsls","pvs vs ls",1000,0.,3000.,0.0,1000.); htrackslsn = fs->make<TProfile>("htrackslsn","tracks with pix hits/lumi vs ls",1000,0.,3000.,0.0,10000.); hpvslsn = fs->make<TProfile>("hpvslsn","pvs/lumi vs ls",1000,0.,3000.,0.0,1000.); hmult1 = fs->make<TProfile>("hmult1","clu mult layer 1",10,0.,10.,0.0,1000.); hmult2 = fs->make<TProfile>("hmult2","clu mult layer 2",10,0.,10.,0.0,1000.); hmult3 = fs->make<TProfile>("hmult3","clu mult layer 3",10,0.,10.,0.0,1000.); hclusPerTrkVsEta = fs->make<TProfile>("hclusPerTrkVsEta","clus per trk vs.eta",60,-3.,3.,0.0,100.); hclusPerTrkVsPt = fs->make<TProfile>("hclusPerTrkVsPt","clus per trk vs.pt",120,0.,120.,0.0,100.); hclusPerTrkVsls = fs->make<TProfile>("hclusPerTrkVsls","clus per trk vs.ls",300,0.,3000.,0.0,100.); hclusPerTrkVsEtaF = fs->make<TProfile>("hclusPerTrkVsEtaF","F clus per trk vs.eta",60,-3.,3.,0.0,100.); hclusPerTrkVsEtaB = fs->make<TProfile>("hclusPerTrkVsEtaB","B clus per trk vs.eta",60,-3.,3.,0.0,100.); hlumi0 = fs->make<TH1D>("hlumi0", "lumi", 2000,0,2000.); hlumi = fs->make<TH1D>("hlumi", "lumi", 2000,0,2000.); hbx0 = fs->make<TH1D>("hbx0", "bx", 4000,0,4000.); hbx = fs->make<TH1D>("hbx", "bx", 4000,0,4000.); hclusMap1 = fs->make<TH2F>("hclusMap1","clus - lay1",260,-26.,26.,350,-3.5,3.5); hclusMap2 = fs->make<TH2F>("hclusMap2","clus - lay2",260,-26.,26.,350,-3.5,3.5); hclusMap3 = fs->make<TH2F>("hclusMap3","clus - lay3",260,-26.,26.,350,-3.5,3.5); // RecHit errors // alignment errors recHitXAlignError1 = fs->make<TH1D>("recHitXAlignError1","RecHit X Alignment errors bpix 1", 100, 0., 100.); recHitYAlignError1 = fs->make<TH1D>("recHitYAlignError1","RecHit Y Alignment errors bpix 1", 100, 0., 100.); recHitXAlignError2 = fs->make<TH1D>("recHitXAlignError2","RecHit X Alignment errors bpix 2", 100, 0., 100.); recHitYAlignError2 = fs->make<TH1D>("recHitYAlignError2","RecHit Y Alignment errors bpix 2", 100, 0., 100.); recHitXAlignError3 = fs->make<TH1D>("recHitXAlignError3","RecHit X Alignment errors bpix 3", 100, 0., 100.); recHitYAlignError3 = fs->make<TH1D>("recHitYAlignError3","RecHit Y Alignment errors bpix 3", 100, 0., 100.); recHitXAlignError4 = fs->make<TH1D>("recHitXAlignError4","RecHit X Alignment errors fpix -d2", 100, 0., 100.); recHitYAlignError4 = fs->make<TH1D>("recHitYAlignError4","RecHit Y Alignment errors fpix -d2", 100, 0., 100.); recHitXAlignError5 = fs->make<TH1D>("recHitXAlignError5","RecHit X Alignment errors fpix -d1", 100, 0., 100.); recHitYAlignError5 = fs->make<TH1D>("recHitYAlignError5","RecHit Y Alignment errors fpix -d1", 100, 0., 100.); recHitXAlignError6 = fs->make<TH1D>("recHitXAlignError6","RecHit X Alignment errors fpix +d1", 100, 0., 100.); recHitYAlignError6 = fs->make<TH1D>("recHitYAlignError6","RecHit Y Alignment errors fpix +d1", 100, 0., 100.); recHitXAlignError7 = fs->make<TH1D>("recHitXAlignError7","RecHit X Alignment errors fpix +d2", 100, 0., 100.); recHitYAlignError7 = fs->make<TH1D>("recHitYAlignError7","RecHit Y Alignment errors fpix +d2", 100, 0., 100.); recHitXError1 = fs->make<TH1D>("recHitXError1","RecHit X errors bpix 1", 100, 0., 100.); recHitYError1 = fs->make<TH1D>("recHitYError1","RecHit Y errors bpix 1", 100, 0., 100.); recHitXError2 = fs->make<TH1D>("recHitXError2","RecHit X errors bpix 2", 100, 0., 100.); recHitYError2 = fs->make<TH1D>("recHitYError2","RecHit Y errors bpix 2", 100, 0., 100.); recHitXError3 = fs->make<TH1D>("recHitXError3","RecHit X errors bpix 3", 100, 0., 100.); recHitYError3 = fs->make<TH1D>("recHitYError3","RecHit Y errors bpix 3", 100, 0., 100.); recHitXError4 = fs->make<TH1D>("recHitXError4","RecHit X errors fpix -d2", 100, 0., 100.); recHitYError4 = fs->make<TH1D>("recHitYError4","RecHit Y errors fpix -d2", 100, 0., 100.); recHitXError5 = fs->make<TH1D>("recHitXError5","RecHit X errors fpix -d1", 100, 0., 100.); recHitYError5 = fs->make<TH1D>("recHitYError5","RecHit Y errors fpix -d1", 100, 0., 100.); recHitXError6 = fs->make<TH1D>("recHitXError6","RecHit X errors fpix +d1", 100, 0., 100.); recHitYError6 = fs->make<TH1D>("recHitYError6","RecHit Y errors fpix +d1", 100, 0., 100.); recHitXError7 = fs->make<TH1D>("recHitXError7","RecHit X errors fpix +d2", 100, 0., 100.); recHitYError7 = fs->make<TH1D>("recHitYError7","RecHit Y errors fpix +d2", 100, 0., 100.); hErrorXB = fs->make<TProfile>("hErrorXB","bpix x errors per ladder",220,0.,220.,0.0,1000.); hErrorXF = fs->make<TProfile>("hErrorXF","fpix x errors per ladder",100,0.,100.,0.0,1000.); hErrorYB = fs->make<TProfile>("hErrorYB","bpix y errors per ladder",220,0.,220.,0.0,1000.); hErrorYF = fs->make<TProfile>("hErrorYF","fpix y errors per ladder",100,0.,100.,0.0,1000.); hAErrorXB = fs->make<TProfile>("hAErrorXB","bpix x errors per ladder",220,0.,220.,0.0,1000.); hAErrorXF = fs->make<TProfile>("hAErrorXF","fpix x errors per ladder",100,0.,100.,0.0,1000.); hAErrorYB = fs->make<TProfile>("hAErrorYB","bpix y errors per ladder",220,0.,220.,0.0,1000.); hAErrorYF = fs->make<TProfile>("hAErrorYF","fpix y errors per ladder",100,0.,100.,0.0,1000.); #ifdef VDM_STUDIES highH = 3000.; sizeH = 1000; hclusls = fs->make<TProfile>("hclusls","clus vs ls",sizeH,0.,highH,0.0,30000.); //hpixls = fs->make<TProfile>("hpixls", "pix vs ls ",sizeH,0.,highH,0.0,100000.); hcharCluls = fs->make<TProfile>("hcharCluls","clu char vs ls",sizeH,0.,highH,0.0,100.); //hcharPixls = fs->make<TProfile>("hcharPixls","pix char vs ls",sizeH,0.,highH,0.0,100.); hsizeCluls = fs->make<TProfile>("hsizeCluls","clu size vs ls",sizeH,0.,highH,0.0,1000.); hsizeXCluls= fs->make<TProfile>("hsizeXCluls","clu size-x vs ls",sizeH,0.,highH,0.0,100.); hcharCluls1 = fs->make<TProfile>("hcharCluls1","clu char vs ls",sizeH,0.,highH,0.0,100.); //hcharPixls1 = fs->make<TProfile>("hcharPixls1","pix char vs ls",sizeH,0.,highH,0.0,100.); hsizeCluls1 = fs->make<TProfile>("hsizeCluls1","clu size vs ls",sizeH,0.,highH,0.0,1000.); hsizeXCluls1= fs->make<TProfile>("hsizeXCluls1","clu size-x vs ls",sizeH,0.,highH,0.0,100.); hcharCluls2 = fs->make<TProfile>("hcharCluls2","clu char vs ls",sizeH,0.,highH,0.0,100.); //hcharPixls2 = fs->make<TProfile>("hcharPixls2","pix char vs ls",sizeH,0.,highH,0.0,100.); hsizeCluls2 = fs->make<TProfile>("hsizeCluls2","clu size vs ls",sizeH,0.,highH,0.0,1000.); hsizeXCluls2= fs->make<TProfile>("hsizeXCluls2","clu size-x vs ls",sizeH,0.,highH,0.0,100.); hcharCluls3 = fs->make<TProfile>("hcharCluls3","clu char vs ls",sizeH,0.,highH,0.0,100.); //hcharPixls3 = fs->make<TProfile>("hcharPixls3","pix char vs ls",sizeH,0.,highH,0.0,100.); hsizeCluls3 = fs->make<TProfile>("hsizeCluls3","clu size vs ls",sizeH,0.,highH,0.0,1000.); hsizeXCluls3= fs->make<TProfile>("hsizeXCluls3","clu size-x vs ls",sizeH,0.,highH,0.0,100.); hclusls1 = fs->make<TProfile>("hclusls1","clus vs ls",sizeH,0.,highH,0.0,30000.); //hpixls1 = fs->make<TProfile>("hpixls1", "pix vs ls ",sizeH,0.,highH,0.0,100000.); hclusls2 = fs->make<TProfile>("hclusls2","clus vs ls",sizeH,0.,highH,0.0,30000.); //hpixls2 = fs->make<TProfile>("hpixls2", "pix vs ls ",sizeH,0.,highH,0.0,100000.); hclusls3 = fs->make<TProfile>("hclusls3","clus vs ls",sizeH,0.,highH,0.0,30000.); //hpixls3 = fs->make<TProfile>("hpixls3", "pix vs ls ",sizeH,0.,highH,0.0,100000.); // Profiles versus bx //hpixbx = fs->make<TProfile>("hpixbx", "pixs vs bx ",4000,-0.5,3999.5,0.0,1000000.); hclubx = fs->make<TProfile>("hclubx", "clus vs bx ",4000,-0.5,3999.5,0.0,1000000.); hpvbx = fs->make<TProfile>("hpvbx", "pvs vs bx ", 4000,-0.5,3999.5,0.0,1000000.); htrackbx = fs->make<TProfile>("htrackbx", "tracks vs bx ", 4000,-0.5,3999.5,0.0,1000000.); #endif #endif } // ------------ method called to at the end of the job ------------ void TestWithTracks::endJob(){ cout << " End PixelTracksTest, events = " << countEvents << endl; if(countEvents>0.) { countTracks /= countEvents; countGoodTracks /= countEvents; countTracksInPix /= countEvents; countPVs /= countEvents; countLumi /= 1000.; cout<<" Average tracks/event "<< countTracks<<" good "<< countGoodTracks<<" in pix "<< countTracksInPix <<" PVs "<< countPVs<<" events " << countEvents<<" lumi pb-1 "<< countLumi<<"/10, bug!"<<endl; } } ////////////////////////////////////////////////////////////////// // Functions that gets called by framework every event void TestWithTracks::analyze(const edm::Event& e, const edm::EventSetup& es) { using namespace edm; using namespace reco; static int lumiBlockOld = -9999; const float CLU_SIZE_PT_CUT = 1.; int trackNumber = 0; int countNiceTracks=0; int countPixTracks=0; int numberOfClusters = 0; int numberOfPixels = 0; int numOfClusPerTrk1=0; int numOfClustersPerLay1=0; int numOfPixelsPerLay1=0; int numOfClusPerTrk2=0; int numOfClustersPerLay2=0; int numOfPixelsPerLay2=0; int numOfClusPerTrk3=0; int numOfClustersPerLay3=0; int numOfPixelsPerLay3=0; int numOfClusPerTrk4=0; int numOfClustersPerLay4=0; int numOfPixelsPerLay4=0; int numOfClusPerTrk5=0; int numOfClustersPerLay5=0; int numOfPixelsPerLay5=0; int numOfClustersPerDisk1=0; int numOfClustersPerDisk2=0; int numOfClustersPerDisk3=0; int numOfClustersPerDisk4=0; int run = e.id().run(); int event = e.id().event(); int lumiBlock = e.luminosityBlock(); int bx = e.bunchCrossing(); //int orbit = e.orbitNumber(); // unused if(PRINT) cout<<"Run "<<run<<" Event "<<event<<" LS "<<lumiBlock<<endl; hbx0->Fill(float(bx)); hlumi0->Fill(float(lumiBlock)); edm::LuminosityBlock const& iLumi = e.getLuminosityBlock(); edm::Handle<LumiSummary> lumi; iLumi.getByLabel("lumiProducer", lumi); edm::Handle<edm::ConditionsInLumiBlock> cond; float intlumi = 0, instlumi=0; int beamint1=0, beamint2=0; iLumi.getByLabel("conditionsInEdm", cond); // This will only work when running on RECO until (if) they fix it in the FW // When running on RAW and reconstructing, the LumiSummary will not appear // in the event before reaching endLuminosityBlock(). Therefore, it is not // possible to get this info in the event if (lumi.isValid()) { intlumi =(lumi->intgRecLumi())/1000.; // 10^30 -> 10^33/cm2/sec -> 1/nb/sec instlumi=(lumi->avgInsDelLumi())/1000.; beamint1=(cond->totalIntensityBeam1)/1000; beamint2=(cond->totalIntensityBeam2)/1000; } else { //std::cout << "** ERROR: Event does not get lumi info\n"; } hinstl->Fill(float(lumiBlock),float(instlumi)); hintgl->Fill(float(lumiBlock),float(intlumi)); hbeam1->Fill(float(lumiBlock),float(beamint1)); hbeam2->Fill(float(lumiBlock),float(beamint2)); #ifdef L1 // Get L1 Handle<L1GlobalTriggerReadoutRecord> L1GTRR; e.getByLabel("gtDigis",L1GTRR); if (L1GTRR.isValid()) { //bool l1a = L1GTRR->decision(); // global decission? //cout<<" L1 status :"<<l1a<<" "<<hex; for (unsigned int i = 0; i < L1GTRR->decisionWord().size(); ++i) { int l1flag = L1GTRR->decisionWord()[i]; int t1flag = L1GTRR->technicalTriggerWord()[i]; if( l1flag>0 ) hl1a->Fill(float(i)); if( t1flag>0 && i<64) hl1t->Fill(float(i)); } // for loop } // if l1a #endif #ifdef HLT bool hlt[256]; for(int i=0;i<256;++i) hlt[i]=false; edm::TriggerNames TrigNames; edm::Handle<edm::TriggerResults> HLTResults; // Extract the HLT results e.getByLabel(edm::InputTag("TriggerResults","","HLT"),HLTResults); if ((HLTResults.isValid() == true) && (HLTResults->size() > 0)) { //TrigNames.init(*HLTResults); const edm::TriggerNames & TrigNames = e.triggerNames(*HLTResults); //cout<<TrigNames.triggerNames().size()<<endl; for (unsigned int i = 0; i < TrigNames.triggerNames().size(); i++) { // loop over trigger //if(countAllEvents==1) cout<<i<<" "<<TrigNames.triggerName(i)<<endl; if ( (HLTResults->wasrun(TrigNames.triggerIndex(TrigNames.triggerName(i))) == true) && (HLTResults->accept(TrigNames.triggerIndex(TrigNames.triggerName(i))) == true) && (HLTResults->error( TrigNames.triggerIndex(TrigNames.triggerName(i))) == false) ) { hlt[i]=true; hlt1->Fill(float(i)); } // if hlt } // loop } // if valid #endif // -- Does this belong into beginJob()? //ESHandle<TrackerGeometry> TG; //iSetup.get<TrackerDigiGeometryRecord>().get(TG); //const TrackerGeometry* theTrackerGeometry = TG.product(); //const TrackerGeometry& theTracker(*theTrackerGeometry); // Get event setup edm::ESHandle<TrackerGeometry> geom; es.get<TrackerDigiGeometryRecord>().get( geom ); const TrackerGeometry& theTracker(*geom); // -- Primary vertices // ---------------------------------------------------------------------- edm::Handle<reco::VertexCollection> vertices; e.getByLabel("offlinePrimaryVertices", vertices); if(PRINT) cout<<" PV list "<<vertices->size()<<endl; int pvNotFake = 0, pvsTrue = 0; vector<float> pvzVector; for (reco::VertexCollection::const_iterator iv = vertices->begin(); iv != vertices->end(); ++iv) { if( (iv->isFake()) == 1 ) continue; pvNotFake++; float pvx = iv->x(); float pvy = iv->y(); float pvz = iv->z(); int numTracksPerPV = iv->tracksSize(); //int numTracksPerPV = iv->nTracks(); //float xe = iv->xError(); //float ye = iv->yError(); //float ze = iv->zError(); //int chi2 = iv->chi2(); //int dof = iv->ndof(); if(PRINT) cout<<" PV "<<pvNotFake<<" pos = "<<pvx<<"/"<<pvy<<"/"<<pvz <<", Num of tracks "<<numTracksPerPV<<endl; hpvz->Fill(pvz); if(pvz>-22. && pvz<22.) { float pvr = sqrt(pvx*pvx + pvy*pvy); hpvxy->Fill(pvx,pvy); hpvr->Fill(pvr); if(pvr<0.3) { pvsTrue++; pvzVector.push_back(pvz); //if(PRINT) cout<<"PV "<<pvsTrue<<" "<<pvz<<endl; } //pvr } // pvz //if(pvsTrue<1) continue; // skip events with no PV } // loop pvs hNumPv->Fill(float(pvNotFake)); hNumPvClean->Fill(float(pvsTrue)); if(PRINT) cout<<" Not fake PVs = "<<pvNotFake<<" good position "<<pvsTrue<<endl; // -- Tracks // ---------------------------------------------------------------------- Handle<reco::TrackCollection> recTracks; // e.getByLabel("generalTracks", recTracks); // e.getByLabel("ctfWithMaterialTracksP5", recTracks); // e.getByLabel("splittedTracksP5", recTracks); //e.getByLabel("cosmictrackfinderP5", recTracks); e.getByLabel(src_ , recTracks); if(PRINT) cout<<" Tracks "<<recTracks->size()<<endl; for(reco::TrackCollection::const_iterator t=recTracks->begin(); t!=recTracks->end(); ++t){ trackNumber++; numOfClusPerTrk1=0; // this is confusing, it is used as clus per track numOfClusPerTrk2=0; numOfClusPerTrk3=0; numOfClusPerTrk4=0; numOfClusPerTrk5=0; int pixelHits=0; int size = t->recHitsSize(); float pt = t->pt(); float eta = t->eta(); float phi = t->phi(); //float trackCharge = t->charge(); // unused float d0 = t->d0(); float dz = t->dz(); //float tkvx = t->vx(); // unused //float tkvy = t->vy(); //float tkvz = t->vz(); if(PRINT) cout<<"Track "<<trackNumber<<" Pt "<<pt<<" Eta "<<eta<<" d0/dz "<<d0<<" "<<dz <<" Hits "<<size<<endl; hEta->Fill(eta); hDz->Fill(dz); if(abs(eta)>2.8 || abs(dz)>25.) continue; // skip hD0->Fill(d0); if(d0>1.0) continue; // skip bool goodTrack = false; for(vector<float>::iterator m=pvzVector.begin(); m!=pvzVector.end();++m) { float z = *m; float tmp = abs(z-dz); hzdiff->Fill(tmp); if( tmp < 1.) goodTrack=true; } if(isData && !goodTrack) continue; countNiceTracks++; hPt->Fill(pt); // Loop over rechits for ( trackingRecHit_iterator recHit = t->recHitsBegin(); recHit != t->recHitsEnd(); ++recHit ) { if ( !((*recHit)->isValid()) ) continue; if( (*recHit)->geographicalId().det() != DetId::Tracker ) continue; const DetId & hit_detId = (*recHit)->geographicalId(); uint IntSubDetID = (hit_detId.subdetId()); // Select pixel rechits if(IntSubDetID == 0 ) continue; // Select ?? int layer=0, ladder=0, zindex=0, ladderOn=0, module=0, shell=0; unsigned int disk=0; //1,2,3 unsigned int blade=0; //1-24 unsigned int zindexF=0; // unsigned int side=0; //size=1 for -z, 2 for +z unsigned int panel=0; //panel=1 if(IntSubDetID == PixelSubdetector::PixelBarrel) { // bpix // Pixel detector PXBDetId pdetId = PXBDetId(hit_detId); //unsigned int detTypeP=pdetId.det(); //unsigned int subidP=pdetId.subdetId(); // Barell layer = 1,2,3 layer=pdetId.layer(); // Barrel ladder id 1-20,32,44. ladder=pdetId.ladder(); // Barrel Z-index=1,8 zindex=pdetId.module(); if(zindex<5) side=1; else side=2; // Convert to online PixelBarrelName pbn(pdetId); // Shell { mO = 1, mI = 2 , pO =3 , pI =4 }; PixelBarrelName::Shell sh = pbn.shell(); //enum //sector = pbn.sectorName(); ladderOn = pbn.ladderName(); //layerOn = pbn.layerName(); module = pbn.moduleName(); // 1 to 4 //half = pbn.isHalfModule(); shell = int(sh); // change the module sign for z<0 if(shell==1 || shell==2) module = -module; // make -1 to -4 for -z // change ladeer sign for Outer )x<0) if(shell==1 || shell==3) ladderOn = -ladderOn; if(PRINT) cout<<"barrel layer/ladder/module: "<<layer<<"/"<<ladder<<"/"<<zindex<<endl; } else if(IntSubDetID == PixelSubdetector::PixelEndcap) { // fpix PXFDetId pdetId = PXFDetId(hit_detId); disk=pdetId.disk(); //1,2,3 blade=pdetId.blade(); //1-24 zindexF=pdetId.module(); // side=pdetId.side(); //size=1 for -z, 2 for +z panel=pdetId.panel(); //panel=1 if(PRINT) cout<<" forward det, disk "<<disk<<", blade " <<blade<<", module "<<zindexF<<", side "<<side<<", panel " <<panel<<endl; } else { // nothings continue; // skip } // Get the geom-detector const PixelGeomDetUnit * theGeomDet = dynamic_cast<const PixelGeomDetUnit*> (theTracker.idToDet(hit_detId) ); //double detZ = theGeomDet->surface().position().z(); // unused //double detR = theGeomDet->surface().position().perp(); // unused const PixelTopology * topol = &(theGeomDet->specificTopology()); // pixel topology //std::vector<SiStripRecHit2D*> output = getRecHitComponents((*recHit).get()); //std::vector<SiPixelRecHit*> TrkComparison::getRecHitComponents(const TrackingRecHit* rechit){ const SiPixelRecHit* hit = dynamic_cast<const SiPixelRecHit*>((*recHit).get()); //edm::Ref<edmNew::DetSetVector<SiStripCluster> ,SiStripCluster> cluster = hit->cluster(); // get the edm::Ref to the cluster if(hit) { if(pt>1.) { // eliminate low pt tracks // RecHit (recthits are transient, so not available without track refit) double xloc = hit->localPosition().x();// 1st meas coord double yloc = hit->localPosition().y();// 2nd meas coord or zero //double zloc = hit->localPosition().z();// up, always zero LocalError lerr = hit->localPositionError(); float lerr_x = sqrt(lerr.xx())*1E4; float lerr_y = sqrt(lerr.yy())*1E4; if( layer == 1) {recHitXError1->Fill(lerr_x); recHitYError1->Fill(lerr_y); hErrorXB->Fill(float(ladder+(110*(side-1))),lerr_x); hErrorYB->Fill(float(ladder+(110*(side-1))),lerr_y); } else if( layer == 2) {recHitXError2->Fill(lerr_x); recHitYError2->Fill(lerr_y); hErrorXB->Fill(float(ladder+25+(110*(side-1))),lerr_x); hErrorYB->Fill(float(ladder+25+(110*(side-1))),lerr_y); } else if( layer == 3) {recHitXError3->Fill(lerr_x); recHitYError3->Fill(lerr_y); hErrorXB->Fill(float(ladder+60+(110*(side-1))),lerr_x); hErrorYB->Fill(float(ladder+60+(110*(side-1))),lerr_y); } else if( (disk == 2) && (side==1) ) {recHitXError4->Fill(lerr_x); recHitYError4->Fill(lerr_y); hErrorXF->Fill(float(blade),lerr_x); hErrorYF->Fill(float(blade),lerr_y); } else if( (disk == 1) && (side==1) ) {recHitXError5->Fill(lerr_x); recHitYError5->Fill(lerr_y); hErrorXF->Fill(float(blade+25),lerr_x); hErrorYF->Fill(float(blade+25),lerr_y); } else if( (disk == 1) && (side==2) ) {recHitXError6->Fill(lerr_x); recHitYError6->Fill(lerr_y); hErrorXF->Fill(float(blade+50),lerr_x); hErrorYF->Fill(float(blade+50),lerr_y); } else if( (disk == 2) && (side==2) ) {recHitXError7->Fill(lerr_x); recHitYError7->Fill(lerr_y); hErrorXF->Fill(float(blade+75),lerr_x); hErrorYF->Fill(float(blade+75),lerr_y); } LocalError lape = theGeomDet->localAlignmentError(); if (lape.valid()) { float tmp11= 0.; if(lape.xx()>0.) tmp11= sqrt(lape.xx())*1E4; //float tmp12= sqrt(lape.xy())*1E4; float tmp13= 0.; if(lape.yy()>0.) tmp13= sqrt(lape.yy())*1E4; //bool tmp14=tmp2<tmp1; if( layer == 1) {recHitXAlignError1->Fill(tmp11); recHitYAlignError1->Fill(tmp13); hAErrorXB->Fill(float(ladder+(110*(side-1))),tmp11); hAErrorYB->Fill(float(ladder+(110*(side-1))),tmp13); } else if( layer == 2) {recHitXAlignError2->Fill(tmp11); recHitYAlignError2->Fill(tmp13); hAErrorXB->Fill(float(ladder+25+(110*(side-1))),tmp11); hAErrorYB->Fill(float(ladder+25+(110*(side-1))),tmp13); } else if( layer == 3) {recHitXAlignError3->Fill(tmp11); recHitYAlignError3->Fill(tmp13); hAErrorXB->Fill(float(ladder+60+(110*(side-1))),tmp11); hAErrorYB->Fill(float(ladder+60+(110*(side-1))),tmp13); } else if( (disk == 2) && (side==1) ) {recHitXAlignError4->Fill(tmp11); recHitYAlignError4->Fill(tmp13); hAErrorXF->Fill(float(blade),tmp11); hAErrorYF->Fill(float(blade),tmp13); } else if( (disk == 1) && (side==1) ) {recHitXAlignError5->Fill(tmp11); recHitYAlignError5->Fill(tmp13); hAErrorXF->Fill(float(blade+25),tmp11); hAErrorYF->Fill(float(blade+25),tmp13); } else if( (disk == 1) && (side==2) ) {recHitXAlignError6->Fill(tmp11); recHitYAlignError6->Fill(tmp13); hAErrorXF->Fill(float(blade+50),tmp11); hAErrorYF->Fill(float(blade+50),tmp13); } else if( (disk == 2) && (side==2) ) {recHitXAlignError7->Fill(tmp11); recHitYAlignError7->Fill(tmp13); hAErrorXF->Fill(float(blade+75),tmp11); hAErrorYF->Fill(float(blade+75),tmp13); } //cout<<tTopo->pxbLayer(detId)<<" "<<tTopo->pxbModule(detId)<<" "<<rows<<" "<<tmp14<<" " if(PRINT) cout<<" align error "<<layer<<tmp11<<" "<<tmp13<<endl; } else { cout<<" lape = 0"<<endl; } // if lape if(PRINT) cout<<" rechit loc "<<xloc<<" "<<yloc<<" "<<lerr_x<<" " <<lerr_y<<endl; } // limit pt edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = hit->cluster(); // check if the ref is not null if (!clust.isNonnull()) continue; numberOfClusters++; pixelHits++; float charge = (clust->charge())/1000.0; // convert electrons to kilo-electrons int size = clust->size(); int sizeX = clust->sizeX(); int sizeY = clust->sizeY(); float row = clust->x(); float col = clust->y(); numberOfPixels += size; //cout<<" clus loc "<<row<<" "<<col<<endl; if(PRINT) cout<<" cluster "<<numberOfClusters<<" charge = "<<charge<<" size = "<<size<<endl; LocalPoint lp = topol->localPosition( MeasurementPoint( clust->x(), clust->y() ) ); //float x = lp.x(); //float y = lp.y(); //cout<<" clu loc "<<x<<" "<<y<<endl; GlobalPoint clustgp = theGeomDet->surface().toGlobal( lp ); double gX = clustgp.x(); double gY = clustgp.y(); double gZ = clustgp.z(); //cout<<" CLU GLOBAL "<<gX<<" "<<gY<<" "<<gZ<<endl; TVector3 v(gX,gY,gZ); //float phi = v.Phi(); // unused //int maxPixelCol = clust->maxPixelCol(); //int maxPixelRow = clust->maxPixelRow(); //int minPixelCol = clust->minPixelCol(); //int minPixelRow = clust->minPixelRow(); //int geoId = PixGeom->geographicalId().rawId(); // Replace with the topology methods // edge method moved to topologi class //int edgeHitX = (int) ( topol->isItEdgePixelInX( minPixelRow ) || topol->isItEdgePixelInX( maxPixelRow ) ); //int edgeHitY = (int) ( topol->isItEdgePixelInY( minPixelCol ) || topol->isItEdgePixelInY( maxPixelCol ) ); // calculate alpha and beta from cluster position //LocalTrajectoryParameters ltp = tsos.localParameters(); //LocalVector localDir = ltp.momentum()/ltp.momentum().mag(); //float locx = localDir.x(); //float locy = localDir.y(); //float locz = localDir.z(); //float loctheta = localDir.theta(); // currently unused //float alpha = atan2( locz, locx ); //float beta = atan2( locz, locy ); if(layer==1) { hDetMap1->Fill(float(zindex),float(ladder)); hcluDetMap1->Fill(col,row); hcharge1->Fill(charge); //hcols1->Fill(col); //hrows1->Fill(row); hclusMap1->Fill(gZ,phi); hmult1->Fill(zindex,float(size)); if(pt>CLU_SIZE_PT_CUT) { hsize1->Fill(float(size)); hsizex1->Fill(float(sizeX)); hsizey1->Fill(float(sizeY)); hclumult1->Fill(eta,float(size)); hclumultx1->Fill(eta,float(sizeX)); hclumulty1->Fill(eta,float(sizeY)); hcluchar1->Fill(eta,float(charge)); //cout<<ladder<<" "<<ladderOn<<endl; hclumultld1->Fill(float(ladderOn),size); hclumultxld1->Fill(float(ladderOn),sizeX); hclumultyld1->Fill(float(ladderOn),sizeY); hclucharld1->Fill(float(ladderOn),charge); } #ifdef VDM_STUDIES hcharCluls->Fill(lumiBlock,charge); hsizeCluls->Fill(lumiBlock,size); hsizeXCluls->Fill(lumiBlock,sizeX); hcharCluls1->Fill(lumiBlock,charge); hsizeCluls1->Fill(lumiBlock,size); hsizeXCluls1->Fill(lumiBlock,sizeX); #endif numOfClusPerTrk1++; numOfClustersPerLay1++; numOfPixelsPerLay1 += size; } else if(layer==2) { hDetMap2->Fill(float(zindex),float(ladder)); hcluDetMap2->Fill(col,row); hcharge2->Fill(charge); //hcols2->Fill(col); //hrows2->Fill(row); hclusMap2->Fill(gZ,phi); hmult2->Fill(zindex,float(size)); if(pt>CLU_SIZE_PT_CUT) { hsize2->Fill(float(size)); hsizex2->Fill(float(sizeX)); hsizey2->Fill(float(sizeY)); hclumult2->Fill(eta,float(size)); hclumultx2->Fill(eta,float(sizeX)); hclumulty2->Fill(eta,float(sizeY)); hcluchar2->Fill(eta,float(charge)); hclumultld2->Fill(float(ladderOn),size); hclumultxld2->Fill(float(ladderOn),sizeX); hclumultyld2->Fill(float(ladderOn),sizeY); hclucharld2->Fill(float(ladderOn),charge); } #ifdef VDM_STUDIES hcharCluls->Fill(lumiBlock,charge); hsizeCluls->Fill(lumiBlock,size); hsizeXCluls->Fill(lumiBlock,sizeX); hcharCluls2->Fill(lumiBlock,charge); hsizeCluls2->Fill(lumiBlock,size); hsizeXCluls2->Fill(lumiBlock,sizeX); #endif numOfClusPerTrk2++; numOfClustersPerLay2++; numOfPixelsPerLay2 += size; } else if(layer==3) { hDetMap3->Fill(float(zindex),float(ladder)); hcluDetMap3->Fill(col,row); hcharge3->Fill(charge); //hcols3->Fill(col); //hrows3->Fill(row); hclusMap3->Fill(gZ,phi); hmult3->Fill(zindex,float(size)); if(pt>CLU_SIZE_PT_CUT) { hsize3->Fill(float(size)); hsizex3->Fill(float(sizeX)); hsizey3->Fill(float(sizeY)); hclumult3->Fill(eta,float(size)); hclumultx3->Fill(eta,float(sizeX)); hclumulty3->Fill(eta,float(sizeY)); hcluchar3->Fill(eta,float(charge)); hclumultld3->Fill(float(ladderOn),size); hclumultxld3->Fill(float(ladderOn),sizeX); hclumultyld3->Fill(float(ladderOn),sizeY); hclucharld3->Fill(float(ladderOn),charge); } #ifdef VDM_STUDIES hcharCluls->Fill(lumiBlock,charge); hsizeCluls->Fill(lumiBlock,size); hsizeXCluls->Fill(lumiBlock,sizeX); hcharCluls3->Fill(lumiBlock,charge); hsizeCluls3->Fill(lumiBlock,size); hsizeXCluls3->Fill(lumiBlock,sizeX); #endif numOfClusPerTrk3++; numOfClustersPerLay3++; numOfPixelsPerLay3 += size; } else if (disk==1) { numOfClusPerTrk4++; numOfClustersPerLay4++; numOfPixelsPerLay4 += size; hcharge4->Fill(charge); if(pt>CLU_SIZE_PT_CUT) { hsize4->Fill(float(size)); hsizex4->Fill(float(sizeX)); hsizey4->Fill(float(sizeY)); } if(side==1) numOfClustersPerDisk2++; // -z else if(side==2) numOfClustersPerDisk3++; // +z } else if (disk==2) { numOfClusPerTrk5++; numOfClustersPerLay5++; numOfPixelsPerLay5 += size; hcharge5->Fill(charge); if(pt>CLU_SIZE_PT_CUT) { hsize5->Fill(float(size)); hsizex5->Fill(float(sizeX)); hsizey5->Fill(float(sizeY)); } if(side==1) numOfClustersPerDisk1++; // -z else if(side==2) numOfClustersPerDisk4++; // +z } else { cout<<" which layer is this? "<<layer<<" "<< disk<<endl; } // if layer } // if valid } // clusters if(pixelHits>0) countPixTracks++; if(PRINT) cout<<" Clusters for track "<<trackNumber<<" num of clusters "<<numberOfClusters <<" num of pixels "<<pixelHits<<endl; #ifdef HISTOS // per track histos if(numberOfClusters>0) { hclusPerTrk1->Fill(float(numOfClusPerTrk1)); if(PRINT) cout<<"Lay1: number of clusters per track = "<<numOfClusPerTrk1<<endl; hclusPerTrk2->Fill(float(numOfClusPerTrk2)); if(PRINT) cout<<"Lay2: number of clusters per track = "<<numOfClusPerTrk1<<endl; hclusPerTrk3->Fill(float(numOfClusPerTrk3)); if(PRINT) cout<<"Lay3: number of clusters per track = "<<numOfClusPerTrk1<<endl; hclusPerTrk4->Fill(float(numOfClusPerTrk4)); // fpix disk1 hclusPerTrk5->Fill(float(numOfClusPerTrk5)); // fpix disk2 float clusPerTrkB = numOfClusPerTrk1 + numOfClusPerTrk2 + numOfClusPerTrk3; float clusPerTrkF = numOfClusPerTrk4 + numOfClusPerTrk5; float clusPerTrk = clusPerTrkB + clusPerTrkF; hclusPerTrkB->Fill(clusPerTrkB); hclusPerTrkF->Fill(clusPerTrkF); hclusPerTrk->Fill(clusPerTrk); hclusPerTrkVsEta->Fill(eta,clusPerTrk); hclusPerTrkVsEtaB->Fill(eta,clusPerTrkB); hclusPerTrkVsEtaF->Fill(eta,clusPerTrkF); hclusPerTrkVsPt->Fill(pt,clusPerTrk); hclusPerTrkVsls->Fill(lumiBlock,clusPerTrk); } #endif // HISTOS } // tracks #ifdef HISTOS // total layer histos if(numberOfClusters>0) { hclusPerLay1->Fill(float(numOfClustersPerLay1)); hclusPerLay2->Fill(float(numOfClustersPerLay2)); hclusPerLay3->Fill(float(numOfClustersPerLay3)); hclusPerDisk1->Fill(float(numOfClustersPerDisk1)); hclusPerDisk2->Fill(float(numOfClustersPerDisk2)); hclusPerDisk3->Fill(float(numOfClustersPerDisk3)); hclusPerDisk4->Fill(float(numOfClustersPerDisk4)); //hdetsPerLay1->Fill(float(numberOfDetUnits1)); //hdetsPerLay2->Fill(float(numberOfDetUnits2)); //hdetsPerLay3->Fill(float(numberOfDetUnits3)); //int tmp = numberOfDetUnits1+numberOfDetUnits2+numberOfDetUnits3; //hpixPerLay1->Fill(float(numOfPixelsPerLay1)); //hpixPerLay2->Fill(float(numOfPixelsPerLay2)); //hpixPerLay3->Fill(float(numOfPixelsPerLay3)); //htest7->Fill(float(tmp)); hclusBpix->Fill(float(numberOfClusters)); hpixBpix->Fill(float(numberOfPixels)); } htracksGood->Fill(float(countNiceTracks)); htracksGoodInPix->Fill(float(countPixTracks)); htracks->Fill(float(trackNumber)); hbx->Fill(float(bx)); hlumi->Fill(float(lumiBlock)); htracksls->Fill(float(lumiBlock),float(countPixTracks)); hpvsls->Fill(float(lumiBlock),float(pvsTrue)); if(instlumi>0.) { float tmp = float(countPixTracks)/instlumi; htrackslsn->Fill(float(lumiBlock),tmp); tmp = float(pvsTrue)/instlumi; hpvslsn->Fill(float(lumiBlock),tmp); } #ifdef VDM_STUDIES hclusls->Fill(float(lumiBlock),float(numberOfClusters)); // clusters fpix+bpix //hpixls->Fill(float(lumiBlock),float(numberOfPixels)); // pixels fpix+bpix hclubx->Fill(float(bx),float(numberOfClusters)); // clusters fpix+bpix //hpixbx->Fill(float(bx),float(numberOfPixels)); // pixels fpix+bpix hpvbx->Fill(float(bx),float(pvsTrue)); // pvs htrackbx->Fill(float(bx),float(countPixTracks)); // tracks hclusls1->Fill(float(lumiBlock),float(numOfClustersPerLay1)); // clusters bpix1 //hpixls1->Fill( float(lumiBlock),float(numOfPixPerLay1)); // pixels bpix1 hclusls2->Fill(float(lumiBlock),float(numOfClustersPerLay2)); // clusters bpix2 //hpixls2->Fill( float(lumiBlock),float(numOfPixPerLay2)); // pixels bpix2 hclusls3->Fill(float(lumiBlock),float(numOfClustersPerLay3)); // clusters bpix3 //hpixls3->Fill( float(lumiBlock),float(numOfPixPerLay3)); // pixels bpix3 #endif #endif // HISTOS // countTracks += float(trackNumber); countGoodTracks += float(countNiceTracks); countTracksInPix += float(countPixTracks); countPVs += float(pvsTrue); countEvents++; if(lumiBlock != lumiBlockOld) { countLumi += intlumi; lumiBlockOld = lumiBlock; } if(PRINT) cout<<" event with tracks = "<<trackNumber<<" "<<countNiceTracks<<endl; return; #ifdef USE_TRAJ // Not used //---------------------------------------------------------------------------- // Use Trajectories edm::Handle<TrajTrackAssociationCollection> trajTrackCollectionHandle; e.getByLabel(conf_.getParameter<std::string>("trajectoryInput"),trajTrackCollectionHandle); TrajectoryStateCombiner tsoscomb; int NbrTracks = trajTrackCollectionHandle->size(); std::cout << " track measurements " << trajTrackCollectionHandle->size() << std::endl; int trackNumber = 0; int numberOfClusters = 0; for(TrajTrackAssociationCollection::const_iterator it = trajTrackCollectionHandle->begin(), itEnd = trajTrackCollectionHandle->end(); it!=itEnd;++it){ int pixelHits = 0; int stripHits = 0; const Track& track = *it->val; const Trajectory& traj = *it->key; std::vector<TrajectoryMeasurement> checkColl = traj.measurements(); for(std::vector<TrajectoryMeasurement>::const_iterator checkTraj = checkColl.begin(); checkTraj != checkColl.end(); ++checkTraj) { if(! checkTraj->updatedState().isValid()) continue; TransientTrackingRecHit::ConstRecHitPointer testhit = checkTraj->recHit(); if(! testhit->isValid() || testhit->geographicalId().det() != DetId::Tracker ) continue; uint testSubDetID = (testhit->geographicalId().subdetId()); if(testSubDetID == PixelSubdetector::PixelBarrel || testSubDetID == PixelSubdetector::PixelEndcap) pixelHits++; else if (testSubDetID == StripSubdetector::TIB || testSubDetID == StripSubdetector::TOB || testSubDetID == StripSubdetector::TID || testSubDetID == StripSubdetector::TEC) stripHits++; } if (pixelHits == 0) continue; trackNumber++; std::cout << " track " << trackNumber <<" has pixelhits "<<pixelHits << std::endl; pixelHits = 0; //std::vector<TrajectoryMeasurement> tmColl = traj.measurements(); for(std::vector<TrajectoryMeasurement>::const_iterator itTraj = checkColl.begin(); itTraj != checkColl.end(); ++itTraj) { if(! itTraj->updatedState().isValid()) continue; TrajectoryStateOnSurface tsos = tsoscomb( itTraj->forwardPredictedState(), itTraj->backwardPredictedState() ); TransientTrackingRecHit::ConstRecHitPointer hit = itTraj->recHit(); if(! hit->isValid() || hit->geographicalId().det() != DetId::Tracker ) continue; const DetId & hit_detId = hit->geographicalId(); uint IntSubDetID = (hit_detId.subdetId()); if(IntSubDetID == 0 ) continue; // Select ?? if(IntSubDetID != PixelSubdetector::PixelBarrel) continue; // look only at bpix || IntSubDetID == PixelSubdetector::PixelEndcap) { // const GeomDetUnit* detUnit = hit->detUnit(); // if(detUnit) { // const Surface& surface = hit->detUnit()->surface(); // const TrackerGeometry& theTracker(*tkGeom_); // const PixelGeomDetUnit* theGeomDet = dynamic_cast<const PixelGeomDetUnit*> (theTracker.idToDet(hit_detId) ); // const RectangularPixelTopology * topol = dynamic_cast<const RectangularPixelTopology*>(&(theGeomDet->specificTopology())); // } // get the enclosed persistent hit const TrackingRecHit *persistentHit = hit->hit(); // check if it's not null, and if it's a valid pixel hit if ((persistentHit != 0) && (typeid(*persistentHit) == typeid(SiPixelRecHit))) { // tell the C++ compiler that the hit is a pixel hit const SiPixelRecHit* pixhit = dynamic_cast<const SiPixelRecHit*>( hit->hit() ); // get the edm::Ref to the cluster edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> const& clust = (*pixhit).cluster(); // check if the ref is not null if (clust.isNonnull()) { numberOfClusters++; pixelHits++; float charge = (clust->charge())/1000.0; // convert electrons to kilo-electrons int size = clust->size(); int size_x = clust->sizeX(); int size_y = clust->sizeY(); float row = clust->x(); float col = clust->y(); //LocalPoint lp = topol->localPosition(MeasurementPoint(clust_.row,clust_.col)); //float x = lp.x(); //float y = lp.y(); int maxPixelCol = clust->maxPixelCol(); int maxPixelRow = clust->maxPixelRow(); int minPixelCol = clust->minPixelCol(); int minPixelRow = clust->minPixelRow(); //int geoId = PixGeom->geographicalId().rawId(); // Replace with the topology methods // edge method moved to topologi class //int edgeHitX = (int) ( topol->isItEdgePixelInX( minPixelRow ) || topol->isItEdgePixelInX( maxPixelRow ) ); //int edgeHitY = (int) ( topol->isItEdgePixelInY( minPixelCol ) || topol->isItEdgePixelInY( maxPixelCol ) ); // calculate alpha and beta from cluster position //LocalTrajectoryParameters ltp = tsos.localParameters(); //LocalVector localDir = ltp.momentum()/ltp.momentum().mag(); //float locx = localDir.x(); //float locy = localDir.y(); //float locz = localDir.z(); //float loctheta = localDir.theta(); // currently unused //float alpha = atan2( locz, locx ); //float beta = atan2( locz, locy ); //clust_.normalized_charge = clust_.charge*sqrt(1.0/(1.0/pow(tan(clust_.clust_alpha),2)+1.0/pow(tan(clust_.clust_beta),2)+1.0)); } // valid cluster } // valid peristant hit } // loop over trajectory meas. if(PRINT) cout<<" Cluster for track "<<trackNumber<<" cluaters "<<numberOfClusters<<" "<<pixelHits<<endl; } // loop over tracks #endif // USE_TRAJ cout<<" event with tracks = "<<trackNumber<<" "<<countGoodTracks<<endl; } // end //define this as a plug-in DEFINE_FWK_MODULE(TestWithTracks);
[ "danek.kotlinski@psi.ch" ]
danek.kotlinski@psi.ch
654fc6c409a75b6e4b2c6588696e1ec9e7ac16ad
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/media/test/fake_encrypted_media.h
9e1e643a0ceefe7f2d482dc1cf398ce498904631
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,835
h
// Copyright 2017 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. #ifndef MEDIA_TEST_FAKE_ENCRYPTED_MEDIA_H_ #define MEDIA_TEST_FAKE_ENCRYPTED_MEDIA_H_ #include "media/base/cdm_context.h" #include "media/base/content_decryption_module.h" namespace media { class AesDecryptor; // Note: Tests using this class only exercise the DecryptingDemuxerStream path. // They do not exercise the Decrypting{Audio|Video}Decoder path. class FakeEncryptedMedia { public: // Defines the behavior of the "app" that responds to EME events. class AppBase { public: virtual ~AppBase() {} virtual void OnSessionMessage(const std::string& session_id, CdmMessageType message_type, const std::vector<uint8_t>& message, AesDecryptor* decryptor) = 0; virtual void OnSessionClosed(const std::string& session_id) = 0; virtual void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key, CdmKeysInfo keys_info) = 0; virtual void OnSessionExpirationUpdate(const std::string& session_id, base::Time new_expiry_time) = 0; virtual void OnEncryptedMediaInitData(EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data, AesDecryptor* decryptor) = 0; }; FakeEncryptedMedia(AppBase* app); ~FakeEncryptedMedia(); CdmContext* GetCdmContext(); // Callbacks for firing session events. Delegate to |app_|. void OnSessionMessage(const std::string& session_id, CdmMessageType message_type, const std::vector<uint8_t>& message); void OnSessionClosed(const std::string& session_id); void OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key, CdmKeysInfo keys_info); void OnSessionExpirationUpdate(const std::string& session_id, base::Time new_expiry_time); void OnEncryptedMediaInitData(EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data); private: class TestCdmContext : public CdmContext { public: TestCdmContext(Decryptor* decryptor); Decryptor* GetDecryptor() final; private: Decryptor* decryptor_; }; scoped_refptr<AesDecryptor> decryptor_; TestCdmContext cdm_context_; std::unique_ptr<AppBase> app_; DISALLOW_COPY_AND_ASSIGN(FakeEncryptedMedia); }; } // namespace media #endif // MEDIA_TEST_FAKE_ENCRYPTED_MEDIA_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a895c5eb6bec1153d70cf30ce6fc9a001a90652b
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/TransmitterPattern/Transmitter.h
a7656b3abfc3434e8609eb6ac9d03591993fcc53
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
2,349
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #pragma once #define MSG_TRANSMITTER_QUIT 0 class MessageDetails { public: virtual ~MessageDetails() {} }; class Receiver { public: virtual void OnMessage(UINT msgID, LPVOID sender, MessageDetails* detail) = 0; #ifdef _DEBUG virtual LPCTSTR GetReceiverName() = 0; #endif }; class Transmitter { public: virtual ~Transmitter() {} virtual void RegisterReceiver(Receiver& receiver) = 0; virtual void UnRegisterReceiver(Receiver& receiver) = 0; //===SendMessage //Sends a message directly to the Registered Receivers //- msgID: The App-Defined Identification of the message. *value 0 is reserved //- sender: [Optional]The sender of the message. //- detail: [Optional] Details for the message. // The receiver must be able to cast the derived MessageDetain through the ID virtual void SendMessage(UINT msgID, LPVOID sender = NULL, MessageDetails* detail = NULL) = 0; //===PostMessage //Queues the message in a storage. The message is being send in the next Heartbeat. //Extra options //- bGroupSimilar. Similar msgIDs may be grouped in one. virtual void PostMessage(UINT msgID, LPVOID sender = NULL, MessageDetails* detail = NULL, BOOL bGroupSimilar = FALSE) = 0; //===HeartBeat //- Posted Messages are send when HeartBeat is called virtual void HeartBeat() = 0; };
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678
3fcd6504c751ebdb71b7f16eca03ca6e31373112
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/External (Offsets Only)/SDK/Title_CollectorOfLegendaryVillainousSkulls_functions.cpp
021f9c3931668c2a45e25d0c5bf33586c2c80493
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
// Name: SoT-Insider, Version: 1.102.2382.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void UTitle_CollectorOfLegendaryVillainousSkulls_C::AfterRead() { UTitleDesc::AfterRead(); } void UTitle_CollectorOfLegendaryVillainousSkulls_C::BeforeDelete() { UTitleDesc::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
07098b4b168e50c19c07b2b2917c8648bff62df0
3f5945204403bff6dcfc1b16d536097fee7dff93
/mutex.cpp
7dec1022285eff15f35d3b25d48da371c7d8bab0
[]
no_license
chadatgcu/threading
646a6673b43abd8019df65b646dcc95db87370e8
1500d0ff5b7a78bdb0cf395bd41d014fc1354440
refs/heads/master
2020-05-30T12:56:25.324390
2019-06-01T15:43:31
2019-06-01T15:43:31
189,748,663
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
// Chad Weirick // CST-221 // This is a sample of a monitor process // This will simulate bank transactions #include <thread> #include <string> #include <mutex> #include <string.h> #include <cstdio> #include <iostream> #include <iomanip> using namespace std; std::mutex balanceMutex; float balance = 1000.00; void shared_balanceUpdate(float change, string origin, int id){ balanceMutex.lock(); float newBalance = balance + change; std::cout << std::fixed; std::cout << std::setprecision(2); cout << "Function: " << origin << "id: " << id << " balance: $" << balance << " adjustment: $" << change << " new balance: $" << newBalance << "\n"; balance = newBalance; balanceMutex.unlock(); } void additionSimulator(){ int multiplierVar = std::rand(); for (int i = 0; i<1000; i++){ float roundThis = ((int)(i * multiplierVar * 100 + 0.5) / 100.00); shared_balanceUpdate(roundThis, "addition sim", i); } } void subtractionSimulator(){ int multiplierVar = std::rand(); for (int i = 0; i>-1000; i--){ float roundThis = ((int)(i * multiplierVar * 100 + 0.5) / 100.00); shared_balanceUpdate(roundThis, "subtraction sim", (i * (0-1))); } } int main(){ std::thread t1(additionSimulator); std::thread t2(subtractionSimulator); t1.join(); t2.join(); return 0; }
[ "chad@chadandstephanieweirick.com" ]
chad@chadandstephanieweirick.com
9b6e807cf29ad17fdbd3aa7783b342195a49fc54
2f05d3dec54f3d72bd8405b1bf34d7b73cb0bf03
/code/exp-4-lmn/ns.cpp
c2b57e945b1ff78eb438b9a0e063959989cc409a
[]
no_license
anirudhakulkarni/Parallel-MCMF-at-IISc-Research
3ee6c61c190b95c7effcc7256ba76c87de29563c
ac1f794df529f2f1d002f79ae2c0d26f757e2f1a
refs/heads/master
2023-06-17T12:25:17.610142
2021-07-10T11:05:42
2021-07-10T11:05:42
368,953,615
0
0
null
null
null
null
UTF-8
C++
false
false
3,818
cpp
#include <iostream> #include <vector> #include <chrono> #include <string> #include <tuple> #include <lemon/smart_graph.h> #include <lemon/network_simplex.h> using namespace lemon; using namespace std; #define ln "\n" #define out1(x1) cout << x1 << ln #define out2(x1, x2) cout << x1 << " " << x2 << ln #define out3(x1, x2, x3) cout << x1 << " " << x2 << " " << x3 << ln #define out4(x1, x2, x3, x4) cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln #define out5(x1, x2, x3, x4, x5) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln #define out6(x1, x2, x3, x4, x5, x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln #include "debugger.cpp" #include "graph-generator.cpp" using Weight = int; using Capacity = int; using Graph = SmartDigraph; using Node = Graph::Node; using Arc = Graph::Arc; template<typename ValueType> using ArcMap = SmartDigraph::ArcMap<ValueType>; using NS = NetworkSimplex<SmartDigraph, Capacity, Weight>; int main(int argc, char const *argv[]) { int num = stoi(argv[1]); srand(time(0)); int tempList[15] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000}; int parameters[8] = {50, 100, 200, 300, 400, 600, 800, 1000}; vector<vector<int>> experiments; for (int i = 0; i < 15; i++) { experiments.push_back({parameters[num - 1], tempList[i]}); } // experiments={{2,2}}; for (int i = 0; i < experiments.size(); i++) { int numberOfSrcs = experiments[i][0]; int numberOfSnks = experiments[i][1]; int numberOfNodes = numberOfSrcs + numberOfSnks; int totalCapacity = 30000; int totalRequirement = 10000; vector<vector<int>> nodes = getNodes(numberOfNodes); vector<vector<int>> sources; vector<vector<int>> sinks; tie(sources, sinks) = distributeSourceSink(nodes, numberOfSrcs, totalCapacity, totalRequirement); vector<vector<int>> edgeList = getEdges(sources, sinks); // printedges(edgeList); // printsources(sources); // printsinks(sinks); Graph g; Graph::Node nodeMap[numberOfNodes + 2]; // Graph::Arc edgeMap[edgeList.size()+numberOfNodes]; ArcMap<Weight> weights(g); ArcMap<Capacity> capacities(g); Node u; for (int i = 0; i < numberOfNodes + 2; i++) { u = g.addNode(); nodeMap[i] = u; } Arc a; for (int i = 1; i < numberOfSrcs + 1; i++) { a = g.addArc(nodeMap[0], nodeMap[i]); weights[a] = 0; capacities[a] = sources[i - 1][1]; } for (int i = 0; i < edgeList.size(); i++) { a = g.addArc(nodeMap[edgeList[i][0]], nodeMap[edgeList[i][1]]); // edgeMap[i]=a; weights[a] = edgeList[i][2]; capacities[a] = INT32_MAX; } for (int i = numberOfSrcs + 1; i < numberOfNodes + 1; i++) { a = g.addArc(nodeMap[i], nodeMap[numberOfNodes + 1]); weights[a] = 0; capacities[a] = sinks[i - numberOfSrcs - 1][1]; } NS ns(g); ns.costMap(weights).upperMap(capacities).stSupply(nodeMap[0], nodeMap[numberOfNodes + 1], 10000); ArcMap<Capacity> flows(g); NS::ProblemType status = ns.run(); switch (status) { case NS::INFEASIBLE: cerr << "insufficient flow" << endl; break; case NS::OPTIMAL: ns.flowMap(flows); // cerr<<ns.flow(a); cerr << "cost=" << ns.totalCost() << endl; break; case NS::UNBOUNDED: cerr << "infinite flow" << endl; break; default: break; } } return 0; }
[ "kulkarnianirudha8@gmail.com" ]
kulkarnianirudha8@gmail.com
4953147a7cd4fed7322e9f1be11d61d0b98e4bfa
cd470ad61c4dbbd37ff004785fd6d75980987fe9
/Codeforces/1195/B/std.cpp
dc73e0646a984ae44f4e0b58a386d991f9608065
[]
no_license
AutumnKite/Codes
d67c3770687f3d68f17a06775c79285edc59a96d
31b7fc457bf8858424172bc3580389badab62269
refs/heads/master
2023-02-17T21:33:04.604104
2023-02-17T05:38:57
2023-02-17T05:38:57
202,944,952
3
1
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include <bits/stdc++.h> int n, k; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cin >> n >> k; for (int i = 0; i <= n; ++i) { if (1ll * i * (i + 1) / 2 - (n - i) == k) { std::cout << n - i << "\n"; return 0; } } }
[ "1790397194@qq.com" ]
1790397194@qq.com
e4d4c2417ca9d53b653219ff7f17491bcc3951cd
f2cfa4ea8d0ec66eb722fba47b13181ac003f228
/GameServer/Unit.cpp
2be5298404c47fa50fd8457fab3a3e26361bb794
[]
no_license
Mortgy/KODevelopers-1534
a2b0cbfbd706245b8f486568d9f2ff65385c05a2
cd3c07dd310baee59702c78ca165c177464ec161
refs/heads/master
2021-05-22T18:30:24.818341
2017-12-09T05:58:19
2017-12-09T05:58:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,615
cpp
#include "stdafx.h" #include "Map.h" #ifdef GAMESERVER # include "GameServerDlg.h" # include "MagicInstance.h" #else # include "../AIServer/ServerDlg.h" # include "../AIServer/Npc.h" # include "../AIServer/User.h" #endif #include <cfloat> Unit::Unit(UnitType unitType) : m_pMap(nullptr), m_pRegion(nullptr), m_sRegionX(0), m_sRegionZ(0), m_unitType(unitType) { Initialize(); } void Unit::Initialize() { m_pMap = nullptr; m_pRegion = nullptr; SetPosition(0.0f, 0.0f, 0.0f); m_bLevel = 0; m_bNation = 0; m_sTotalHit = 0; m_sTotalAc = 0; m_fTotalHitrate = 0.0f; m_fTotalEvasionrate = 0.0f; m_bResistanceBonus = 0; m_sFireR = m_sColdR = m_sLightningR = m_sMagicR = m_sDiseaseR = m_sPoisonR = 0; m_sDaggerR = m_sSwordR = m_sAxeR = m_sMaceR = m_sSpearR = m_sBowR = 0; m_byDaggerRAmount = m_byBowRAmount = 100; Guard lock(m_equippedItemBonusLock); m_equippedItemBonuses.clear(); m_bCanStealth = true; m_ReflectUsageSkill = 0; m_bIsBlinded = false; m_bCanUseSkills = m_bCanUsePotions = m_bCanTeleport = true; m_bInstantCast = false; m_bIsUndead = m_bIsKaul = false; m_bBlockPhysical = m_bBlockMagic = false; m_bBlockCurses = m_bReflectCurses = false; m_bMirrorDamage = false; m_byMirrorAmount = 0; m_sAttackSpeedAmount = 100; // this is for the duration spells Type 4 m_bSpeedAmount = 100; m_sACAmount = 0; m_sACPercent = 100; m_bAttackAmount = 100; m_sMagicAttackAmount = 0; m_sMaxHPAmount = m_sMaxMPAmount = 0; m_bHitRateAmount = 100; m_sAvoidRateAmount = 100; m_bAddFireR = m_bAddColdR = m_bAddLightningR = 0; m_bAddMagicR = m_bAddDiseaseR = m_bAddPoisonR = 0; m_bPctFireR = m_bPctColdR = m_bPctLightningR = 100; m_bPctMagicR = m_bPctDiseaseR = m_bPctPoisonR = 100; m_bMagicDamageReduction = 100; m_bManaAbsorb = 0; m_bRadiusAmount = 0; m_buffCount = 0; m_oSocketID = -1; m_bEventRoom = 0; InitType3(); InitType4(true); } /* NOTE: Due to KO messiness, we can really only calculate a 2D distance/ There are a lot of instances where the y (height level, in this case) coord isn't set, which understandably screws things up a lot. */ // Calculate the distance between 2 2D points. float Unit::GetDistance(float fx, float fz) { return (float)GetDistance(GetX(), GetZ(), fx, fz); } // Calculate the 2D distance between Units. float Unit::GetDistance(Unit * pTarget) { if (pTarget != nullptr){ ASSERT(pTarget != nullptr); if (m_bZone && GetZoneID() != pTarget->GetZoneID()) return -FLT_MAX; return GetDistance(pTarget->GetX(), pTarget->GetZ()); }else{ return -FLT_MAX; } } float Unit::GetDistanceSqrt(Unit * pTarget) { if (pTarget != nullptr){ ASSERT(pTarget != nullptr); if (GetZoneID() != pTarget->GetZoneID()) return -FLT_MAX; return sqrtf(GetDistance(pTarget->GetX(), pTarget->GetZ())); }else{ return -FLT_MAX; } } // Check to see if the Unit is in 2D range of another Unit. // Range MUST be squared already. bool Unit::isInRange(Unit * pTarget, float fSquaredRange) { return (GetDistance(pTarget) <= fSquaredRange); } // Check to see if we're in the 2D range of the specified coordinates. // Range MUST be squared already. bool Unit::isInRange(float fx, float fz, float fSquaredRange) { return (GetDistance(fx, fz) <= fSquaredRange); } // Check to see if the Unit is in 2D range of another Unit. // Range must NOT be squared already. // This is less preferable to the more common precalculated range. bool Unit::isInRangeSlow(Unit * pTarget, float fNonSquaredRange) { return isInRange(pTarget, pow(fNonSquaredRange, 2.0f)); } // Check to see if the Unit is in 2D range of the specified coordinates. // Range must NOT be squared already. // This is less preferable to the more common precalculated range. bool Unit::isInRangeSlow(float fx, float fz, float fNonSquaredRange) { return isInRange(fx, fz, pow(fNonSquaredRange, 2.0f)); } float Unit::GetDistance(float fStartX, float fStartZ, float fEndX, float fEndZ) { return pow(fStartX - fEndX, 2.0f) + pow(fStartZ - fEndZ, 2.0f); } bool Unit::isInRange(float fStartX, float fStartZ, float fEndX, float fEndZ, float fSquaredRange) { return (GetDistance(fStartX, fStartZ, fEndX, fEndZ) <= fSquaredRange); } bool Unit::isInRangeSlow(float fStartX, float fStartZ, float fEndX, float fEndZ, float fNonSquaredRange) { return isInRange(fStartX, fStartZ, fEndX, fEndZ, pow(fNonSquaredRange, 2.0f)); } #ifdef GAMESERVER void Unit::SetRegion(uint16 x /*= -1*/, uint16 z /*= -1*/) { m_sRegionX = x; m_sRegionZ = z; m_pRegion = m_pMap->GetRegion(x, z); // TODO: Clean this up } bool Unit::RegisterRegion() { uint16 new_region_x = GetNewRegionX(), new_region_z = GetNewRegionZ(), old_region_x = GetRegionX(), old_region_z = GetRegionZ(); if (GetRegion() == nullptr || (old_region_x == new_region_x && old_region_z == new_region_z)) return false; AddToRegion(new_region_x, new_region_z); RemoveRegion(old_region_x - new_region_x, old_region_z - new_region_z); InsertRegion(new_region_x - old_region_x, new_region_z - old_region_z); return true;//error } void Unit::RemoveRegion(int16 del_x, int16 del_z) { ASSERT(GetMap() != nullptr); Packet result; GetInOut(result, INOUT_OUT); g_pMain->Send_OldRegions(&result, del_x, del_z, GetMap(), GetRegionX(), GetRegionZ(), nullptr, GetEventRoom()); } void Unit::InsertRegion(int16 insert_x, int16 insert_z) { ASSERT(GetMap() != nullptr); Packet result; GetInOut(result, INOUT_IN); g_pMain->Send_NewRegions(&result, insert_x, insert_z, GetMap(), GetRegionX(), GetRegionZ(), nullptr, GetEventRoom());//error } #endif /* These should not be declared here, but it's necessary until the AI server better shares unit code */ /** * @brief Calculates damage for players attacking either monsters/NPCs or other players. * * @param pTarget Target unit. * @param pSkill The skill used in the attack, if applicable.. * @param bPreviewOnly true to preview the damage only and not apply any item bonuses. * Used by AI logic to determine who to target (by checking who deals the most damage). * * @return The damage. */ short CUser::GetDamage(Unit *pTarget, _MAGIC_TABLE *pSkill /*= nullptr*/, bool bPreviewOnly /*= false*/) { /* This seems identical to users attacking NPCs/monsters. The only differences are: - GetACDamage() is not called - the resulting damage is not divided by 3. */ int32 damage = 0; int random = 0; int32 temp_hit = 0, temp_ac = 0, temp_ap = 0, temp_hit_B = 0; uint8 result; if (pTarget == nullptr || pTarget->isDead()) return -1; // Trigger item procs if (pTarget->isPlayer() && !bPreviewOnly) { OnAttack(pTarget, AttackTypePhysical); pTarget->OnDefend(this, AttackTypePhysical); } temp_ac = pTarget->m_sTotalAc; // A unit's total AC shouldn't ever go below 0. if ((pTarget->m_sACAmount) <= 0) pTarget->m_sACAmount = 0; else temp_ac += pTarget->m_sACAmount; if (pTarget->m_sACPercent > 0 && pTarget->m_sACPercent < 100) temp_ac -= temp_ac * (100 - pTarget->m_sACPercent) / 100; temp_ap = m_sTotalHit * m_bAttackAmount; #ifdef GAMESERVER // Apply player vs player AC/AP bonuses. if (pTarget->isPlayer()) { CUser * pTUser = TO_USER(pTarget); // NOTE: using a = a*v instead of a *= v because the compiler assumes different // types being multiplied, which results in these calcs not behaving correctly. // adjust player AP by percent, for skills like "Critical Point" temp_ap = temp_ap * m_bPlayerAttackAmount / 100; // Now handle class-specific AC/AP bonuses. temp_ac = temp_ac * (100 + pTUser->m_byAcClassBonusAmount[GetBaseClassType() - 1]) / 100; temp_ap = temp_ap * (100 + m_byAPClassBonusAmount[pTUser->GetBaseClassType() - 1]) / 100; } #endif // Allow for complete physical damage blocks. // NOTE: Unsure if we need to count skill usage as magic damage or if we // should only block that in explicit magic damage skills (CMagicProcess::GetMagicDamage()). if (pTarget->m_bBlockPhysical) return 0; temp_hit_B = (int)((temp_ap * 200 / 100) / (temp_ac + 240)); // Skill/arrow hit. if (pSkill != nullptr) { // SKILL HIT! YEAH! if (pSkill->bType[0] == 1) { _MAGIC_TYPE1 *pType1 = g_pMain->m_Magictype1Array.GetData(pSkill->iNum); if (pType1 == nullptr) return -1; // Non-relative hit. if (pType1->bHitType) { result = (pType1->sHitRate <= myrand(0, 100) ? FAIL : SUCCESS); } // Relative hit. else { result = GetHitRate((m_fTotalHitrate / pTarget->m_fTotalEvasionrate) * (pType1->sHitRate / 100.0f)); } temp_hit = (int32)(temp_hit_B * (pType1->sHit / 100.0f)); } // ARROW HIT! YEAH! else if (pSkill->bType[0] == 2) { _MAGIC_TYPE2 *pType2 = g_pMain->m_Magictype2Array.GetData(pSkill->iNum); if (pType2 == nullptr) return -1; // Non-relative/Penetration hit. if (pType2->bHitType == 1 || pType2->bHitType == 2) { result = (pType2->sHitRate <= myrand(0, 100) ? FAIL : SUCCESS); } // Relative hit/Arc hit. else { result = GetHitRate((m_fTotalHitrate / pTarget->m_fTotalEvasionrate) * (pType2->sHitRate / 100.0f)); } if (pType2->bHitType == 1 /* || pType2->bHitType == 2 */) temp_hit = (int32)(m_sTotalHit * m_bAttackAmount * (pType2->sAddDamage / 100.0f) / 100); else temp_hit = (int32)(temp_hit_B * (pType2->sAddDamage / 100.0f)); } } // Normal hit (R attack) else { temp_hit = temp_ap / 100; result = GetHitRate(m_fTotalHitrate / pTarget->m_fTotalEvasionrate); } switch (result) { // 1. Magical item damage.... case GREAT_SUCCESS: case SUCCESS: case NORMAL: if (pSkill != nullptr) { // Skill Hit. damage = temp_hit; random = myrand(0, damage); if (pSkill->bType[0] == 1) damage = (short)((temp_hit + 0.3f * random) + 0.99f); else damage = (short)(((temp_hit * 0.6f) + 1.0f * random) + 0.99f); } else { // Normal Hit. #ifdef GAMESERVER if (isGM() && !pTarget->isPlayer()) { if (g_pMain->m_nGameMasterRHitDamage != 0) { damage = g_pMain->m_nGameMasterRHitDamage; return damage; } } #endif damage = temp_hit_B; random = myrand(0, damage); damage = (short)((0.85f * temp_hit_B) + 0.3f * random); } break; case FAIL: if (pSkill != nullptr) { // Skill Hit. } else { // Normal Hit. #ifdef GAMESERVER if (isGM() && !pTarget->isPlayer()) { damage = 30000; return damage; } #endif } } // Apply item bonuses damage = GetMagicDamage(damage, pTarget, bPreviewOnly); // These two only apply to players if (pTarget->isPlayer()) { damage = GetACDamage(damage, pTarget); // 3. Additional AC calculation.... // Give increased damage in war zones (as per official 1.298~1.325) // This may need to be revised to use the last nation to win the war, or more accurately, // the nation that last won the war 3 times in a row (whether official behaves this way now is unknown). if (GetMap()->isWarZone()) damage /= 2; else damage /= 2; } // Enforce damage cap if (damage > MAX_DAMAGE) damage = MAX_DAMAGE; return damage; } #if GAMESERVER void CUser::OnAttack(Unit * pTarget, AttackType attackType) { if (!pTarget->isPlayer() || attackType == AttackTypeMagic) return; // Trigger weapon procs for the attacker on attack static const uint8 itemSlots[] = { RIGHTHAND, LEFTHAND }; foreach_array (i, itemSlots) { // If we hit an applicable weapon, don't try proc'ing the other weapon. // It is only ever meant to proc on the dominant weapon. if (TriggerProcItem(itemSlots[i], pTarget, TriggerTypeAttack)) break; } } void CUser::OnDefend(Unit * pAttacker, AttackType attackType) { if (!pAttacker->isPlayer()) return; // Trigger defensive procs for the defender when being attacked static const uint8 itemSlots[] = { LEFTHAND }; foreach_array (i, itemSlots) TriggerProcItem(itemSlots[i], pAttacker, TriggerTypeDefend); } /** * @brief Trigger item procs. * * @param bSlot Slot of item to attempt to proc. * @param pTarget Target of the skill (attacker/defender depending on the proc type). * @param triggerType Which type of item to proc (offensive/defensive). * * @return true if there's an applicable item to proc, false if not. */ bool CUser::TriggerProcItem(uint8 bSlot, Unit * pTarget, ItemTriggerType triggerType) { // Don't proc weapon skills if our weapon is disabled. if (triggerType == TriggerTypeAttack && isWeaponsDisabled()) return false; // Ensure there's an item in this slot, _ITEM_DATA * pItem = GetItem(bSlot); if (pItem == nullptr // and that it doesn't need to be repaired. || pItem->sDuration == 0) return false; // not an applicable item // Ensure that this item has an attached proc skill in the table _ITEM_OP * pData = g_pMain->m_ItemOpArray.GetData(pItem->nNum); if (pData == nullptr // no skill to proc || pData->bTriggerType != triggerType) // don't use an offensive proc when we're defending (or vice versa) return false; // not an applicable item // At this point, we have determined there is an applicable item in the slot. // Should it proc now? (note: CheckPercent() checks out of 1000) if (!CheckPercent(pData->bTriggerRate * 10)) return true; // it is an applicable item, it just didn't proc. No need to proc subsequent items. MagicInstance instance; instance.bIsItemProc = true; instance.sCasterID = GetID(); instance.sTargetID = pTarget->GetID(); instance.nSkillID = pData->nSkillID; // For AOE skills such as "Splash", the AOE should be focus on the target. instance.sData[0] = (uint16) pTarget->GetX(); instance.sData[2] = (uint16) pTarget->GetZ(); instance.Run(); return true; // it is an applicable item, and it proc'd. No need to proc subsequent items. } #endif short CNpc::GetDamage(Unit *pTarget, _MAGIC_TABLE *pSkill /*= nullptr*/, bool bPreviewOnly /*= false*/) { if (pTarget->isPlayer()) return GetDamage(TO_USER(pTarget), pSkill); return GetDamage(TO_NPC(pTarget), pSkill); } /** * @brief Calculates damage for monsters/NPCs attacking players. * * @param pTarget Target player. * @param pSkill The skill (not used here). * @param bPreviewOnly true to preview the damage only and not apply any item bonuses (not used here). * * @return The damage. */ short CNpc::GetDamage(CUser *pTarget, _MAGIC_TABLE *pSkill /*= nullptr*/, bool bPreviewOnly /*= false*/) { if (pTarget == nullptr) return 0; int32 damage = 0, HitB; int32 Ac = pTarget->m_sTotalAc; // A unit's total AC shouldn't ever go below 0. if ((pTarget->m_sACAmount) <= 0) pTarget->m_sACAmount = 0; else Ac += pTarget->m_sACAmount; Ac = TO_USER(pTarget)->m_sItemAc + pTarget->GetLevel() + (Ac - pTarget->GetLevel() - TO_USER(pTarget)->m_sItemAc); HitB = (int)((m_sTotalHit * m_bAttackAmount * 200 / 100) / (Ac + 240)); if (HitB <= 0) return 0; uint8 result = GetHitRate(m_fTotalHitrate / pTarget->m_fTotalEvasionrate); switch (result) { case GREAT_SUCCESS: damage = (int)(0.3f * myrand(0, HitB)); damage += (short)(0.85f * (float)HitB); damage = (damage * 3) / 2; break; case SUCCESS: case NORMAL: damage = (int)(0.3f * myrand(0, HitB)); damage += (short)(0.85f * (float)HitB); break; } int nMaxDamage = (int)(2.6 * m_sTotalHit); if (damage > nMaxDamage) damage = nMaxDamage; // Enforce overall damage cap if (damage > MAX_DAMAGE) damage = MAX_DAMAGE; return (short) damage; } /** * @brief Calculates damage for monsters/NPCs attacking other monsters/NPCs. * * @param pTarget Target NPC/monster. * @param pSkill The skill (not used here). * @param bPreviewOnly true to preview the damage only and not apply any item bonuses (not used here). * * @return The damage. */ short CNpc::GetDamage(CNpc *pTarget, _MAGIC_TABLE *pSkill /*= nullptr*/, bool bPreviewOnly /*= false*/) { if (pTarget == nullptr) return 0; short damage = 0, Hit = m_sTotalHit, Ac = pTarget->m_sTotalAc; uint8 result = GetHitRate(m_fTotalHitrate / pTarget->m_fTotalEvasionrate); switch (result) { case GREAT_SUCCESS: damage = (short)(0.6 * Hit); if (damage <= 0) { damage = 0; break; } damage = myrand(0, damage); damage += (short)(0.7 * Hit); break; case SUCCESS: case NORMAL: if (Hit - Ac > 0) { damage = (short)(0.6 * (Hit - Ac)); if (damage <= 0) { damage = 0; break; } damage = myrand(0, damage); damage += (short)(0.7 * (Hit - Ac)); } break; } // Enforce damage cap if (damage > MAX_DAMAGE) damage = MAX_DAMAGE; return damage; } short Unit::GetMagicDamage(int damage, Unit *pTarget, bool bPreviewOnly /*= false*/) { if (pTarget->isDead() || pTarget->isDead() || pTarget-> isBlinking()) return 0; Guard lock(m_equippedItemBonusLock); int16 sReflectDamage = 0; bool sKontrol = false; // Check each item that has a bonus effect. int aa = m_equippedItemBonuses.size(); foreach (itr, m_equippedItemBonuses) { // Each item can support multiple bonuses. // Thus, we must handle each bonus. int ss = itr->second.size(); foreach (bonusItr, itr->second) { short total_r = 0, temp_damage = 0; uint8 bType = bonusItr->first; int16 sAmount = bonusItr->second; bool bIsDrain = (bType >= ITEM_TYPE_HP_DRAIN && bType <= ITEM_TYPE_MP_DRAIN); if (bIsDrain) temp_damage = damage * sAmount / 100; switch (bType) { case ITEM_TYPE_FIRE: total_r = (pTarget->m_sFireR + pTarget->m_bAddFireR) * pTarget->m_bPctFireR / 100; break; case ITEM_TYPE_COLD: total_r = (pTarget->m_sColdR + pTarget->m_bAddColdR) * pTarget->m_bPctColdR / 100; break; case ITEM_TYPE_LIGHTNING: total_r = (pTarget->m_sLightningR + pTarget->m_bAddLightningR) * pTarget->m_bPctLightningR / 100; break; case ITEM_TYPE_HP_DRAIN: pTarget->HpChange(temp_damage); sKontrol = true; break; case ITEM_TYPE_MP_DAMAGE: pTarget->MSpChange(-temp_damage); sKontrol = true; break; case ITEM_TYPE_MP_DRAIN: MSpChange(temp_damage); sKontrol = true; break; case ITEM_TYPE_MIRROR_DAMAGE: sReflectDamage += sAmount; break; } total_r += pTarget->m_bResistanceBonus; if (!bIsDrain) { if (total_r > 200) total_r = 200; temp_damage = sAmount - sAmount * total_r / 200; damage += temp_damage; } else if(bType == ITEM_TYPE_HP_DRAIN) { HpChange(temp_damage); temp_damage = sAmount - sAmount * total_r / 200; return damage += temp_damage; } } } // If any items have have damage reflection enabled, we should reflect this back to the client. // NOTE: This should only apply to shields, so it should only ever apply once. // We do this here to ensure it's taking into account the total calculated damage. if (sReflectDamage > 0 && !sKontrol) { short temp_damage = damage * sReflectDamage / 100; HpChange(-temp_damage); } return damage; } short Unit::GetACDamage(int damage, Unit *pTarget) { // This isn't applicable to NPCs. if (!isPlayer() || !pTarget->isPlayer()) return damage; #ifdef GAMESERVER if (pTarget->isDead()) return 0; CUser * pUser = TO_USER(this); if (pUser->isWeaponsDisabled()) return damage; uint8 weaponSlots[] = { LEFTHAND, RIGHTHAND }; int firstdamage = damage; foreach_array (slot, weaponSlots) { _ITEM_TABLE * pWeapon = pUser->GetItemPrototype(weaponSlots[slot]); if (pWeapon == nullptr) continue; if (pWeapon->isDagger()) damage -= damage * pTarget->m_sDaggerR / 200; else if (pWeapon->isSword()) damage -= damage * pTarget->m_sSwordR / 200; else if (pWeapon->isAxe()) damage -= damage * pTarget->m_sAxeR / 200; else if (pWeapon->isMace()) damage -= damage * pTarget->m_sMaceR / 200; else if (pWeapon->isSpear()) damage -= damage * pTarget->m_sSpearR / 200; else if (pWeapon->isBow()) damage -= damage * pTarget->m_sBowR / 200; } #endif return damage; } uint8 Unit::GetHitRate(float rate) { int random = myrand(1, 10000); if (rate >= 5.0f) { if (random >= 1 && random <= 3500) return GREAT_SUCCESS; else if (random >= 3501 && random <= 7500) return SUCCESS; else if (random >= 7501 && random <= 9800) return NORMAL; } else if (rate < 5.0f && rate >= 3.0f) { if (random >= 1 && random <= 2500) return GREAT_SUCCESS; else if (random >= 2501 && random <= 6000) return SUCCESS; else if (random >= 6001 && random <= 9600) return NORMAL; } else if (rate < 3.0f && rate >= 2.0f) { if (random >= 1 && random <= 2000) return GREAT_SUCCESS; else if (random >= 2001 && random <= 5000) return SUCCESS; else if (random >= 5001 && random <= 9400) return NORMAL; } else if (rate < 2.0f && rate >= 1.25f) { if (random >= 1 && random <= 1500) return GREAT_SUCCESS; else if (random >= 1501 && random <= 4000) return SUCCESS; else if (random >= 4001 && random <= 9200) return NORMAL; } else if (rate < 1.25f && rate >= 0.8f) { if (random >= 1 && random <= 1000) return GREAT_SUCCESS; else if (random >= 1001 && random <= 3000) return SUCCESS; else if (random >= 3001 && random <= 9000) return NORMAL; } else if (rate < 0.8f && rate >= 0.5f) { if (random >= 1 && random <= 800) return GREAT_SUCCESS; else if (random >= 801 && random <= 2500) return SUCCESS; else if (random >= 2501 && random <= 8000) return NORMAL; } else if (rate < 0.5f && rate >= 0.33f) { if (random >= 1 && random <= 600) return GREAT_SUCCESS; else if (random >= 601 && random <= 2000) return SUCCESS; else if (random >= 2001 && random <= 7000) return NORMAL; } else if (rate < 0.33f && rate >= 0.2f) { if (random >= 1 && random <= 400) return GREAT_SUCCESS; else if (random >= 401 && random <= 1500) return SUCCESS; else if (random >= 1501 && random <= 6000) return NORMAL; } else { if (random >= 1 && random <= 200) return GREAT_SUCCESS; else if (random >= 201 && random <= 1000) return SUCCESS; else if (random >= 1001 && random <= 5000) return NORMAL; } return FAIL; } #ifdef GAMESERVER void Unit::SendToRegion(Packet *result) { g_pMain->Send_Region(result, GetMap(), GetRegionX(), GetRegionZ(), nullptr, GetEventRoom()); } // Handle it here so that we don't need to ref the class everywhere void Unit::Send_AIServer(Packet *result) { g_pMain->Send_AIServer(result); } #endif void Unit::InitType3() { for (int i = 0; i < MAX_TYPE3_REPEAT; i++) m_durationalSkills[i].Reset(); m_bType3Flag = false; } void Unit::InitType4(bool bRemoveSavedMagic /*= false*/, uint8 buffType /* = 0 */) { // Remove all buffs that should not be recast. Guard lock(m_buffLock); Type4BuffMap buffMap = m_buffMap; // copy the map for (auto itr = buffMap.begin(); itr != buffMap.end(); itr++) { #ifdef GAMESERVER if (buffType > 0 && itr->second.m_bBuffType != buffType) continue; CMagicProcess::RemoveType4Buff(itr->first, this, bRemoveSavedMagic, buffType > 0 ? true : false); #endif } } /** * @brief Determine if this unit is basically able to attack the specified unit. * This should only be called to handle the minimal shared logic between * NPCs and players. * * You should use the more appropriate CUser or CNpc specialization. * * @param pTarget Target for the attack. * * @return true if we can attack, false if not. */ bool Unit::CanAttack(Unit * pTarget) { if (pTarget == nullptr) return false; // Units cannot attack units in different zones. if (GetZoneID() != pTarget->GetZoneID()) return false; // We cannot attack our target if we are incapacitated // (should include debuffs & being blinded) if (isIncapacitated() // or if our target is in a state in which // they should not be allowed to be attacked || pTarget->isDead() || pTarget->isBlinking()) return false; // Finally, we can only attack the target if we are hostile towards them. return isHostileTo(pTarget); } /** * @brief Determine if this unit is basically able to attack the specified unit. * This should only be called to handle the minimal shared logic between * NPCs and players. * * You should use the more appropriate CUser or CNpc specialization. * * @param pTarget Target for the attack. * * @return true if we attackable, false if not. */ bool Unit::isAttackable(Unit * pTarget) { if (pTarget == nullptr) pTarget = this; if (pTarget) { if (pTarget->isNPC()) { CNpc * pNpc = TO_NPC(pTarget); if (pNpc != nullptr) { #if defined(GAMESERVER) if (pNpc->GetType() == NPC_BDW_MONUMENT) return true; if (pNpc->GetType() == NPC_BIFROST_MONUMENT) return (g_pMain->m_bAttackBifrostMonument); else if (pNpc->GetType() == NPC_PVP_MONUMENT) { if ((GetNation() == KARUS && pNpc->m_sPid == MONUMENT_KARUS_SPID) || (GetNation() == ELMORAD && pNpc->m_sPid == MONUMENT_ELMORAD_SPID)) return true; } else if (pNpc->GetType() == NPC_GUARD_TOWER1 || pNpc->GetType() == NPC_GUARD_TOWER2 || pNpc->GetType() == NPC_GATE2 || pNpc->GetType() == NPC_VICTORY_GATE || pNpc->GetType() == NPC_PHOENIX_GATE || pNpc->GetType() == NPC_SPECIAL_GATE || pNpc->GetType() == NPC_GATE_LEVER) return false; else if (pNpc->m_sSid == 8850 && !GetMap()->canAttackOtherNation()) return false; #endif } } } return true; } bool Unit::CanCastRHit(uint16 m_socketID) { #if defined(GAMESERVER) CUser *pUser = g_pMain->GetUserPtr(m_socketID); if (pUser == nullptr) return true; if (pUser->m_RHitRepeatList.find(m_socketID) != pUser->m_RHitRepeatList.end()) { RHitRepeatList::iterator itr = pUser->m_RHitRepeatList.find(m_socketID); if (float(UNIXTIME - itr->second) < PLAYER_R_HIT_REQUEST_INTERVAL) return false; else { pUser->m_RHitRepeatList.erase(m_socketID); return true; } } #endif return true; } void Unit::OnDeath(Unit *pKiller) { #ifdef GAMESERVER SendDeathAnimation(pKiller); #endif } void Unit::SendDeathAnimation(Unit * pKiller /*= nullptr*/) { #ifdef GAMESERVER Packet result(WIZ_DEAD); result << GetID(); SendToRegion(&result); #else Packet result(AG_DEAD); int16 tid = (pKiller == nullptr ? -1 : pKiller->GetID()); result << GetID() << tid; g_pMain->Send(&result); #endif } void Unit::AddType4Buff(uint8 bBuffType, _BUFF_TYPE4_INFO & pBuffInfo) { Guard lock(m_buffLock); m_buffMap.insert(std::make_pair(bBuffType, pBuffInfo)); if (pBuffInfo.isBuff()) m_buffCount++; } /************************************************************************** * The following methods should not be here, but it's necessary to avoid * code duplication between AI and GameServer until they're better merged. **************************************************************************/ /** * @brief Sets zone attributes for the loaded zone. * * @param zoneNumber The zone number. */ void KOMap::SetZoneAttributes(int zoneNumber) { m_zoneFlags = 0; #if defined(GAMESERVER) m_byTariff = g_pMain->GetTariffByZone(zoneNumber); // defaults to 10 officially for zones that don't use it. #else m_byTariff = 10; // defaults to 10 officially for zones that don't use it. #endif m_byMinLevel = 1; m_byMaxLevel = MAX_LEVEL; switch (zoneNumber) { case ZONE_KARUS: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_CLAN_UPDATE; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_ELMORAD: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_CLAN_UPDATE; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_KARUS_ESLANT: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; m_byMinLevel = MIN_LEVEL_ESLANT, m_byMaxLevel = MAX_LEVEL; break; case ZONE_ELMORAD_ESLANT: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; m_byMinLevel = MIN_LEVEL_ESLANT, m_byMaxLevel = MAX_LEVEL; break; case ZONE_MORADON: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS | ZF_CLAN_UPDATE; break; case ZONE_DELOS: m_zoneType = ZoneAbilitySiegeDisabled; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_BIFROST: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS ; m_byMinLevel = MIN_LEVEL_BIFROST, m_byMaxLevel = MAX_LEVEL; break; case ZONE_DESPERATION_ABYSS: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_HELL_ABYSS: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_DRAGON_CAVE: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS; m_byMinLevel = MIN_LEVEL_NATION_BASE, m_byMaxLevel = MAX_LEVEL; break; case ZONE_ARENA: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_ATTACK_SAME_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_ORC_ARENA: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_BLOOD_DON_ARENA: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_GOBLIN_ARENA: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_CAITHAROS_ARENA: m_zoneType = ZoneAbilityCaitharosArena; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_FORGOTTEN_TEMPLE: m_zoneType = ZoneAbilityNeutral; m_zoneFlags = ZF_TRADE_OTHER_NATION | ZF_TALK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_BATTLE: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_BATTLE2: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_BATTLE3: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; /*m_byMinLevel = MIN_LEVEL_NIEDS_TRIANGLE, m_byMaxLevel = MAX_LEVEL_NIEDS_TRIANGLE;*/ break; case ZONE_BATTLE4: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_BATTLE5: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_BATTLE6: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_SNOW_BATTLE: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_WAR_ZONE; break; case ZONE_RONARK_LAND: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; m_byMinLevel = MIN_LEVEL_RONARK_LAND, m_byMaxLevel = MAX_LEVEL; break; case ZONE_ARDREAM: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; m_byMinLevel = MIN_LEVEL_ARDREAM, m_byMaxLevel = MAX_LEVEL_ARDREAM; break; case ZONE_RONARK_LAND_BASE: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; m_byMinLevel = MIN_LEVEL_RONARK_LAND_BASE, m_byMaxLevel = MAX_LEVEL_RONARK_LAND_BASE; break; case ZONE_KROWAZ_DOMINION: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS | ZF_WAR_ZONE; m_byMinLevel = MIN_LEVEL_KROWAZ_DOMINION, m_byMaxLevel = MAX_LEVEL; break; case ZONE_BORDER_DEFENSE_WAR: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION; case ZONE_CHAOS_DUNGEON: m_zoneType = ZoneAbilityPVP; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_ATTACK_SAME_NATION | ZF_WAR_ZONE; break; case ZONE_JURAD_MOUNTAIN: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS | ZF_WAR_ZONE; m_byMinLevel = MIN_LEVEL_JURAD_MOUNTAIN, m_byMaxLevel = MAX_LEVEL; break; case ZONE_PRISON: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS; break; case ZONE_ISILOON_ARENA: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS | ZF_WAR_ZONE; case ZONE_FELANKOR_ARENA: m_zoneType = ZoneAbilityPVPNeutralNPCs; m_zoneFlags = ZF_TALK_OTHER_NATION | ZF_ATTACK_OTHER_NATION | ZF_FRIENDLY_NPCS | ZF_WAR_ZONE; break; default: m_zoneType = ZoneAbilityPVP; break; } } /** * @brief Determines if an NPC is hostile to a unit. * Non-hostile units cannot be attacked. * * @param pTarget Target unit * * @return true if hostile to, false if not. */ bool CNpc::isHostileTo(Unit * pTarget) { if (pTarget == nullptr) return false; if (GetType() == NPC_GATE && (GetZoneID() == ZONE_BATTLE || GetZoneID() == ZONE_BATTLE2 || GetZoneID() == ZONE_BATTLE3 || GetZoneID() == ZONE_BATTLE4 || GetZoneID() == ZONE_BATTLE5 || GetZoneID() == ZONE_BATTLE6) && GetNation() != pTarget->GetNation()) return true; if (GetType() == NPC_BDW_MONUMENT) return true; #if defined(GAMESERVER) if (!g_pMain->m_byBattleSiegeWarOpen && GetZoneID() == ZONE_DELOS) return false; #endif // Only players can attack these targets. if (pTarget->isPlayer()) { // Scarecrows are NPCs that the client allows us to attack // however, since they're not a monster, and all NPCs in neutral zones // are friendly, we need to override to ensure we can attack them server-side. #if defined(GAMESERVER) if (GetType() == NPC_SCARECROW || g_pMain->m_bAttackBifrostMonument) return true; #else if (GetType() == NPC_SCARECROW) return true; #endif } #if defined(GAMESERVER) if (g_pMain->m_byBattleSiegeWarOpen && !TO_USER(pTarget)->isInClan() && GetZoneID() == ZONE_DELOS) return false; CKnights * pKnights ; _KNIGHTS_SIEGE_WARFARE * pSiegeWars ; if (g_pMain->m_byBattleSiegeWarOpen && GetZoneID() == ZONE_DELOS && TO_USER(pTarget)->GetClanID() != 0) { pKnights = g_pMain->GetClanPtr(TO_USER(pTarget)->GetClanID()); pSiegeWars = g_pMain->GetSiegeMasterKnightsPtr(1); } if (g_pMain->m_byBattleSiegeWarOpen && GetZoneID() == ZONE_DELOS) return true; #endif // A nation of 0 indicates friendliness to all if (GetNation() == Nation::ALL // Also allow for cases when all NPCs in this zone are inherently friendly. || (!isMonster() && GetMap()->areNPCsFriendly())) return false; // A nation of 3 indicates hostility to all (or friendliness to none) if (GetNation() == Nation::NONE) return true; // An NPC cannot attack a unit of the same nation return (GetNation() != pTarget->GetNation()); } /** * @brief Determines if a player is hostile to a unit. * Non-hostile units cannot be attacked. * * @param pTarget Target unit * * @return true if hostile to, false if not. */ bool CUser::isHostileTo(Unit * pTarget) { if (pTarget == nullptr) return false; // For non-player hostility checks, refer to the appropriate override. if (!pTarget->isPlayer()) return pTarget->isHostileTo(this); // Players can attack other players in the arena. if (isInArena() && TO_USER(pTarget)->isInArena()) return true; // Players can attack other players in the safety area. if (isInSafetyArea() || (pTarget->isPlayer() && TO_USER(pTarget)->isInSafetyArea())) return false; // Players can attack opposing nation players when they're in PVP zones. if (GetNation() != pTarget->GetNation() && isInPVPZone()) return true; if (isInTempleEventZone() && (pTarget->GetNation() != GetNation() || !isSameEventRoom(pTarget))) return true; #if GAMESERVER if (g_pMain->m_byBattleSiegeWarOpen && GetZoneID() == ZONE_DELOS) { CUser *pUser = g_pMain->GetUserPtr(GetName(), TYPE_CHARACTER); CUser *pTargetUser = g_pMain->GetUserPtr(TO_USER(pTarget)->m_strUserID, TYPE_CHARACTER); if(pUser == nullptr || pTargetUser == nullptr) return false; if (pUser->GetClanID() > 0 && pTargetUser->GetClanID() > 0){ return g_pMain->CastleSiegeWarAttack(pUser, pTargetUser); } return false; } #endif // Players cannot attack other players in any other circumstance. return false; } /** * @brief Determine if this user is in an arena area. * * @return true if in arena, false if not. */ bool CUser::isInArena() { /* All of this needs to be handled more generically (i.e. bounds loaded from the database, or their existing SMD method). */ // If we're in the Arena zone, assume combat is acceptable everywhere. // NOTE: This is why we need generic bounds checks, to ensure even attacks in the Arena zone are in one of the 4 arena locations. if (GetZoneID() == ZONE_ARENA) return true; // The only other arena is located in Moradon. If we're not in Moradon, then it's not an Arena. return false; } /** * @brief Determine if this user is in a normal PVP zone. * That is, they're in an PK zone that allows combat * against the opposite nation. * * @return true if in PVP zone, false if not. */ bool CUser::isInPVPZone() { if (GetMap()->canAttackOtherNation()) return true; #if defined(GAMESERVER) // Native/home zones are classed as PVP zones during invasions. if ((GetZoneID() == KARUS && g_pMain->m_byKarusOpenFlag) || (GetZoneID() == ELMORAD && g_pMain->m_byElmoradOpenFlag)) return true; #endif return false; } /** * @brief Determine if this user is in an safety area. * * @return true if in safety area, false if not. */ bool CUser::isInSafetyArea() { switch (GetZoneID()) { case ZONE_BIFROST: if (GetNation() == ELMORAD) return ((GetX() < 124.0f && GetX() > 56.0f) && ((GetZ() < 840.0f && GetZ() > 700.0f))); else return ((GetX() < 270.0f && GetX() > 190.0f) && ((GetZ() < 970.0f && GetZ() > 870.0f))); case ZONE_ARENA: return ((GetX() < 148.0f && GetX() > 106.0f) && ((GetZ() < 149.0f && GetZ() > 50.0f)) || (GetX() < 169.0f && GetX() > 86.0f) && ((GetZ() < 127.0f && GetZ() > 100.0f)) || (GetX() < 150.0f && GetX() > 102.0f) && ((GetZ() < 144.0f && GetZ() > 82.0f)) || (GetX() < 157.0f && GetX() > 99.0f) && ((GetZ() < 139.0f && GetZ() > 88.0f))); case ZONE_ELMORAD: if (GetNation() == ELMORAD) return ((GetX() < 244.0f && GetX() > 176.0f) && ((GetZ() < 1880.0f && GetZ() > 1820.0f))); case ZONE_KARUS: if (GetNation() == KARUS) return ((GetX() < 1876.0f && GetX() > 1820.0f) && ((GetZ() < 212.0f && GetZ() > 136.0f))); case ZONE_BATTLE: if (GetNation() == KARUS) return ((GetX() < 125.0f && GetX() > 98.0f) && ((GetZ() < 780.0f && GetZ() > 755.0f))); else if (GetNation() == ELMORAD) return ((GetX() < 831.0f && GetX() > 805.0f) && ((GetZ() < 110.0f && GetZ() > 85.0f))); case ZONE_BATTLE2: if (GetNation() == ELMORAD) return ((GetX() < 977.0f && GetX() > 942.0f) && ((GetZ() < 904.0f && GetZ() > 863.0f))); else if (GetNation() == KARUS) return ((GetX() < 80.0f && GetX() > 46.0f) && ((GetZ() < 174.0f && GetZ() > 142.0f))); case ZONE_BATTLE4: if (GetNation() == KARUS) return ((GetX() < 300.0f && GetX() > 106.0f) && ((GetZ() < 251.0f && GetZ() > 199.0f))); else if (GetNation() == ELMORAD) return ((GetX() < 844.0f && GetX() > 741.0f) && ((GetZ() < 821.0f && GetZ() > 730.0f))); case ZONE_DELOS: return ((GetX() > 411.0f && GetX() < 597.0f) && ((GetZ() < 296.0f && GetZ() > 113.0f))); } return false; } bool Unit::isSameEventRoom(Unit *pTarget) { if (pTarget == nullptr) return false; if (GetEventRoom() == pTarget->GetEventRoom()) return true; return false; }
[ "staticforcepowerdev@gmail.com" ]
staticforcepowerdev@gmail.com
06d28ea7b4c1098b11cb2eb2df9767c8cded4b7d
19d1c24484c1771c0be7cdef45f3342a6889a4cb
/nnforge/network_trainer_sgd.cpp
4671d206437b827c1246bb7c7e5b72c4e6403aaf
[ "Apache-2.0" ]
permissive
dreadlord1984/nnForge
06bc261fa9d9d58c45aafdbf3f7026990809c288
b4c795ab6ddf3ce9dfe8a628dd1ad33dd19dee9b
refs/heads/master
2021-01-18T13:40:21.646717
2014-08-06T18:23:53
2014-08-06T18:23:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,506
cpp
/* * Copyright 2011-2014 Maxim Milakov * * 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 "network_trainer_sgd.h" #include <boost/format.hpp> #include <numeric> #include <limits> #include "neural_network_exception.h" namespace nnforge { network_trainer_sgd::network_trainer_sgd( network_schema_smart_ptr schema, network_updater_smart_ptr updater) : network_trainer(schema) , updater(updater) { } network_trainer_sgd::~network_trainer_sgd() { } void network_trainer_sgd::train_step( supervised_data_reader& reader, training_task_state& task) { boost::chrono::steady_clock::time_point start = boost::chrono::high_resolution_clock::now(); std::pair<network_data_smart_ptr, std::string> lr_and_comment = prepare_learning_rates(task.get_current_epoch()); task.comments.push_back(lr_and_comment.second); testing_result_smart_ptr train_result = updater->update( reader, lr_and_comment.first, task.data, batch_size, weight_decay, momentum); boost::chrono::duration<float> sec = (boost::chrono::high_resolution_clock::now() - start); float flops = updater->get_flops_for_single_entry(); train_result->time_to_complete_seconds = sec.count(); train_result->flops = static_cast<float>(train_result->get_entry_count()) * flops; task.history.push_back(train_result); } std::pair<network_data_smart_ptr, std::string> network_trainer_sgd::prepare_learning_rates(unsigned int epoch) { float learning_rate = get_global_learning_rate(static_cast<unsigned int>(epoch)); network_data_smart_ptr lr(new network_data(*schema)); lr->fill(learning_rate); std::string comment = (boost::format("LR %|1$.5e|") % learning_rate).str(); return std::make_pair(lr, comment); } void network_trainer_sgd::initialize_train(supervised_data_reader& reader) { updater->set_input_configuration_specific(reader.get_input_configuration()); } }
[ "maxim.milakov@gmail.com" ]
maxim.milakov@gmail.com
289c1f2ff3f6911d758c6c39ad0b836400c70e00
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmbs12/pmsb13-data-20120615/trunk/sandbox/arsenew/apps/msplazer/stellar_routines.h
06a3e04c4cd8e64ccbde67c5af8329ff7bdf096a
[ "MIT", "BSD-3-Clause" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
22,103
h
// ========================================================================== // msplazer // ========================================================================== // Copyright (c) 2011, Kathrin Trappe, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Kathrin Trappe <kathrin.trappe@fu-berlin.de> // ========================================================================== #ifndef SANDBOX_KTRAPPE_APPS_MSPLAZER_STELLAR_ROUTINES_H_ #define SANDBOX_KTRAPPE_APPS_MSPLAZER_STELLAR_ROUTINES_H_ #define BREAKPOINT_DEBUG #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/stream.h> #include "../../../../core/apps/stellar/stellar.h" using namespace seqan; //Compare StellarMatches using in order of priority (1) read begin, (2) read end position, (3) chromosome begin, (4) chromosome end pos template< typename TSequence, typename TId> struct CompareStellarMatches{ bool operator() (StellarMatch<TSequence, TId> const & match1, StellarMatch<TSequence, TId> const & match2) const { if(match1.begin2 != match2.begin2) return match1.begin2 < match2.begin2; if(match1.end2 != match2.end2) return match1.end2 < match2.end2; if(match1.begin1 != match2.begin1) return match1.begin1 < match2.begin1; //if(match1.end1 != match2.end1) return match1.end1 < match2.end1; } }; /////////////////////////////////////////////////////////////////////////////// //Wrapper functions to get Stellar matches template <typename TSequence, typename TMatches> void _getStellarMatches(StringSet<TSequence> & queries, StringSet<TSequence> & databases, StringSet<CharString> & databaseIDs, StellarOptions & stellarOptions, TMatches & stellarMatches){ //Finder typedef Finder<TSequence, Swift<SwiftLocal> > TFinder; // typedef Finder<TSequence, Swift<SwiftLocal> > TFinder; //Using Stellars structure for queries typedef Index<StringSet<TSequence, Dependent<> >, IndexQGram<SimpleShape, OpenAddressing> > TQGramIndex; //typedef Index<StringSet<TSequence, Dependent<> >, IndexQGram<SimpleShape> > TQGramIndex; TQGramIndex qgramIndex(queries); //stellarOptions.qGram = 4; resize(indexShape(qgramIndex), stellarOptions.qGram); // cargo(qgramIndex).abundanceCut = stellarOptions.qgramAbundanceCut; //pattern /* //Using FragmenStore typedef Index<StringSet<TSequence, Owner<ConcatDirect<> > >, IndexQGram<SimpleShape, OpenAddressing> > TQGramIndexFrSt; TQGramIndexFrSt qgramIndexFrSt(fragments.readSeqStore); stellarOptions.qGram = 4; resize(indexShape(qgramIndexFrSt), stellarOptions.qGram); typedef Pattern<TQGramIndexFrSt, Swift<SwiftLocal> > TPatternFrSt; TPatternFrSt swiftPatternFrSt(qgramIndexFrSt); std::cout << "FrStPattern: " << value(host(needle(swiftPatternFrSt)),0) << std::endl; // Construct index std::cout << "Constructing index..." << std::endl; indexRequire(qgramIndexFrSt, QGramSADir()); std::cout << std::endl; */ //Using Stellars structure for queries typedef Pattern<TQGramIndex, Swift<SwiftLocal> > TPattern; TPattern swiftPattern(qgramIndex); //std::cout << "Pattern: " << value(host(needle(swiftPattern)),0) << std::endl; // Construct index std::cout << "Constructing index..." << std::endl; indexRequire(qgramIndex, QGramSADir()); std::cout << std::endl; //Call Stellar for each database sequence double start = sysTime(); for(unsigned i = 0; i < length(databases); ++i){ //Using long stellar() to calculate stellarMatches on + strand if(stellarOptions.forward){ TFinder swiftFinder(databases[i], stellarOptions.minRepeatLength, stellarOptions.maxRepeatPeriod); stellar(swiftFinder, swiftPattern, stellarOptions.epsilon, stellarOptions.minLength, stellarOptions.xDrop, stellarOptions.disableThresh, stellarOptions.compactThresh, stellarOptions.numMatches, stellarOptions.verbose, databaseIDs[i], true, stellarMatches, AllLocal()); } // - strand if(stellarOptions.reverse){ reverseComplement(databases[i]); TFinder revSwiftFinder(databases[i], stellarOptions.minRepeatLength, stellarOptions.maxRepeatPeriod); stellar(revSwiftFinder, swiftPattern, stellarOptions.epsilon, stellarOptions.minLength, stellarOptions.xDrop, stellarOptions.disableThresh, stellarOptions.compactThresh, stellarOptions.numMatches, stellarOptions.verbose, databaseIDs[i], false, stellarMatches, AllLocal()); reverseComplement(databases[i]); } } std::cout << "TIME stellar " << (sysTime() - start) << "s" << std::endl; } //Alignment Score using _analyzeAlignment(row0, row1, alignLen, matchNumber) from stellar_output.h //matchNumber and alignLen reset within _analyzeAlignment template < typename TSequence, typename TId, typename TValue > void _getScore(StellarMatch<TSequence, TId> & match, TValue & alignLen, TValue & matchNumber, TValue & alignDistance){ if(!match.orientation) reverseComplement(infix(source(match.row1),match.begin1,match.end1)); _analyzeAlignment(match.row1, match.row2, alignLen, matchNumber); alignDistance = alignLen - matchNumber; if(!match.orientation) reverseComplement(infix(source(match.row1),match.begin1,match.end1)); } //Transforms coordinates of a stellar match onto the other strand template <typename TMatch> void _transformCoordinates(TMatch & match){ //setClippedBeginPosition(match.row1, length(source(match.row1)) - match.end1); //setClippedEndPosition(match.row1, length(source(match.row1)) - match.begin1); //std::cerr << "Chr length: " << length(source(match.row1)) << std::endl; match.row1.clipped_source_begin = length(source(match.row1)) - match.end1; match.row1.clipped_source_end = length(source(match.row1)) - match.begin1; match.begin1 = clippedBeginPosition(match.row1); match.end1 = clippedEndPosition(match.row1); } //Computes distance score for each match and stores is in distanceScores //Note: Matches are being sorted within this function //Note also: StellarMatches of the reverse Strand are being modified, in the sense that they correspond to the right positions within the forward strand template < typename TScoreAlloc, typename TSequence, typename TId> void _getMatchDistanceScore( StringSet <QueryMatches <StellarMatch <TSequence, TId> > > & stellarMatches, String<TScoreAlloc> & distanceScores, bool internalStellarCall){ typedef StellarMatch<TSequence, TId> TMatch; typedef typename Size<typename TMatch::TAlign>::Type TSize; typedef typename Iterator<String<TMatch> >::Type TIterator; //Calculating distance score of each match using Stellars _analayzeAlignment function int matchNumber, alignLen, alignDistance; for(TSize i = 0; i < length(stellarMatches); ++i){ TScoreAlloc & matchDistanceScores = distanceScores[i]; resize(matchDistanceScores, length(stellarMatches[i].matches)); //Sorting matches according to query begin position (begin2) std::sort(begin(stellarMatches[i].matches), end(stellarMatches[i].matches), CompareStellarMatches<TSequence, TId>()); TIterator itStellarMatches = begin(stellarMatches[i].matches); TIterator itEndStellarMatches = end(stellarMatches[i].matches); TSize matchIndex = 0; for(;itStellarMatches < itEndStellarMatches;goNext(itStellarMatches)){ if(internalStellarCall && !(*itStellarMatches).orientation){ //coordinate transformation (setClippedPosition does not work here) _transformCoordinates(*itStellarMatches); } //Compute edit distance score _getScore(*itStellarMatches, alignLen, matchNumber, alignDistance); matchDistanceScores[matchIndex] = alignDistance; ++matchIndex; } } } template <typename TMatch, typename TPos> void _trimMatchBegin(TMatch & stMatch, TPos const & splitPos, TPos const & projSplitPos){ setClippedBeginPosition(stMatch.row2, projSplitPos); if(stMatch.orientation) setClippedBeginPosition(stMatch.row1, splitPos); else{ TPos diff = splitPos - clippedBeginPosition(stMatch.row1); _transformCoordinates(stMatch); setClippedBeginPosition(stMatch.row1, stMatch.begin1 + diff); stMatch.begin1 = clippedBeginPosition(stMatch.row1); _transformCoordinates(stMatch); } stMatch.begin1 = clippedBeginPosition(stMatch.row1); stMatch.begin2 = clippedBeginPosition(stMatch.row2); } template <typename TMatch, typename TPos> void _trimMatchEnd(TMatch & stMatch, TPos & splitPos, TPos & projSplitPos){ setClippedEndPosition(stMatch.row2, projSplitPos); if(stMatch.orientation) setClippedEndPosition(stMatch.row1, splitPos); else{ TPos diff = clippedEndPosition(stMatch.row1) - splitPos; _transformCoordinates(stMatch); setClippedEndPosition(stMatch.row1, stMatch.end1 - diff); stMatch.end1 = clippedEndPosition(stMatch.row1); _transformCoordinates(stMatch); } stMatch.end1 = clippedEndPosition(stMatch.row1); stMatch.end2 = clippedEndPosition(stMatch.row2); } //TODO Restructure template <typename TSequence, typename TId, typename TBreakpoint> void _getStellarIndel(StellarMatch<TSequence, TId> & match, String<TBreakpoint> & globalStellarIndels, TId const & queryId, TSequence & query){ //std::cerr << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl; typedef typename Infix<TSequence>::Type TInfix; typedef typename TBreakpoint::TPos TPos; //typedef typename StellarMatch<TSequence, TId>::TRow TRow; typedef Align<TInfix> TAlign; typedef typename Row<TAlign>::Type TRow; bool gapOpen = true; TPos startSeqPos, endSeqPos, indelStart, pos; indelStart = 0; //Match refinement int matchNumber, alignLen, score; Score<int> scoreType(1,-2,-2,-5); /* std::cerr << "Trying to build infices: " << length(match.row1) << " begin1: " << match.begin1 << " clippedBegin: " << clippedBeginPosition(match.row1) << " end1: " << match.end1 << " clippedEnd: " << clippedEndPosition(match.row1) << std::endl; */ TInfix seq1, seq2; seq1 = infix(source(match.row1), match.begin1, match.end1); seq2 = infix(query, match.begin2, match.end2); if(!match.orientation) reverseComplement(seq1); TAlign align; resize(rows(align), 2); setSource(row(align, 0), seq1); setSource(row(align, 1), seq2); StringSet<TInfix> seqs; appendValue(seqs, seq1); appendValue(seqs, seq2); _analyzeAlignment(match.row1, match.row2, alignLen, matchNumber); score = alignLen - matchNumber; //Refine match using banded global alignment with affine gap score if(score > 0){ globalAlignment(align, seqs, scoreType, -score, score, BandedGotoh()); //std::cout << align << std::endl; } TRow & rowDB = row(align, 0); TRow & rowRead = row(align, 1); //Insertions for(pos = 0; pos < std::max(endPosition(rowDB), endPosition(rowRead)); ++pos){ //Look for gap in rowDB if(isGap(rowDB,pos)){ //Keep track if it is the first gap, i.e. the beginning of the insertion if(gapOpen){ gapOpen = false; indelStart = pos; //std::cerr << "indelStart: " << indelStart << " gapopen " << gapOpen << std::endl; } }else{ //If an insertion just closed, i.e. !gapOpen, save the insertion in a breakpoint if(!gapOpen){ //Get breakpoint position (note, in case of an insertion start=end) startSeqPos = toSourcePosition(rowDB, indelStart) + match.begin1; TPos readStartPos = toSourcePosition(rowRead, indelStart) + match.begin2; TPos readEndPos = toSourcePosition(rowRead, pos) + match.begin2; TBreakpoint bp(match.id, match.id, match.orientation, match.orientation, startSeqPos, startSeqPos, readStartPos, readEndPos, queryId); //get insertion sequence TPos bPos = toSourcePosition(rowRead, indelStart); TPos ePos = toSourcePosition(rowRead, pos); if(bPos > ePos) std::swap(bPos, ePos); TInfix inSeq = infix(query, bPos, ePos); setSVType(bp, static_cast<TId>("insertion")); setInsertionSeq(bp, inSeq); //_insertBreakpoint(globalStellarIndels, bp); //std::cerr << bp << std::endl; //reset gapOpen gapOpen = true; } } } //Get insertion at the end of the match if(!gapOpen){ //Get breakpoint position (note, in case of an insertion start=end) startSeqPos = toSourcePosition(rowDB, indelStart) + match.begin1; TPos readStartPos = toSourcePosition(rowRead, indelStart) + match.begin2; TPos readEndPos = toSourcePosition(rowRead, pos) + match.begin2; TBreakpoint bp(match.id, match.id, match.orientation, match.orientation, startSeqPos, startSeqPos, readStartPos, readEndPos, queryId); //get insertion sequence TPos bPos = toSourcePosition(rowRead, indelStart) + match.begin2; TPos ePos = toSourcePosition(rowRead, pos) + match.begin2; if(bPos > ePos) std::swap(bPos, ePos); TInfix inSeq = infix(query, bPos, ePos); setSVType(bp, static_cast<TId>("insertion")); setInsertionSeq(bp, inSeq); _insertBreakpoint(globalStellarIndels, bp); //reset gapOpen gapOpen = true; } //Deletions for(pos = 0; pos < std::max(endPosition(rowDB), endPosition(rowRead)); ++pos){ //Look for gap in rowRead if(isGap(rowRead,pos)){ if(gapOpen){ gapOpen = false; indelStart = pos; } }else{ if(!gapOpen){ //Get breakpoint positions startSeqPos = toSourcePosition(rowDB, indelStart) + match.begin1; endSeqPos = toSourcePosition(rowDB, pos) + match.begin1; if(startSeqPos > endSeqPos) std::swap(startSeqPos, endSeqPos); TPos readStartPos = toSourcePosition(rowRead, indelStart) + match.begin2; TPos readEndPos = toSourcePosition(rowRead, pos) + match.begin2; TBreakpoint bp(match.id, match.id, match.orientation, match.orientation, startSeqPos, endSeqPos, readStartPos, readEndPos, queryId); setSVType(bp, static_cast<TId>("deletion")); _insertBreakpoint(globalStellarIndels, bp); gapOpen = true; } } } //Get deletion at the end of the match if(!gapOpen){ startSeqPos = toSourcePosition(rowDB, indelStart) + match.begin1; endSeqPos = toSourcePosition(rowDB, pos) + match.begin1; if(startSeqPos > endSeqPos) std::swap(startSeqPos, endSeqPos); TPos readStartPos = toSourcePosition(rowRead, indelStart) + match.begin2; TPos readEndPos = toSourcePosition(rowRead, pos) + match.begin2; TBreakpoint bp(match.id, match.id, match.orientation, match.orientation, startSeqPos, endSeqPos, readStartPos, readEndPos, queryId); setSVType(bp, static_cast<TId>("deletion")); _insertBreakpoint(globalStellarIndels, bp); gapOpen = true; } if(!match.orientation) reverseComplement(seq1); } template<typename TId> bool _checkUniqueId(TId const & sId, TId const & id, StringSet<TId> & ids, StringSet<TId> & sQueryIds){ bool unique = true; for(unsigned j = 0; j < length(sQueryIds); ++j){ if(sId == sQueryIds[j]){ std::cout << "Found nonunique sequence ID!" << std::endl; std::cout << ids[j] << std::endl; std::cout << id << std::endl; std::cout << "###########################" << std::endl; unique = false; } } return unique; } /////////////////////////////////////////////////////////////////////////////// //Functions taken from Stellar code for writing Stellar parameters and read files /////////////////////////////////////////////////////////////////////////////// // Imports sequences from a file, // stores them in the StringSet seqs and their identifiers in the StringSet ids template<typename TSequence, typename TId> inline bool _importSequences(CharString const & fileName, CharString const & name, StringSet<TSequence> & seqs, StringSet<TId> & ids) { MultiSeqFile multiSeqFile; if (!open(multiSeqFile.concat, toCString(fileName), OPEN_RDONLY)) { std::cerr << "Failed to open " << name << " file." << std::endl; return false; } StringSet<TId> sQueryIds; AutoSeqFormat format; guessFormat(multiSeqFile.concat, format); split(multiSeqFile, format); unsigned seqCount = length(multiSeqFile); reserve(seqs, seqCount, Exact()); reserve(ids, seqCount, Exact()); TSequence seq; TId id; TId sId; unsigned counter = 0; for(unsigned i = 0; i < seqCount; ++i) { assignSeq(seq, multiSeqFile[i], format); assignSeqId(id, multiSeqFile[i], format); appendValue(seqs, seq, Generous()); appendValue(ids, id, Generous()); _getShortId(id, sId); if(!_checkUniqueId(sId, id, ids, sQueryIds)) ++counter; appendValue(sQueryIds, sId); } std::cout << "Loaded " << seqCount << " " << name << " sequence" << ((seqCount>1)?"s.":".") << std::endl; if(counter > 0) std::cout << "Found " << counter << " nonunique sequence IDs" << std::endl; return true; } /////////////////////////////////////////////////////////////////////////////// // Calculates parameters from parameters in options object and writes them to std::cout void _writeCalculatedParams(StellarOptions & options) { //IOREV _notio_ int errMinLen = (int) floor(options.epsilon * options.minLength); int n = (int) ceil((errMinLen + 1) / options.epsilon); int errN = (int) floor(options.epsilon * n); unsigned smin = (unsigned) _min(ceil((double)(options.minLength-errMinLen)/(errMinLen+1)), ceil((double)(n-errN)/(errN+1))); std::cout << "Calculated parameters:" << std::endl; if (options.qGram == (unsigned)-1) { options.qGram = (unsigned)_min(smin, 32u); std::cout << " k-mer length: " << options.qGram << std::endl; } int threshold = (int) _max(1, (int) _min((n + 1) - options.qGram * (errN + 1), (options.minLength + 1) - options.qGram * (errMinLen + 1))); int overlap = (int) floor((2 * threshold + options.qGram - 3) / (1 / options.epsilon - options.qGram)); int distanceCut = (threshold - 1) + options.qGram * overlap + options.qGram; int logDelta = _max(4, (int) ceil(log((double)overlap + 1) / log(2.0))); int delta = 1 << logDelta; std::cout << " s^min : " << smin << std::endl; std::cout << " threshold : " << threshold << std::endl; std::cout << " distance cut: " << distanceCut << std::endl; std::cout << " delta : " << delta << std::endl; std::cout << " overlap : " << overlap << std::endl; std::cout << std::endl; } /////////////////////////////////////////////////////////////////////////////// // Writes user specified parameters from options object to std::cout template<typename TOptions> void _writeSpecifiedParams(TOptions & options) { //IOREV _notio_ // Output user specified parameters std::cout << "User specified parameters:" << std::endl; std::cout << " minimal match length : " << options.minLength << std::endl; std::cout << " maximal error rate (epsilon) : " << options.epsilon << std::endl; std::cout << " maximal x-drop : " << options.xDrop << std::endl; if (options.qGram != (unsigned)-1) std::cout << " k-mer (q-gram) length : " << options.qGram << std::endl; std::cout << " search forward strand : " << ((options.forward)?"yes":"no") << std::endl; std::cout << " search reverse complement : " << ((options.reverse)?"yes":"no") << std::endl; std::cout << std::endl; std::cout << " verification strategy : " << options.fastOption << std::endl; if (options.disableThresh != (unsigned)-1) { std::cout << " disable queries with more than : " << options.disableThresh << " matches" << std::endl; } std::cout << " maximal number of matches : " << options.numMatches << std::endl; std::cout << " duplicate removal every : " << options.compactThresh << std::endl; if (options.maxRepeatPeriod != 1 || options.minRepeatLength != 1000) { std::cout << " max low complexity repeat period : " << options.maxRepeatPeriod << std::endl; std::cout << " min low complexity repeat length : " << options.minRepeatLength << std::endl; } if (options.qgramAbundanceCut != 1) { std::cout << " q-gram abundance cut ratio : " << options.qgramAbundanceCut << std::endl; } std::cout << std::endl; } /////////////////////////////////////////////////////////////////////////////// // Writes file name from options object to std::cout template<typename TOptions> void _writeFileNames(TOptions & options) { //IOREV _notio_ std::cout << "Database file : " << options.databaseFile << std::endl; std::cout << "Query file : " << options.queryFile << std::endl; std::cout << "Output file : " << options.outputFile << std::endl; std::cout << "Output format : " << options.outputFormat << std::endl; if (options.disableThresh != (unsigned)-1) { std::cout << "Disabled queries: " << options.disabledQueriesFile << std::endl; } std::cout << std::endl; } #endif // #ifndef SANDBOX_MY_SANDBOX_APPS_MSPLAZER_STELLAR_ROUTINES_H_
[ "mail@bkahlert.com" ]
mail@bkahlert.com
dbba372e283d747c9606d32fde09a178c1be4ba1
49043e84564baa99cf10e5a9cdec85021b1760e8
/include/wifi-telemetry/wpa/wpa_event_disconnected.hpp
f9c3710d8a259efe99a225eaf9dd91598ace53da
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
microsoft/wifi-telemetry
235b77344528e5f4f7c61dd02e9c54a471918bb8
52cf172797d480b0a92696448756e8a3125e8a2f
refs/heads/main
2023-05-15T11:25:57.744257
2021-06-11T18:33:00
2021-06-11T18:33:00
368,251,675
6
2
null
null
null
null
UTF-8
C++
false
false
551
hpp
#ifndef __WPA_EVENT_DISCONNECTED_HPP__ #define __WPA_EVENT_DISCONNECTED_HPP__ #include <array> #include <cinttypes> #include "wifi-telemetry/wifi/wifi_80211.hpp" #include "wifi-telemetry/wpa/wpa_event.hpp" struct WpaEventDisconnected : public WpaEvent { WpaEventDisconnected(const wifi_80211_mac& bssid_, WifiDeauthenticationReasonCode reason_code_, bool locally_generated); const wifi_80211_mac bssid; const WifiDeauthenticationReasonCode reason_code; bool locally_generated = false; }; #endif // __WPA_EVENT_DISCONNECTED_HPP__
[ "anbeltra@microsoft.com" ]
anbeltra@microsoft.com
cc8129933518461bc8b6d076477d82a7e4a696e5
ddbdbc0ce681558fac8d0fad3a5b346bdb8db561
/libParameter/RegardsConfigParam.h
27b5623373b3a797d53dcb8c40a864bec9094eda
[]
no_license
Trisoil/Regards
9488f4ee31784490e06a24a136a76a45a09910f9
3eda6669f4d1a2043f631f747a6c36fa644c590d
refs/heads/master
2020-05-07T11:57:03.681785
2019-04-09T16:41:14
2019-04-09T16:41:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
h
#pragma once #include "ConfigParam.h" #include <iostream> #include <fstream> using namespace rapidxml; class CRegardsConfigParam : public CConfigParam { public: CRegardsConfigParam(); ~CRegardsConfigParam(); int GetPreviewLibrary(); void SetPreviewLibrary(const int &numLib); bool GetDatabaseInMemory(); void SetDatabaseInMemory(const int &value); float GetIconSizeRatio(); void SetIconSizeRatio(const float &ratio); int GetVideoLibrary(); void SetVideoLibrary(const int &numLib); int GetEffectLibrary(); void SetEffectLibrary(const int &numLib); int GetOpenCLPlatformIndex(); void SetOpenCLPlatformIndex(const int &numIndex); int GetFaceDetectionPictureSize(); void SetFaceDetectionPictureSize(const int &numIndex); wxString GetOpenCLPlatformName(); void SetOpenCLPlatformName(const wxString &platformName); int GetOpenCLLoadFromBinaries(); void SetOpenCLLoadFromBinaries(const int &loadFromBinaries); int GetEffect(); void SetEffect(const int &numEffect); wxString GetUrlServer(); int GetNbGpsIterationByMinute(); int GetDiaporamaTime(); void SetDiaporamaTime(const int &diaporamaTime); int GetDiaporamaTransitionEffect(); void SetDiaporamaTransitionEffect(const int &diaporamaEffect); int GetDiaporamaFullscreen(); void SetDiaporamaFullscreen(const int &diaporamaFullscreen); int GetThumbnailQuality(); void SetThumbnailQuality(const int &quality); int GetThumbnailIconeCache(); void SetThumbnailIconeCache(const int &iconeCache); int GetThumbnailProcess(); void SetThumbnailProcess(const int &nbProcess); int GetFaceProcess(); void SetFaceProcess(const int &nbProcess); int GetExifProcess(); void SetExifProcess(const int &nbProcess); int GetNumLanguage(); void SetNumLanguage(const int &numLanguage); protected: void InitVideoToolbar(); void InitBitmapToolbar(); void InitClickToolbar(); void InitToolbar(); void LoadParameter(); void SaveParameter(); void SetIconParameter(xml_node<>* sectionPosition); void GetIconParameter(xml_node<>* position_node); void SetImageLibrary(xml_node<>* sectionPosition); void GetImageLibrary(xml_node<> * position_node); void SetDatabaseParameter(xml_node<>* sectionPosition); void GetDatabaseParameter(xml_node<> * position_node); void SetEffectLibrary(xml_node<>* sectionPosition); void GetEffectLibrary(xml_node<> * position_node); void SetVideoLibrary(xml_node<>* sectionPosition); void GetVideoLibrary(xml_node<> * position_node); void SetDiaporamaParameter(xml_node<>* sectionPosition); void GetDiaporamaParameter(xml_node<> * position_node); void SetGeolocalisationServer(xml_node<>* sectionPosition); void GetGeolocalisationServer(xml_node<> * position_node); void SetThumbnail(xml_node<>* sectionPosition); void GetThumbnail(xml_node<> * position_node); int pictureSize; int numLibPreview; int numLibEffect; int numLibVideo; int numEffect; int openCLNumIndex; int numLanguage; //Diaporama int diaporamaTime; int diaporamaEffect; int diaporamaFullscreen; int thumbnailQuality; int thumbnailIconeCache; float iconSizeRatio; wxString openCLPlatformName; wxString geolocUrl; int dataInMemory; int nbProcessThumbnail; int nbProcessExif; int nbProcessFace; int nbGpsFileByMinute; int loadFromBinaries = 0; };
[ "jfiguinha@hotmail.fr" ]
jfiguinha@hotmail.fr
5d6e1ef41162b3d1759bf117ac2d734e1bd4764b
e30ab85bde0c8887f4fb519337da95ad4393fe8d
/NewUIHelpWindow.h
6ec122dafe6f904e974dc0bca949ab6f0be7f6ce
[]
no_license
rodrigolmonteiro/muonline-client-sources
a80a105c2d278cee482b504b167c393d3b05322e
be7f279f0d17bb8ca87455e434edd30b60e5a5fe
refs/heads/master
2023-06-29T09:45:22.154516
2021-08-04T17:10:15
2021-08-04T17:10:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
// NewUIHelpWindow.h: interface for the CNewUIHelpWindow class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_NEWUIHELPWINDOW_H__9A918DE0_7707_456C_9E5B_89503F1936D1__INCLUDED_) #define AFX_NEWUIHELPWINDOW_H__9A918DE0_7707_456C_9E5B_89503F1936D1__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "NewUIManager.h" namespace SEASON3B { class CNewUIHelpWindow : public CNewUIObj { public: CNewUIHelpWindow(); virtual ~CNewUIHelpWindow(); bool Create(CNewUIManager* pNewUIMng, int x, int y); void Release(); void SetPos(int x, int y); bool UpdateMouseEvent(); bool UpdateKeyEvent(); bool Update(); bool Render(); float GetLayerDepth(); //. 7.1f float GetKeyEventOrder(); // 10.f; void OpenningProcess(); void ClosingProcess(); void AutoUpdateIndex(); private: CNewUIManager* m_pNewUIMng; POINT m_Pos; int m_iIndex; }; } #endif // !defined(AFX_NEWUIHELPWINDOW_H__9A918DE0_7707_456C_9E5B_89503F1936D1__INCLUDED_)
[ "sasha.broslavskiy@gmail.com" ]
sasha.broslavskiy@gmail.com
e404d0d7a0de5b9b7ea847238700e1888011264d
4f6b26626dc639aea3457b1f7245d3baac6ec750
/Bibliotecas/Ultrasonic/Ultrasonic.h
fcc00c28fd99e868f0e08c5940e455269dad2f68
[]
no_license
brunoamenegotto/Sistemas-Embarcados
828b16463d4789f15693e39c2614b7f1cb89fd4e
ebac0c4b9cde99e8d165b4a46e62fa6d2b2fca72
refs/heads/master
2022-12-02T08:28:30.421724
2020-07-22T17:35:19
2020-07-22T17:35:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
h
/* * Ultrasonic.h - Library for HC-SR04 Ultrasonic Sensing Module. * * With ideas from: * Created by ITead studio. Alex, Apr 20, 2010. * iteadstudio.com * * SVN Keywords * ---------------------------------- * $Author: cnobile $ * $Date: 2011-12-07 21:49:14 -0500 (Wed, 07 Dec 2011) $ * $Revision: 38 $ * ---------------------------------- * * Thank you to Rowan Simms for pointing out the change in header name with * Arduino version 1.0 and up. * */ #ifndef ULTRASONIC_H #define ULTRASONIC_H #include <stddef.h> #if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif // Undefine COMPILE_STD_DEV if you don't want Standard Deviation. #define COMPILE_STD_DEV typedef struct bufferCtl { float *pBegin; float *pIndex; size_t length; bool filled; } BufCtl; class Ultrasonic { public: Ultrasonic(int tp, int ep); long timing(); float convert(long microsec, int metric); void setDivisor(float value, int metric); static const int IN = 0; static const int CM = 1; #ifdef COMPILE_STD_DEV bool sampleCreate(size_t size, ...); void sampleClear(); float unbiasedStdDev(float value, size_t bufNum); #endif // COMPILE_STD_DEV private: int _trigPin; int _echoPin; float _cmDivisor; float _inDivisor; #ifdef COMPILE_STD_DEV size_t _numBufs; BufCtl *_pBuffers; void _sampleUpdate(BufCtl *buf, float msec); void _freeBuffers(); #endif // COMPILE_STD_DEV }; #endif // ULTRASONIC_H
[ "brunoamenegotto@gmail.com" ]
brunoamenegotto@gmail.com
0b822de5076ed59f9ada3ce067a199bc838224cf
246a16842feb7633edbe6291ff36b4c93edbb3c7
/opengl-first/common/camera3.cpp
30d7ecbb56a59a424bd75aa5c9eee1cf901d45b9
[]
no_license
curtkim/c-first
2c223949912c708734648cf29f98778249f79346
f6fa50108ab7c032b74199561698cef087405c37
refs/heads/master
2023-06-08T10:57:35.159250
2023-05-28T05:52:20
2023-05-28T05:52:20
213,894,731
3
1
null
null
null
null
UTF-8
C++
false
false
8,020
cpp
#include "camera3.hpp" #include <GLFW/glfw3.h> #include <Eigen/Geometry> using namespace std; template<typename Scalar> Eigen::Matrix<Scalar,4,4> perspective(Scalar fovy, Scalar aspect, Scalar zNear, Scalar zFar){ Eigen::Transform<Scalar,3,Eigen::Projective> tr; tr.matrix().setZero(); assert(aspect > 0); assert(zFar > zNear); assert(zNear > 0); Scalar radf = M_PI * fovy / 180.0; Scalar tan_half_fovy = std::tan(radf / 2.0); tr(0,0) = 1.0 / (aspect * tan_half_fovy); tr(1,1) = 1.0 / (tan_half_fovy); tr(2,2) = - (zFar + zNear) / (zFar - zNear); tr(3,2) = - 1.0; tr(2,3) = - (2.0 * zFar * zNear) / (zFar - zNear); return tr.matrix(); } template<typename Derived> Eigen::Matrix<typename Derived::Scalar,4,4> lookAt(Derived const & eye, Derived const & center, Derived const & up){ typedef Eigen::Matrix<typename Derived::Scalar,4,4> Matrix4; typedef Eigen::Matrix<typename Derived::Scalar,3,1> Vector3; Vector3 f = (center - eye).normalized(); Vector3 u = up.normalized(); Vector3 s = f.cross(u).normalized(); u = s.cross(f); Matrix4 mat = Matrix4::Zero(); mat(0,0) = s.x(); mat(0,1) = s.y(); mat(0,2) = s.z(); mat(0,3) = -s.dot(eye); mat(1,0) = u.x(); mat(1,1) = u.y(); mat(1,2) = u.z(); mat(1,3) = -u.dot(eye); mat(2,0) = -f.x(); mat(2,1) = -f.y(); mat(2,2) = -f.z(); mat(2,3) = f.dot(eye); mat.row(3) << 0,0,0,1; return mat; } /// @see glm::ortho template<typename Scalar> Eigen::Matrix<Scalar,4,4> ortho( Scalar const& left, Scalar const& right, Scalar const& bottom, Scalar const& top, Scalar const& zNear, Scalar const& zFar ) { Eigen::Matrix<Scalar,4,4> mat = Eigen::Matrix<Scalar,4,4>::Identity(); mat(0,0) = Scalar(2) / (right - left); mat(1,1) = Scalar(2) / (top - bottom); mat(2,2) = - Scalar(2) / (zFar - zNear); mat(3,0) = - (right + left) / (right - left); mat(3,1) = - (top + bottom) / (top - bottom); mat(3,2) = - (zFar + zNear) / (zFar - zNear); return mat; } Camera3::Camera3() { camera_mode = FREE; camera_up = Eigen::Vector3f(0, 1, 0); field_of_view = 45; camera_position_delta = Eigen::Vector3f(0, 0, 0); camera_scale = .5f; max_pitch_rate = 5; max_heading_rate = 5; move_camera = false; } Camera3::~Camera3() { } void Camera3::Reset() { camera_up = Eigen::Vector3f(0, 1, 0); } void Camera3::Update() { camera_direction = (camera_look_at - camera_position).normalized(); //need to set the matrix state. this is only important because lighting doesn't work if this isn't done glViewport(viewport_x, viewport_y, window_width, window_height); projection = perspective(field_of_view, aspect, near_clip, far_clip); //detmine axis for pitch rotation Eigen::Vector3f axis = camera_direction.cross(camera_up).normalized(); //compute quaternion for pitch based on the camera pitch angle auto pitch_quat = Eigen::AngleAxisf(camera_pitch, axis); //determine heading quaternion from the camera up vector and the heading angle auto heading_quat = Eigen::AngleAxisf(camera_heading, camera_up); //add the two quaternions auto temp = pitch_quat*heading_quat; temp.normalized(); //update the direction from the quaternion camera_direction = temp*camera_direction; //add the camera delta camera_position += camera_position_delta; //set the look at to be infront of the camera camera_look_at = camera_position + camera_direction * 1.0f; //damping for smooth camera camera_heading *= .5; camera_pitch *= .5; camera_position_delta = camera_position_delta * .8f; //compute the MVP view = lookAt(camera_position, camera_look_at, camera_up); model = Eigen::Matrix4f::Ones(); MVP = projection * view * model; } //Setting Functions void Camera3::SetMode(CameraType cam_mode) { camera_mode = cam_mode; camera_up = Eigen::Vector3f(0, 1, 0); } void Camera3::SetPosition(Eigen::Vector3f pos) { camera_position = pos; } void Camera3::SetLookAt(Eigen::Vector3f pos) { camera_look_at = pos; } void Camera3::SetFOV(double fov) { field_of_view = fov; } void Camera3::SetViewport(int loc_x, int loc_y, int width, int height) { viewport_x = loc_x; viewport_y = loc_y; window_width = width; window_height = height; //need to use doubles division here, it will not work otherwise and it is possible to get a zero aspect ratio with integer rounding aspect = double(width) / double(height); ; } void Camera3::SetClipping(double near_clip_distance, double far_clip_distance) { near_clip = near_clip_distance; far_clip = far_clip_distance; } void Camera3::Move(CameraDirection dir) { if (camera_mode == FREE) { switch (dir) { case UP: camera_position_delta += camera_up * camera_scale; break; case DOWN: camera_position_delta -= camera_up * camera_scale; break; case LEFT: camera_position_delta -= camera_direction.cross(camera_up) * camera_scale; break; case RIGHT: camera_position_delta += camera_direction.cross(camera_up) * camera_scale; break; case FORWARD: camera_position_delta += camera_direction * camera_scale; break; case BACK: camera_position_delta -= camera_direction * camera_scale; break; } } } void Camera3::ChangePitch(float degrees) { //Check bounds with the max pitch rate so that we aren't moving too fast if (degrees < -max_pitch_rate) { degrees = -max_pitch_rate; } else if (degrees > max_pitch_rate) { degrees = max_pitch_rate; } camera_pitch += degrees; //Check bounds for the camera pitch if (camera_pitch > 360.0f) { camera_pitch -= 360.0f; } else if (camera_pitch < -360.0f) { camera_pitch += 360.0f; } } void Camera3::ChangeHeading(float degrees) { //Check bounds with the max heading rate so that we aren't moving too fast if (degrees < -max_heading_rate) { degrees = -max_heading_rate; } else if (degrees > max_heading_rate) { degrees = max_heading_rate; } //This controls how the heading is changed if the camera is pointed straight up or down //The heading delta direction changes if (camera_pitch > 90 && camera_pitch < 270 || (camera_pitch < -90 && camera_pitch > -270)) { camera_heading -= degrees; } else { camera_heading += degrees; } //Check bounds for the camera heading if (camera_heading > 360.0f) { camera_heading -= 360.0f; } else if (camera_heading < -360.0f) { camera_heading += 360.0f; } } void Camera3::Move2D(int x, int y) { //compute the mouse delta from the previous mouse position Eigen::Vector3f mouse_delta = mouse_position - Eigen::Vector3f(x, y, 0); //if the camera is moving, meaning that the mouse was clicked and dragged, change the pitch and heading if (move_camera) { ChangeHeading(.01f * mouse_delta.x()); ChangePitch(.01f * mouse_delta.y()); } mouse_position = Eigen::Vector3f (x, y, 0); } void Camera3::SetPos(int button, int state) { if (button == 3 && state == GLFW_PRESS) { camera_position_delta += camera_up * .05f; } else if (button == 4 && state == GLFW_PRESS) { camera_position_delta -= camera_up * .05f; } else if (button == GLFW_MOUSE_BUTTON_LEFT && state == GLFW_PRESS) { move_camera = true; } else if (button == GLFW_MOUSE_BUTTON_LEFT && state == GLFW_RELEASE) { move_camera = false; } //mouse_position = glm::vec3(x, y, 0); } CameraType Camera3::GetMode() { return camera_mode; } void Camera3::GetViewport(int &loc_x, int &loc_y, int &width, int &height) { loc_x = viewport_x; loc_y = viewport_y; width = window_width; height = window_height; } void Camera3::GetMatricies(Eigen::Matrix4f &P, Eigen::Matrix4f &V, Eigen::Matrix4f &M) { P = projection; V = view; M = model; }
[ "curt.k@kakaomobility.com" ]
curt.k@kakaomobility.com
de0f9202a769ece811cd64f57107199c00af49b3
5988ea61f0a5b61fef8550601b983b46beba9c5d
/3rd/ACE-5.7.0/ACE_wrappers/apps/JAWS/server/JAWS_IO.cpp
c0855b6f1ddd6d2f8deb2e572f7817a2a270f53c
[ "MIT" ]
permissive
binghuo365/BaseLab
e2fd1278ee149d8819b29feaa97240dec7c8b293
2b7720f6173672efd9178e45c3c5a9283257732a
refs/heads/master
2016-09-15T07:50:48.426709
2016-05-04T09:46:51
2016-05-04T09:46:51
38,291,364
1
2
null
null
null
null
UTF-8
C++
false
false
14,533
cpp
// $Id: JAWS_IO.cpp 85430 2009-05-25 11:26:46Z johnnyw $ #include "ace/OS_NS_string.h" #include "ace/OS_NS_sys_uio.h" #include "ace/OS_NS_sys_socket.h" #include "ace/Message_Block.h" #include "ace/Min_Max.h" #include "ace/SOCK_Stream.h" #include "ace/Filecache.h" #include "JAWS_IO.h" #include "HTTP_Helpers.h" #include "ace/OS_NS_fcntl.h" #include "ace/OS_NS_unistd.h" #include "ace/OS_NS_sys_stat.h" #include "ace/Auto_Ptr.h" #include "ace/Basic_Types.h" ACE_RCSID (server, IO, "$Id: JAWS_IO.cpp 85430 2009-05-25 11:26:46Z johnnyw $") JAWS_IO::JAWS_IO (void) : handler_ (0) { } JAWS_IO::~JAWS_IO (void) { } void JAWS_IO::handler (JAWS_IO_Handler *handler) { this->handler_ = handler; } JAWS_IO_Handler::~JAWS_IO_Handler (void) { } JAWS_Synch_IO::JAWS_Synch_IO (void) : handle_ (ACE_INVALID_HANDLE) { } JAWS_Synch_IO::~JAWS_Synch_IO (void) { ACE_OS::closesocket (this->handle_); } ACE_HANDLE JAWS_Synch_IO::handle (void) const { return this->handle_; } void JAWS_Synch_IO::handle (ACE_HANDLE handle) { this->handle_ = handle; } void JAWS_Synch_IO::read (ACE_Message_Block &mb, int size) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); int result = stream.recv (mb.wr_ptr (), size); if (result <= 0) this->handler_->read_error (); else { mb.wr_ptr (result); this->handler_->read_complete (mb); } } void JAWS_Synch_IO::receive_file (const char *filename, void *initial_data, int initial_data_length, int entire_length) { ACE_Filecache_Handle handle (filename, entire_length); int result = handle.error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); int bytes_to_memcpy = ACE_MIN (entire_length, initial_data_length); ACE_OS::memcpy (handle.address (), initial_data, bytes_to_memcpy); int bytes_to_read = entire_length - bytes_to_memcpy; int bytes = stream.recv_n ((char *) handle.address () + initial_data_length, bytes_to_read); if (bytes == bytes_to_read) this->handler_->receive_file_complete (); else result = -1; } if (result != ACE_Filecache_Handle::ACE_SUCCESS) this->handler_->receive_file_error (result); } void JAWS_Synch_IO::transmit_file (const char *filename, const char *header, int header_size, const char *trailer, int trailer_size) { ACE_Filecache_Handle handle (filename); int result = handle.error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { #if defined (ACE_JAWS_BASELINE) || defined (ACE_WIN32) ACE_SOCK_Stream stream; stream.set_handle (this->handle_); if ((stream.send_n (header, header_size) == header_size) && (stream.send_n (handle.address (), handle.size ()) == handle.size ()) && (stream.send_n (trailer, trailer_size) == trailer_size)) this->handler_->transmit_file_complete (); else result = -1; #else // Attempting to use writev // Is this faster? iovec iov[3]; int iovcnt = 0; if (header_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (header); iov[iovcnt].iov_len = header_size; iovcnt++; } if (handle.size () > 0) { iov[iovcnt].iov_base = reinterpret_cast<char*> (handle.address ()); iov[iovcnt].iov_len = handle.size (); iovcnt++; } if (trailer_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (trailer); iov[iovcnt].iov_len = trailer_size; iovcnt++; } if (ACE_OS::writev (this->handle_, iov, iovcnt) < 0) result = -1; else this->handler_->transmit_file_complete (); #endif /* ACE_JAWS_BASELINE */ } if (result != ACE_Filecache_Handle::ACE_SUCCESS) this->handler_->transmit_file_error (result); } void JAWS_Synch_IO::send_confirmation_message (const char *buffer, int length) { this->send_message (buffer, length); this->handler_->confirmation_message_complete (); } void JAWS_Synch_IO::send_error_message (const char *buffer, int length) { this->send_message (buffer, length); this->handler_->error_message_complete (); } void JAWS_Synch_IO::send_message (const char *buffer, int length) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); stream.send_n (buffer, length); } // This only works on Win32 #if defined (ACE_HAS_WIN32_OVERLAPPED_IO) JAWS_Asynch_IO::JAWS_Asynch_IO (void) { } JAWS_Asynch_IO::~JAWS_Asynch_IO (void) { ACE_OS::closesocket (this->handle_); } void JAWS_Asynch_IO::read (ACE_Message_Block& mb, int size) { ACE_Asynch_Read_Stream ar; if (ar.open (*this, this->handle_) == -1 || ar.read (mb, size) == -1) this->handler_->read_error (); } // This method will be called when an asynchronous read completes on a // stream. void JAWS_Asynch_IO::handle_read_stream (const ACE_Asynch_Read_Stream::Result &result) { // This callback is for this->receive_file() if (result.act () != 0) { int code = 0; if (result.success () && result.bytes_transferred () != 0) { if (result.message_block ().length () == result.message_block ().size ()) code = ACE_Filecache_Handle::ACE_SUCCESS; else { ACE_Asynch_Read_Stream ar; if (ar.open (*this, this->handle_) == -1 || ar.read (result.message_block (), result.message_block ().size () - result.message_block ().length (), result.act ()) == -1) code = -1; else return; } } else code = -1; if (code == ACE_Filecache_Handle::ACE_SUCCESS) this->handler_->receive_file_complete (); else this->handler_->receive_file_error (code); delete &result.message_block (); delete (ACE_Filecache_Handle *) result.act (); } else { // This callback is for this->read() if (result.success () && result.bytes_transferred () != 0) this->handler_->read_complete (result.message_block ()); else this->handler_->read_error (); } } void JAWS_Asynch_IO::receive_file (const char *filename, void *initial_data, int initial_data_length, int entire_length) { ACE_Message_Block *mb = 0; ACE_Filecache_Handle *handle; ACE_NEW (handle, ACE_Filecache_Handle (filename, entire_length, ACE_NOMAP)); int result = handle->error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { ACE_OS::memcpy (handle->address (), initial_data, initial_data_length); int bytes_to_read = entire_length - initial_data_length; ACE_NEW (mb, ACE_Message_Block ((char *)handle->address () + initial_data_length, bytes_to_read)); if (mb == 0) { errno = ENOMEM; result = -1; } else { ACE_Asynch_Read_Stream ar; if (ar.open (*this, this->handle_) == -1 || ar.read (*mb, mb->size () - mb->length (), handle) == -1) result = -1; } } if (result != ACE_Filecache_Handle::ACE_SUCCESS) { this->handler_->receive_file_error (result); delete mb; delete handle; } } void JAWS_Asynch_IO::transmit_file (const char *filename, const char *header, int header_size, const char *trailer, int trailer_size) { ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer = 0; ACE_Filecache_Handle *handle = new ACE_Filecache_Handle (filename, ACE_NOMAP); int result = handle->error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { ACE_Message_Block header_mb (header, header_size); ACE_Message_Block trailer_mb (trailer, trailer_size); header_and_trailer = new ACE_Asynch_Transmit_File::Header_And_Trailer (&header_mb, header_size, &trailer_mb, trailer_size); ACE_Asynch_Transmit_File tf; if (tf.open (*this, this->handle_) == -1 || tf.transmit_file (handle->handle (), // file handle header_and_trailer, // header and trailer data 0, // bytes_to_write 0, // offset 0, // offset_high 0, // bytes_per_send 0, // flags handle // act ) == -1) result = -1; } if (result != ACE_Filecache_Handle::ACE_SUCCESS) { this->handler_->transmit_file_error (result); delete header_and_trailer; delete handle; } } // This method will be called when an asynchronous transmit file completes. void JAWS_Asynch_IO::handle_transmit_file (const ACE_Asynch_Transmit_File::Result &result) { if (result.success ()) this->handler_->transmit_file_complete (); else this->handler_->transmit_file_error (-1); delete result.header_and_trailer (); delete (ACE_Filecache_Handle *) result.act (); } void JAWS_Asynch_IO::send_confirmation_message (const char *buffer, int length) { this->send_message (buffer, length, CONFORMATION); } void JAWS_Asynch_IO::send_error_message (const char *buffer, int length) { this->send_message (buffer, length, ERROR_MESSAGE); } void JAWS_Asynch_IO::send_message (const char *buffer, int length, int act) { ACE_Message_Block *mb; ACE_NEW (mb, ACE_Message_Block (buffer, length)); if (mb == 0) { this->handler_->error_message_complete (); return; } ACE_Asynch_Write_Stream aw; if (aw.open (*this, this->handle_) == -1 || aw.write (*mb, length, (void *) static_cast<intptr_t> (act)) == -1) { mb->release (); if (act == CONFORMATION) this->handler_->confirmation_message_complete (); else this->handler_->error_message_complete (); } } void JAWS_Asynch_IO::handle_write_stream (const ACE_Asynch_Write_Stream::Result &result) { result.message_block ().release (); if (result.act () == (void *) CONFORMATION) this->handler_->confirmation_message_complete (); else this->handler_->error_message_complete (); } #endif /* ACE_HAS_WIN32_OVERLAPPED_IO */ //-------------------Adding SYNCH IO no Caching JAWS_Synch_IO_No_Cache::JAWS_Synch_IO_No_Cache (void) : handle_ (ACE_INVALID_HANDLE) { } JAWS_Synch_IO_No_Cache::~JAWS_Synch_IO_No_Cache (void) { ACE_OS::closesocket (this->handle_); } ACE_HANDLE JAWS_Synch_IO_No_Cache::handle (void) const { return this->handle_; } void JAWS_Synch_IO_No_Cache::handle (ACE_HANDLE handle) { this->handle_ = handle; } void JAWS_Synch_IO_No_Cache::read (ACE_Message_Block &mb, int size) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); int result = stream.recv (mb.wr_ptr (), size); if (result <= 0) this->handler_->read_error (); else { mb.wr_ptr (result); this->handler_->read_complete (mb); } } void JAWS_Synch_IO_No_Cache::receive_file (const char *, void *, int, int) { //ugly hack to send HTTP_Status_Code::STATUS_FORBIDDEN this->handler_->receive_file_error (5); } void JAWS_Synch_IO_No_Cache::transmit_file (const char *filename, const char *header, int header_size, const char *trailer, int trailer_size) { int result = 0; // Can we access the file? if (ACE_OS::access (filename, R_OK) == -1) { //ugly hack to send in HTTP_Status_Code::STATUS_NOT_FOUND result = ACE_Filecache_Handle::ACE_ACCESS_FAILED; this->handler_->transmit_file_error (result); return; } ACE_stat stat; // Can we stat the file? if (ACE_OS::stat (filename, &stat) == -1) { //ugly hack to send HTTP_Status_Code::STATUS_FORBIDDEN result = ACE_Filecache_Handle::ACE_STAT_FAILED; this->handler_->transmit_file_error (result); return; } ACE_OFF_T size = stat.st_size; // Can we open the file? ACE_HANDLE handle = ACE_OS::open (filename, O_RDONLY); if (handle == ACE_INVALID_HANDLE) { //ugly hack to send HTTP_Status_Code::STATUS_FORBIDDEN result = ACE_Filecache_Handle::ACE_OPEN_FAILED; this->handler_->transmit_file_error (result); return; } char* f = new char[size]; ACE_Auto_Basic_Array_Ptr<char> file (f); ACE_OS::read_n (handle, f, size); ACE_SOCK_Stream stream; stream.set_handle (this->handle_); if ((stream.send_n (header, header_size) == header_size) && (stream.send_n (f, size) == size) && (stream.send_n (trailer, trailer_size) == trailer_size)) { this->handler_->transmit_file_complete (); } else { //ugly hack to default to HTTP_Status_Code::STATUS_INTERNAL_SERVER_ERROR result = -1; this->handler_->transmit_file_error (result); } ACE_OS::close (handle); } void JAWS_Synch_IO_No_Cache::send_confirmation_message (const char *buffer, int length) { this->send_message (buffer, length); this->handler_->confirmation_message_complete (); } void JAWS_Synch_IO_No_Cache::send_error_message (const char *buffer, int length) { this->send_message (buffer, length); this->handler_->error_message_complete (); } void JAWS_Synch_IO_No_Cache::send_message (const char *buffer, int length) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); stream.send_n (buffer, length); }
[ "binghuo365@hotmail.com" ]
binghuo365@hotmail.com
5eb0c134f5e6a20fcdf60e9a7fdc910c5c74f461
efb05ad736dc3e735a154ffe1224da0ceb5dc2d1
/ref_counted.hpp
52507e84c73f6c92b91bd2f0c111df730abac381
[ "MIT" ]
permissive
kotbegemot/intrusive_ptr
b17c813c17d64311fa45e173c843c283fc34cee4
ff07aeac90eb551adfcd4207234d92ecc1010cf3
refs/heads/master
2020-03-13T22:11:01.374784
2018-09-03T08:09:58
2018-09-03T08:09:58
131,311,587
4
1
null
null
null
null
UTF-8
C++
false
false
856
hpp
#ifndef REF_COUNTED_HPP #define REF_COUNTED_HPP #include <atomic> #include <cstddef> namespace std { class ref_counted { public: ~ref_counted(); ref_counted(); ref_counted(const ref_counted &); ref_counted &operator=(const ref_counted &); inline void ref() noexcept { rc_.fetch_add(1, std::memory_order_relaxed); } void deref() noexcept; inline bool unique() const noexcept { return rc_ == 1; } inline size_t get_reference_count() const noexcept { return rc_; } protected: std::atomic<size_t> rc_; }; inline void intrusive_ptr_add_ref(ref_counted *p) { p->ref(); } inline void intrusive_ptr_release(ref_counted *p) { p->deref(); } } #endif // REF_COUNTED_HPP
[ "k0tb9g9m0t@yandex.ru" ]
k0tb9g9m0t@yandex.ru
aafaefb489abfbfdcac174b6a5a43ee3c44aa215
b1486a219b350c4533c8e28400de020450f0c975
/Lab04/QuadHash.cpp
73b90ea178767b063bb1cd9eaf94a3de45bdd138
[]
no_license
anhuynh95/EECS_560
94e479d6ad80c99e7030e7f5964648a4b649c782
758a5d6f197301d85194ae799b1af6a6dc103fc1
refs/heads/master
2020-04-18T09:33:48.849122
2019-04-16T22:18:29
2019-04-16T22:18:29
167,438,623
0
0
null
null
null
null
UTF-8
C++
false
false
4,804
cpp
#include "QuadHash.h" #include <iostream> using namespace std; QuadHash::QuadHash(int x) { elementNum = 0; size = x; bucket = new std::string[size]; isEmpty = new bool[size]; isReversed = new bool[size]; for(int i =0; i<size; i++) { bucket[i] = ""; isEmpty[i] = true; isReversed[i] = false; } } QuadHash::~QuadHash() { delete[] bucket; delete[] isEmpty; delete[] isReversed; size =0; elementNum = 0; } int QuadHash::Hash(std::string x, int y) { int position; position = (std::stoi(x)+y)%size; return position; } void QuadHash::Print() { cout<<"Hash Table with Quadratic Probing:\n"; for(int i =0; i<size; i++) { if(bucket[i]!="") cout<<i<<": "<<bucket[i]<<endl; } cout<<endl; } bool QuadHash::isOn(std::string x) { bool check = false; for(int i =0; i<size; i++) { if(bucket[i] == x) { check = true; break; } } return (check); } void QuadHash::Insert(std::string x) { if(isOn(x) == true) { cout<<"Quadratic probing: "<<x<<" is duplicated, can’t be added to the hash table\n"; } else { elementNum++; float lamda = float(elementNum)/float(size); if(lamda >0.5) { Rehash(); Insert2(x, 1); Print(); } else { int position = Hash(x,0); if(isEmpty[position] == true) { bucket[position] = x; isEmpty[position] = false; cout<<"Quadratic probing: "<<x<<" is inserted into the hash table\n"; } else { bool check = false; for(int i=1; i<=20; i++) { if(isEmpty[Hash(x,i*i)] == true) { bucket[Hash(x,i*i)] = x; isEmpty[Hash(x,i*i)] = false; check = true; cout<<"Quadratic probing: "<<x<<" is inserted into the hash table\n"; break; } } if(check == false) { elementNum--; cout<<"Quadratic probing: Insert failed.\n"; } } } } } void QuadHash::Insert2(std::string x, int y) { int position = Hash(x,0); if(isEmpty[position] == true) { bucket[position] = x; isEmpty[position] = false; elementNum = elementNum+y; } else { for(int i=1; i<=elementNum; i++) { if(isEmpty[Hash(x,i*i)] == true) { bucket[Hash(x,i*i)] = x; isEmpty[Hash(x,i*i)] = false; elementNum = elementNum+y; break; } } } } void QuadHash::Delete(std::string x) { if(isOn(x) == false) { cout<<"Quadratic probing: "<<x<<" is not found.\n"; } else { for(int i =0; i<size; i++) { if(bucket[i]==x) { bucket[i] = ""; isEmpty[i] = true; elementNum--; cout<<"Quadratic probing: "<<x<<" is deleted from the hash table.\n"; break; } } } } bool QuadHash::Find(std::string x) { bool check = false; std::string result; for(int i =0; i<size; i++) { if(bucket[i] == x) { cout<<"Quadratic probing: "<<x<<" is found at location "<<i<<endl; check = true; break; } } if(check == false) { cout<<"Quadratic probing: "<<x<<" is not found in the hash table.\n"; return false; } else return true; } void QuadHash::FindPalindrome() { cout<<"Palindrome strings: "; for(int i =0; i<size; i++) { int start =0; int end = bucket[i].length()-1; std::string temp = bucket[i]; bool check = true; if(temp!="") { while (start < end) { if(temp[start]!=temp[end]) { check = false; } start++; end--; } if(check == true) { cout<<temp<<" "; } } } cout<<endl<<endl; } void QuadHash::ReverseString(int x) { std::string temp = bucket[x]; if(temp !="") { int end = bucket[x].length(); cout<<"Quadratic probing: String '"<<temp; for(int i=0; i<end/2; i++) { char temp1 = temp[end-1]; temp[end-1] = temp[i]; temp[i] = temp1; } bucket[x] = temp; isReversed[x] = true; cout<<"' is changed to '"<<temp<<"'\n";; } else { cout<<"There is no string at location "<<x<<" with Quadratic probing.\n"; } } std::string QuadHash::findReverse(std::string x) { std::string temp = x; if(temp !="") { int end = temp.length(); for(int i=0; i<end/2; i++) { char temp1 = temp[end-1]; temp[end-1] = temp[i]; temp[i] = temp1; } } return (temp); } int QuadHash::findNextPrime(int x) { int i, count; for(i=x; 1; i++) { count =0; for(int j=2; j<i; j++) { if(i%j == 0) { count++; break; } } if(count ==0) return i; } } void QuadHash::Rehash() { int newSize = findNextPrime(size*2); std::string* backup = new std::string[elementNum]; int count=0; for(int i=0; i<size; i++) { if(bucket[i]!="") { backup[count] = bucket[i]; count++; } } size = newSize; bucket = new std::string[size]; isEmpty = new bool[size]; for(int i=0; i<size; i++) { bucket[i]=""; isEmpty[i] = true; } for(int i=0; i<elementNum; i++) { std::string temp = backup[i]; Insert2(temp,0); } cout<<"Rehashing....\n\n"; }
[ "arizhuynh211@gmail.com" ]
arizhuynh211@gmail.com
68b44432bb0db75f7a7a17767cf55b96f6f0c111
d8c91260984fbe182066c47e2b5f05586bba8f04
/KSRUtility/Member.h
7284345d932e4830a195086b1f8af0e823ac219e
[]
no_license
Sebastian-Hothaza/KSRUtility
f022f7b622eeec6c9caa7228331d7d936048ee0f
cc1b98e444ecaea570ad947a0a94ea9e3c8122e3
refs/heads/master
2020-05-02T14:31:05.344381
2019-03-29T00:49:18
2019-03-29T00:49:18
178,012,888
0
0
null
null
null
null
UTF-8
C++
false
false
219
h
#pragma once #include <string> class member { std::string name; int age; public: member(std::string, int) ; std::string getName(); int getAge(); void setName(std::string); void setAge(int); void printMem(); };
[ "sebastianhothaza@gmail.com" ]
sebastianhothaza@gmail.com
183776115121fd3d9e605d41b9b5dbf3f1688c87
8654435d89790e32f8e4c336e91f23250da0acb0
/bullet3/src/Bullet3OpenCL/BroadphaseCollision/b3GpuParallelLinearBvhBroadphase.h
902bd04e1cbb50e2b631b1c89e69f6199398ce73
[ "Zlib" ]
permissive
takamtd/deepmimic
226ca68860e5ef206f50d77893dd19af7ac40e46
b0820fb96ee76b9219bce429fd9b63de103ba40a
refs/heads/main
2023-05-09T16:48:16.554243
2021-06-07T05:04:47
2021-06-07T05:04:47
373,762,616
1
0
null
null
null
null
UTF-8
C++
false
false
3,081
h
/* This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //Initial Author Jackson Lee, 2014 #ifndef B3_GPU_PARALLEL_LINEAR_BVH_BROADPHASE_H #define B3_GPU_PARALLEL_LINEAR_BVH_BROADPHASE_H #include "Bullet3OpenCL/BroadphaseCollision/b3GpuBroadphaseInterface.h" #include "b3GpuParallelLinearBvh.h" class b3GpuParallelLinearBvhBroadphase : public b3GpuBroadphaseInterface { b3GpuParallelLinearBvh m_plbvh; b3OpenCLArray<b3Int4> m_overlappingPairsGpu; b3OpenCLArray<b3SapAabb> m_aabbsGpu; b3OpenCLArray<int> m_smallAabbsMappingGpu; b3OpenCLArray<int> m_largeAabbsMappingGpu; b3AlignedObjectArray<b3SapAabb> m_aabbsCpu; b3AlignedObjectArray<int> m_smallAabbsMappingCpu; b3AlignedObjectArray<int> m_largeAabbsMappingCpu; public: b3GpuParallelLinearBvhBroadphase(cl_context context, cl_device_id device, cl_command_queue queue); virtual ~b3GpuParallelLinearBvhBroadphase() {} virtual void createProxy(const b3Vector3& aabbMin, const b3Vector3& aabbMax, int userPtr, int collisionFilterGroup, int collisionFilterMask); virtual void createLargeProxy(const b3Vector3& aabbMin, const b3Vector3& aabbMax, int userPtr, int collisionFilterGroup, int collisionFilterMask); virtual void calculateOverlappingPairs(int maxPairs); virtual void calculateOverlappingPairsHost(int maxPairs); //call writeAabbsToGpu after done making all changes (createProxy etc) virtual void writeAabbsToGpu(); virtual int getNumOverlap() { return m_overlappingPairsGpu.size(); } virtual cl_mem getOverlappingPairBuffer() { return m_overlappingPairsGpu.getBufferCL(); } virtual cl_mem getAabbBufferWS() { return m_aabbsGpu.getBufferCL(); } virtual b3OpenCLArray<b3SapAabb>& getAllAabbsGPU() { return m_aabbsGpu; } virtual b3OpenCLArray<b3Int4>& getOverlappingPairsGPU() { return m_overlappingPairsGpu; } virtual b3OpenCLArray<int>& getSmallAabbIndicesGPU() { return m_smallAabbsMappingGpu; } virtual b3OpenCLArray<int>& getLargeAabbIndicesGPU() { return m_largeAabbsMappingGpu; } virtual b3AlignedObjectArray<b3SapAabb>& getAllAabbsCPU() { return m_aabbsCpu; } static b3GpuBroadphaseInterface* CreateFunc(cl_context context, cl_device_id device, cl_command_queue queue) { return new b3GpuParallelLinearBvhBroadphase(context, device, queue); } }; #endif
[ "m.tym29101998@gmail.com" ]
m.tym29101998@gmail.com
282bbc541588807172390c1d12b3fdb32ae1262e
3c1f20a8b66f35beb37e1137b3ae406d8ff74ba1
/SENTENCE.HPP
2998e55726da510d9c6867f4b64fb89f3cb83cb3
[ "MIT" ]
permissive
Rope-master/NMEA0183
eba5ea90a833fbaee490de0f1975894e4c295575
881d602d3c9140fcb53fd38651cce93167d26100
refs/heads/master
2022-05-17T01:49:16.349571
2020-04-28T10:41:21
2020-04-28T10:41:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,877
hpp
#if ! defined( SENTENCE_CLASS_HEADER ) #define SENTENCE_CLASS_HEADER /* Author: Samuel R. Blackburn Internet: wfc@pobox.com "You can get credit for something or get it done, but not both." Dr. Richard Garwin The MIT License (MIT) Copyright (c) 1996-2019 Sam Blackburn 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. */ /* SPDX-License-Identifier: MIT */ class LATLONG; class SENTENCE { public: inline SENTENCE() noexcept {}; /* ** Data */ std::string Sentence; /* ** Methods */ virtual NMEA0183_BOOLEAN Boolean( int field_number ) const noexcept; virtual uint8_t ComputeChecksum( void ) const noexcept; virtual COMMUNICATIONS_MODE CommunicationsMode( int field_number ) const noexcept; virtual double Double( int field_number ) const noexcept; virtual EASTWEST EastOrWest( int field_number ) const noexcept; virtual std::string_view Field( int field_number ) const noexcept; virtual void Finish( void ) noexcept; virtual uint16_t GetNumberOfDataFields( void ) const noexcept; virtual int Integer( int field_number ) const noexcept; virtual NMEA0183_BOOLEAN IsChecksumBad( int checksum_field_number ) const noexcept; virtual LEFTRIGHT LeftOrRight( int field_number ) const noexcept; virtual NORTHSOUTH NorthOrSouth( int field_number ) const noexcept; virtual REFERENCE Reference( int field_number ) const noexcept; virtual time_t Time( int field_number ) const noexcept; virtual TRANSDUCER_TYPE TransducerType( int field_number ) const noexcept; /* ** Operators */ operator std::string() const noexcept; operator std::string_view() const noexcept; virtual SENTENCE const& operator = ( SENTENCE const& source ) noexcept; virtual SENTENCE const& operator = ( std::string_view source ) noexcept; virtual SENTENCE const& operator += ( std::string_view source ) noexcept; virtual SENTENCE const& operator += ( double const value ) noexcept; virtual SENTENCE const& operator += ( int const value ) noexcept; virtual SENTENCE const& operator += ( COMMUNICATIONS_MODE const mode ) noexcept; virtual SENTENCE const& operator += ( EASTWEST const easting ) noexcept; virtual SENTENCE const& operator += ( LATLONG const& source ) noexcept; virtual SENTENCE const& operator += ( NMEA0183_BOOLEAN const boolean ) noexcept; virtual SENTENCE const& operator += ( NORTHSOUTH const northing ) noexcept; virtual SENTENCE const& operator += ( time_t const time ) noexcept; virtual SENTENCE const& operator += ( TRANSDUCER_TYPE const transducer ) noexcept; virtual SENTENCE const& operator += ( LEFTRIGHT const left_or_right ) noexcept; virtual SENTENCE const& operator += ( REFERENCE const a_reference ) noexcept; }; #endif // SENTENCE_CLASS_HEADER
[ "sam_blackburn@pobox.com" ]
sam_blackburn@pobox.com
289d3fbb8873fdb8545680353f59c4380d466a3e
13781d36f3a3ae2684e41f47268b3d5c5767881b
/bwi_tasks/src/visit_and_ask_list.cpp
afab2ff67590e35cffadffb63676c082ce02d0ac
[ "LicenseRef-scancode-public-domain" ]
permissive
utexas-bwi/bwi_common
c1da90b2d3b88e4514ccc088d6a783a22a65b0fa
ae037f3fca15951e29e08644a135aac1a2ca456f
refs/heads/master
2023-07-20T15:05:34.771069
2023-07-13T04:54:47
2023-07-13T04:54:47
14,791,963
17
43
NOASSERTION
2021-07-16T14:30:24
2013-11-29T03:26:28
C++
UTF-8
C++
false
false
3,709
cpp
#include "plan_execution/ExecutePlanAction.h" #include <plan_execution/UpdateFluents.h> #include <actionlib/client/simple_action_client.h> #include <ros/ros.h> #include <time.h> typedef actionlib::SimpleActionClient<plan_execution::ExecutePlanAction> Client; using namespace std; plan_execution::ExecutePlanGoal navigationGoal(const string location) { plan_execution::ExecutePlanGoal goal; plan_execution::AspRule rule; plan_execution::AspFluent fluent; fluent.name = "not facing"; fluent.variables.push_back(location); rule.body.push_back(fluent); goal.aspGoal.push_back(rule); return goal; } plan_execution::ExecutePlanGoal findPersonGoal(const string person) { plan_execution::ExecutePlanGoal goal; plan_execution::AspRule rule; plan_execution::AspFluent fluent; fluent.name = "not ingdc"; fluent.variables.push_back(person); rule.body.push_back(fluent); plan_execution::AspFluent fluent_not; fluent_not.name = "not -ingdc"; fluent_not.variables.push_back(person); rule.body.push_back(fluent_not); plan_execution::AspRule rule_nav; plan_execution::AspFluent fluent_nav; fluent_nav.name = "not facing"; fluent_nav.variables.push_back("d3_414b2"); rule_nav.body.push_back(fluent_nav); goal.aspGoal.push_back(rule); //goal.aspGoal.push_back(rule_nav); return goal; } int main(int argc, char**argv) { ros::init(argc, argv, "visit_and_ask_node"); ros::NodeHandle n; ros::NodeHandle privateNode("~"); srand (time(NULL)); /*string locationA; privateNode.param<string>("a",locationA,"d3_414b1"); string locationB privateNode.param<string>("b",locationB,"d3_414b2");*/ std::vector<string> doors; doors.push_back("d3_414b1"); doors.push_back("d3_414b2"); doors.push_back("d3_414a1"); doors.push_back("d3_414a2"); std::vector<string> people; people.push_back("peter"); people.push_back("jivko"); people.push_back("garrett"); people.push_back("justin"); people.push_back("yuqian"); int current_door = 0; int current_person = 0; Client client("/action_executor/execute_plan", true); client.waitForServer(); ros::ServiceClient krClient = n.serviceClient<plan_execution::UpdateFluents> ( "update_fluents" ); krClient.waitForExistence(); bool fromAtoB = true; while (ros::ok()) { plan_execution::ExecutePlanGoal goal; float r = ((float) rand() / (RAND_MAX)); r=0; if (r >= 0.7) { string location = doors.at(current_door); current_door++; if (current_door >= (int)doors.size()) current_door = 0; ROS_INFO_STREAM("going to " << location); goal = navigationGoal(location); } else { string person = people.at(current_person); current_person++; if (current_person >= (int)people.size()) current_person = 0; plan_execution::UpdateFluents uf; plan_execution::AspFluent find_person_flag; find_person_flag.name = "findPersonTask"; find_person_flag.variables.push_back(person); uf.request.fluents.push_back(find_person_flag); krClient.call(uf); ROS_INFO_STREAM("looking for " << person); goal = findPersonGoal(person); } ROS_INFO("sending goal"); client.sendGoalAndWait(goal); if (client.getState() == actionlib::SimpleClientGoalState::ABORTED) { ROS_INFO("Aborted"); } else if (client.getState() == actionlib::SimpleClientGoalState::PREEMPTED) { ROS_INFO("Preempted"); } else if (client.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Succeeded!"); } else ROS_INFO("Terminated"); } return 0; }
[ "jiangyuqian@utexas.edu" ]
jiangyuqian@utexas.edu
e3135863ddaa0a61435839896ba2e0dd290bc7d5
ce29d99c84fc7a54d7eed578d9360dc266b01ff9
/335/CF335F.cpp
1ed764b9cb4454be100657d3ad1243bb57e52a82
[]
no_license
mruxim/codeforces
a3f8d28029a77ebc247d939adedc1d547bab0225
5a214b19a0d09c9152ca5b2ef9ff7e5dcc692c50
refs/heads/master
2021-10-26T04:33:42.553698
2019-04-10T12:58:21
2019-04-10T12:58:21
180,573,952
0
0
null
null
null
null
UTF-8
C++
false
false
2,064
cpp
// .... .... .....! // P..... C.....! #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <cassert> #include <algorithm> #include <string> #include <vector> #include <set> #include <map> #include <queue> #include <stack> #include <cmath> #include <numeric> #include <bitset> #include <cstdio> #include <cstring> using namespace std; #define rep(i, n) for (int i = 0, _n = (int)(n); i < _n; i++) #define fer(i, x, n) for (int i = (int)(x), _n = (int)(n); i < _n; i++) #define rof(i, n, x) for (int i = (int)(n), _x = (int)(x); i-- > _x; ) #define fch(i, x) for (__typeof(x.begin()) i = x.begin(); i != x.end(); i++) #define sz(x) (int((x).size())) #define pb push_back #define mkp make_pair #define all(X) (X).begin(),(X).end() #define X first #define Y second typedef long long ll; typedef pair <int, int> pii; //////////////////////////////////////////////////////////////////////////////// struct cmp { bool operator ()(const pii &p, const pii &q) const { return p.X+p.Y != q.X+q.Y ? p.X+p.Y < q.X+q.Y : p.X < q.X; } }; int n; int a[(int)5e5+5]; int C, V; multiset <pii, cmp> S, T; ll cost; int main() { ios_base::sync_with_stdio (false); cin >> n; rep (i, n) cin >> a[i]; sort (a, a+n); for (int i = n; i--; ) { int j = i; while (j && a[j-1] == a[i]) j--; int cnt = i-j+1, val = a[i]; while (cnt) { if (C && val < V) { T.insert (pii (val, V)); C--; cnt--; } else if (cnt >= 2 && !S.empty() && S.begin()->X < 2*val) { pii tmp = *S.begin(); S.erase (S.begin()); T.insert (pii (val, tmp.X)); T.insert (pii (val, tmp.Y)); cost += tmp.X; cnt -= 2; } else C++, V = val, cnt--, cost += val; } for (auto p: T) S.insert (p); T.clear(); i = j; cerr << " ! " << C << ' ' << V << endl; for (auto p: S) cerr << " @ " << p.X << ' ' << p.Y << endl; cerr << endl; } cout << cost << endl; { int _; cin >> _; return 0; } }
[ "maleki.mr@gmail.com" ]
maleki.mr@gmail.com
89064e42c754bc38f20c67f3c8c6a6d3a2ca048f
e008298a11393d3e2678fb74277f8db7448fc6b1
/silkopter/brain/autogen/sz_SPI_RPI.hpp
c58aace262958a7ec21a6151f9efc9e190ad1f84
[ "BSD-3-Clause" ]
permissive
ggggamer/silkopter
e421d1c21d849ed259e100638a7bf5c02b71922b
e82e5bcf5c3b227a9b3440940f2206041311d060
refs/heads/master
2021-01-16T22:21:53.705284
2015-09-02T16:57:54
2015-09-02T16:57:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,658
hpp
#pragma once // The MIT License (MIT) // // Copyright (c) 2014 Siyuan Ren (netheril96@gmail.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. // // 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 <autojsoncxx/autojsoncxx.hpp> // The comments are reserved for replacement // such syntax is chosen so that the template file looks like valid C++ namespace sz { namespace SPI_RPI { struct Init_Params { uint32_t dev; uint32_t mode; uint32_t speed; explicit Init_Params():dev(), mode(), speed() { } }; } } namespace autojsoncxx { template <> class SAXEventHandler< ::sz::SPI_RPI::Init_Params > { private: utility::scoped_ptr<error::ErrorBase> the_error; int state; int depth; SAXEventHandler< uint32_t > handler_0; SAXEventHandler< uint32_t > handler_1; SAXEventHandler< uint32_t > handler_2;bool has_dev; bool has_mode; bool has_speed; bool check_depth(const char* type) { if (depth <= 0) { the_error.reset(new error::TypeMismatchError("object", type)); return false; } return true; } const char* current_member_name() const { switch (state) { case 0: return "dev"; case 1: return "mode"; case 2: return "speed"; default: break; } return "<UNKNOWN>"; } bool checked_event_forwarding(bool success) { if (!success) the_error.reset(new error::ObjectMemberError(current_member_name())); return success; } void set_missing_required(const char* name) { if (the_error.empty() || the_error->type() != error::MISSING_REQUIRED) the_error.reset(new error::RequiredFieldMissingError()); std::vector<std::string>& missing = static_cast<error::RequiredFieldMissingError*>(the_error.get())->missing_members(); missing.push_back(name); } void reset_flags() { has_dev = false; has_mode = false; has_speed = false; } public: explicit SAXEventHandler( ::sz::SPI_RPI::Init_Params * obj) : state(-1) , depth(0) , handler_0(&obj->dev) , handler_1(&obj->mode) , handler_2(&obj->speed) { reset_flags(); } bool Null() { if (!check_depth("null")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Null()); case 1: return checked_event_forwarding(handler_1.Null()); case 2: return checked_event_forwarding(handler_2.Null()); default: break; } return true; } bool Bool(bool b) { if (!check_depth("bool")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Bool(b)); case 1: return checked_event_forwarding(handler_1.Bool(b)); case 2: return checked_event_forwarding(handler_2.Bool(b)); default: break; } return true; } bool Int(int i) { if (!check_depth("int")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Int(i)); case 1: return checked_event_forwarding(handler_1.Int(i)); case 2: return checked_event_forwarding(handler_2.Int(i)); default: break; } return true; } bool Uint(unsigned i) { if (!check_depth("unsigned")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Uint(i)); case 1: return checked_event_forwarding(handler_1.Uint(i)); case 2: return checked_event_forwarding(handler_2.Uint(i)); default: break; } return true; } bool Int64(utility::int64_t i) { if (!check_depth("int64_t")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Int64(i)); case 1: return checked_event_forwarding(handler_1.Int64(i)); case 2: return checked_event_forwarding(handler_2.Int64(i)); default: break; } return true; } bool Uint64(utility::uint64_t i) { if (!check_depth("uint64_t")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Uint64(i)); case 1: return checked_event_forwarding(handler_1.Uint64(i)); case 2: return checked_event_forwarding(handler_2.Uint64(i)); default: break; } return true; } bool Double(double d) { if (!check_depth("double")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.Double(d)); case 1: return checked_event_forwarding(handler_1.Double(d)); case 2: return checked_event_forwarding(handler_2.Double(d)); default: break; } return true; } bool String(const char* str, SizeType length, bool copy) { if (!check_depth("string")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.String(str, length, copy)); case 1: return checked_event_forwarding(handler_1.String(str, length, copy)); case 2: return checked_event_forwarding(handler_2.String(str, length, copy)); default: break; } return true; } bool Key(const char* str, SizeType length, bool copy) { if (!check_depth("object")) return false; if (depth == 1) { if (0) { } else if (utility::string_equal(str, length, "\x64\x65\x76", 3)) { state=0; has_dev = true; } else if (utility::string_equal(str, length, "\x6d\x6f\x64\x65", 4)) { state=1; has_mode = true; } else if (utility::string_equal(str, length, "\x73\x70\x65\x65\x64", 5)) { state=2; has_speed = true; } else { state = -1; return true; } } else { switch (state) { case 0: return checked_event_forwarding(handler_0.Key(str, length, copy)); case 1: return checked_event_forwarding(handler_1.Key(str, length, copy)); case 2: return checked_event_forwarding(handler_2.Key(str, length, copy)); default: break; } } return true; } bool StartArray() { if (!check_depth("array")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.StartArray()); case 1: return checked_event_forwarding(handler_1.StartArray()); case 2: return checked_event_forwarding(handler_2.StartArray()); default: break; } return true; } bool EndArray(SizeType length) { if (!check_depth("array")) return false; switch (state) { case 0: return checked_event_forwarding(handler_0.EndArray(length)); case 1: return checked_event_forwarding(handler_1.EndArray(length)); case 2: return checked_event_forwarding(handler_2.EndArray(length)); default: break; } return true; } bool StartObject() { ++depth; if (depth > 1) { switch (state) { case 0: return checked_event_forwarding(handler_0.StartObject()); case 1: return checked_event_forwarding(handler_1.StartObject()); case 2: return checked_event_forwarding(handler_2.StartObject()); default: break; } } return true; } bool EndObject(SizeType length) { --depth; if (depth > 0) { switch (state) { case 0: return checked_event_forwarding(handler_0.EndObject(length)); case 1: return checked_event_forwarding(handler_1.EndObject(length)); case 2: return checked_event_forwarding(handler_2.EndObject(length)); default: break; } } else { if (!has_dev) set_missing_required("dev"); if (!has_mode) set_missing_required("mode"); if (!has_speed) set_missing_required("speed"); } return the_error.empty(); } bool HasError() const { return !this->the_error.empty(); } bool ReapError(error::ErrorStack& errs) { if (this->the_error.empty()) return false; errs.push(this->the_error.release()); switch (state) { case 0: handler_0.ReapError(errs); break; case 1: handler_1.ReapError(errs); break; case 2: handler_2.ReapError(errs); break; default: break; } return true; } void PrepareForReuse() { depth = 0; state = -1; the_error.reset(); reset_flags(); handler_0.PrepareForReuse(); handler_1.PrepareForReuse(); handler_2.PrepareForReuse(); } }; template < class Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c > struct Serializer< Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c, ::sz::SPI_RPI::Init_Params > { void operator()( Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c& w, const ::sz::SPI_RPI::Init_Params& value) const { w.StartObject(); w.Key("\x64\x65\x76", 3, false); Serializer< Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c, uint32_t >()(w, value.dev); w.Key("\x6d\x6f\x64\x65", 4, false); Serializer< Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c, uint32_t >()(w, value.mode); w.Key("\x73\x70\x65\x65\x64", 5, false); Serializer< Writere09217728ee7e7c15de60e2a76a3d197f5755fb5b0ba8f1688be13dfb66e4f4c, uint32_t >()(w, value.speed); w.EndObject(3); } }; } // The MIT License (MIT) // // Copyright (c) 2014 Siyuan Ren (netheril96@gmail.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. // // 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 <autojsoncxx/autojsoncxx.hpp> // The comments are reserved for replacement // such syntax is chosen so that the template file looks like valid C++ namespace sz { namespace SPI_RPI { struct Config { explicit Config() { } }; } } namespace autojsoncxx { template <> class SAXEventHandler< ::sz::SPI_RPI::Config > { private: utility::scoped_ptr<error::ErrorBase> the_error; int state; int depth; bool check_depth(const char* type) { if (depth <= 0) { the_error.reset(new error::TypeMismatchError("object", type)); return false; } return true; } const char* current_member_name() const { switch (state) { default: break; } return "<UNKNOWN>"; } bool checked_event_forwarding(bool success) { if (!success) the_error.reset(new error::ObjectMemberError(current_member_name())); return success; } void set_missing_required(const char* name) { if (the_error.empty() || the_error->type() != error::MISSING_REQUIRED) the_error.reset(new error::RequiredFieldMissingError()); std::vector<std::string>& missing = static_cast<error::RequiredFieldMissingError*>(the_error.get())->missing_members(); missing.push_back(name); } void reset_flags() { } public: explicit SAXEventHandler( ::sz::SPI_RPI::Config * obj) : state(-1) , depth(0) { reset_flags(); } bool Null() { if (!check_depth("null")) return false; switch (state) { default: break; } return true; } bool Bool(bool b) { if (!check_depth("bool")) return false; switch (state) { default: break; } return true; } bool Int(int i) { if (!check_depth("int")) return false; switch (state) { default: break; } return true; } bool Uint(unsigned i) { if (!check_depth("unsigned")) return false; switch (state) { default: break; } return true; } bool Int64(utility::int64_t i) { if (!check_depth("int64_t")) return false; switch (state) { default: break; } return true; } bool Uint64(utility::uint64_t i) { if (!check_depth("uint64_t")) return false; switch (state) { default: break; } return true; } bool Double(double d) { if (!check_depth("double")) return false; switch (state) { default: break; } return true; } bool String(const char* str, SizeType length, bool copy) { if (!check_depth("string")) return false; switch (state) { default: break; } return true; } bool Key(const char* str, SizeType length, bool copy) { if (!check_depth("object")) return false; if (depth == 1) { if (0) { } else { state = -1; return true; } } else { switch (state) { default: break; } } return true; } bool StartArray() { if (!check_depth("array")) return false; switch (state) { default: break; } return true; } bool EndArray(SizeType length) { if (!check_depth("array")) return false; switch (state) { default: break; } return true; } bool StartObject() { ++depth; if (depth > 1) { switch (state) { default: break; } } return true; } bool EndObject(SizeType length) { --depth; if (depth > 0) { switch (state) { default: break; } } else { } return the_error.empty(); } bool HasError() const { return !this->the_error.empty(); } bool ReapError(error::ErrorStack& errs) { if (this->the_error.empty()) return false; errs.push(this->the_error.release()); switch (state) { default: break; } return true; } void PrepareForReuse() { depth = 0; state = -1; the_error.reset(); reset_flags(); } }; template < class Writerefeaf68c91cffa2a846562a506ccfc6826cfd0d1755a86b29db6cb855aa8fbc3 > struct Serializer< Writerefeaf68c91cffa2a846562a506ccfc6826cfd0d1755a86b29db6cb855aa8fbc3, ::sz::SPI_RPI::Config > { void operator()( Writerefeaf68c91cffa2a846562a506ccfc6826cfd0d1755a86b29db6cb855aa8fbc3& w, const ::sz::SPI_RPI::Config& value) const { w.StartObject(); w.EndObject(0); } }; }
[ "catalin.vasile@gmail.com" ]
catalin.vasile@gmail.com
9121313b14e59ed684c5512590e6233d4a930ee3
0c73246fa51b3faa01cc8b9cea5b8cd87e63a00b
/c++/DP Basics Using CPP/Knapsack Recursive.cpp
9748b90d70dce61cc07cb896edc06b3c96f5a35c
[ "MIT" ]
permissive
Ikshitkate/java-html-5-new-project
81793a5ba5b4e9e00c05d2ede85a095b63f46559
056c1e409fe3422c61c04397ee7b0ab87feff7d1
refs/heads/main
2023-08-29T06:05:05.743256
2021-10-27T15:07:50
2021-10-27T15:07:50
421,359,962
1
2
MIT
2021-10-31T13:04:33
2021-10-26T09:22:36
Python
UTF-8
C++
false
false
540
cpp
#include<bits/stdc++.h> using namespace std; int knapsack(int val[], int wt[], int w, int n){ if(n == 0 || w == 0){ return 0; } if(wt[n-1] <= w){ return max(val[n-1] + knapsack(val, wt, w - wt[n-1], n-1), knapsack(val, wt, w, n-1)); } else { return knapsack(val, wt, w, n - 1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int w = 50; int n = 3; cout << knapsack(val, wt, w, n); }
[ "72209667+dewanshk3255@users.noreply.github.com" ]
72209667+dewanshk3255@users.noreply.github.com
27889ce3a1864aa9ef14acb1865fc99f0b8a4ef9
20683c00ba6acdcf0933233156d7a173472c61af
/src/chainparamsbase.cpp
e42155b15c28d52512e437042f6bc5251cf142b1
[ "MIT" ]
permissive
AddmoreMining2020/Addmore
1b0576d39d0a6789ee18dc8610d6b037cbd8e909
f0b0df156959774b6c2ecb518ce8b16a706bfa12
refs/heads/master
2021-01-07T18:25:16.546967
2020-02-20T03:11:08
2020-02-20T03:11:08
241,781,590
0
1
null
null
null
null
UTF-8
C++
false
false
2,736
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 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 "chainparamsbase.h" #include "tinyformat.h" #include "util.h" #include <assert.h> const std::string CBaseChainParams::MAIN = "main"; const std::string CBaseChainParams::TESTNET = "test"; const std::string CBaseChainParams::REGTEST = "regtest"; void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp) { strUsage += HelpMessageGroup(_("Chain selection options:")); strUsage += HelpMessageOpt("-testnet", _("Use the test chain")); if (debugHelp) { strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " "This is intended for regression testing tools and app development."); } } /** * Main network */ class CBaseMainParams : public CBaseChainParams { public: CBaseMainParams() { nRPCPort = 4879; } }; static CBaseMainParams mainParams; /** * Testnet (v3) */ class CBaseTestNetParams : public CBaseChainParams { public: CBaseTestNetParams() { nRPCPort = 14879; strDataDir = "testnet3"; } }; static CBaseTestNetParams testNetParams; /* * Regression test */ class CBaseRegTestParams : public CBaseChainParams { public: CBaseRegTestParams() { nRPCPort = 24879; strDataDir = "regtest"; } }; static CBaseRegTestParams regTestParams; static CBaseChainParams* pCurrentBaseParams = 0; const CBaseChainParams& BaseParams() { assert(pCurrentBaseParams); return *pCurrentBaseParams; } CBaseChainParams& BaseParams(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return mainParams; else if (chain == CBaseChainParams::TESTNET) return testNetParams; else if (chain == CBaseChainParams::REGTEST) return regTestParams; else throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectBaseParams(const std::string& chain) { pCurrentBaseParams = &BaseParams(chain); } std::string ChainNameFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) throw std::runtime_error("Invalid combination of -regtest and -testnet."); if (fRegTest) return CBaseChainParams::REGTEST; if (fTestNet) return CBaseChainParams::TESTNET; return CBaseChainParams::MAIN; } bool AreBaseParamsConfigured() { return pCurrentBaseParams != NULL; }
[ "60209727+AddmoreMining2020@users.noreply.github.com" ]
60209727+AddmoreMining2020@users.noreply.github.com
ec94fe73feaeeb862699390e655c039c3cea0e37
8f695430e17a235dcb3d20c00986f5af0ccdd6a0
/main.cpp
a5ffe0e8a26b3ee480632b800e54938b8f31a5dd
[]
no_license
pawelbrzozowski/Statki_v4
52f3c5cd7ea2d478cc99d2c7823517424e178406
734d6e577dbe6142ec7316fed4fc991d86477bb2
refs/heads/master
2020-06-12T07:11:23.551022
2019-06-28T07:39:52
2019-06-28T07:39:52
194,228,522
0
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
#include <iostream> #define NDEBUG #include <GL/freeglut.h> #include <GL/glut.h> #include "cScena.h" #include "cSiatka.h" cScena scena; void resize_binding(int width, int height){ scena.resize(width,height); } void keyboard_bingidng(int key,int,int){ scena.key(key); } void idle_binding(){ scena.idle(); } void mouse_binding(int button, int state, int x, int y) { scena.mouse(button, state, x, y); } void mouse_move_binding(int x, int y) { scena.mouse_move(x, y); } void display_binding(){ scena.display(); } int main(int argc, char *argv[]) { // it's still possible to use console to print messages scena.init(argc,argv,"STATKI PRO"); return 0; }
[ "32577436+pawelbrzozowski@users.noreply.github.com" ]
32577436+pawelbrzozowski@users.noreply.github.com
e2d53c11893e024bf9faefe331ef5251071958a3
d6a38ba3714230d43b9b7c1150fb32479a7103aa
/src/sound/android/android_music_stream.h
fd70e63e9f32589261eedb7ab7c7806f1f6beb25
[]
no_license
andryblack/GHL
be49e5445d40552d9ef308d9505b1f53b3d2ed8c
22cce50e790303db3ddec26259e67a83e6b28f51
refs/heads/master
2021-01-23T09:33:20.286056
2019-08-15T15:11:32
2019-08-24T12:18:24
1,968,260
12
10
null
2018-08-21T17:26:31
2011-06-28T19:12:34
C
UTF-8
C++
false
false
1,566
h
#ifndef _ANDROID_MUSIC_STREAM_ #define _ANDROID_MUSIC_STREAM_ #include "opensl_audio_stream.h" #include "ghl_data_stream.h" #include "../../ghl_ref_counter_impl.h" #include <pthread.h> namespace GHL { class AndroidAssetMusic : public RefCounterImpl<MusicInstance> { private: OpenSLFileAudioStream* m_stream; DataStream* m_ds; public: explicit AndroidAssetMusic(DataStream* ds,OpenSLFileAudioStream* stream); ~AndroidAssetMusic(); virtual void GHL_CALL Play( bool loop ); virtual void GHL_CALL SetVolume( float volume ); virtual void GHL_CALL Stop(); virtual void GHL_CALL Pause(); virtual void GHL_CALL Resume(); virtual void GHL_CALL SetPan( float pan ); virtual void GHL_CALL SetPitch( float pitch ); }; class AndroidDecodeMusic : public RefCounterImpl<MusicInstance>, public OpenSLPCMAudioStream::Holder { private: OpenSLPCMAudioStream* m_channel; SoundDecoder* m_decoder; public: AndroidDecodeMusic(OpenSLPCMAudioStream* channel,SoundDecoder* decoder); ~AndroidDecodeMusic(); // holde virtual void ResetChannel(); virtual void GHL_CALL SetVolume( float vol ); virtual void GHL_CALL SetPan( float pan ); virtual void GHL_CALL SetPitch( float pitch ); virtual void GHL_CALL Stop(); virtual void GHL_CALL Pause(); virtual void GHL_CALL Resume(); virtual void GHL_CALL Play( bool loop ); }; } #endif /*_ANDROID_MUSIC_STREAM_*/
[ "blackicebox@gmail.com" ]
blackicebox@gmail.com
5c238b6f986027206dc71bfdcfe7791571799da3
ac8452e8af11d907a81ef896570776421e96c091
/asg3_test/oc.cc
7086c3e5d57046d90291c6d1b8bae6b47b9dcd42
[]
no_license
konaitor/104a_Pair
890d35750b526a54f6fd009029a54272011ee4aa
ed6d370195a4fca11da0478cb9b4eb4a3a658239
refs/heads/master
2021-01-10T20:43:52.419109
2013-12-07T02:53:44
2013-12-07T02:53:44
13,433,102
0
1
null
null
null
null
UTF-8
C++
false
false
4,171
cc
// $Id: cppstrtok.cc,v 1.2 2013-09-20 19:38:26-07 - - $ // Assignment 3 CS 104a // Authors: Konstantin Litovskiy and Gahl Levy // Users Names: klitovsk and grlevy #include <string> using namespace std; #include <errno.h> #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wait.h> #include <unistd.h> #include "auxlib.h" #include "astree.h" #include "stringset.h" #include "lyutils.h" const string CPP = "/usr/bin/cpp"; const size_t LINESIZE = 1024; FILE* tok_file_out = NULL; extern int yy_flex_debug; extern int yydebug; int main (int argc, char **argv) { int arg; string input_file = ""; string debugFlag = ""; string baseName = ""; string programName = ""; string cppInput = ""; char * fileName; yy_flex_debug = 0; yydebug = 0; //uses getopt to parse the command line arguments while((arg = getopt(argc, argv, "ly@:D:")) != -1){ switch (arg){ case 'l': yy_flex_debug = 1; // used to debug flex break; case 'y': yydebug = 1; // used to debug bison break; case '@': debugFlag = optarg; set_debugflags(debugFlag.c_str()); break; case 'D': cppInput = optarg; break; case ':': // outputs error message to standard error syserrprintf ("Requires Input"); set_exitstatus (1); break; case '?': syserrprintf ("not a valid argument"); set_exitstatus (1); break; } } if(get_exitstatus() != 0){ syserrprintf ("Invalid argument"); }else{ input_file = argv[optind]; // checks for the correct file extension if(input_file.compare(input_file.length()-2, input_file.length(),"oc")!= 0){ syserrprintf ("Unknown file extension"); set_exitstatus (1); }else{ // if the correct file extension was found fileName = argv[optind]; baseName = basename(fileName); programName = baseName.substr(0, baseName.length()-3); } } if(get_exitstatus() == 0){ string command = CPP + " "; if (cppInput.compare("") != 0){ command += "-D " + cppInput + " "; } set_execname(fileName); command += fileName; yyin = popen (command.c_str(), "r"); // opens the pipe if (yyin == NULL) { syserrprintf (command.c_str()); }else { try { string outputFileName = programName + ".tok"; tok_file_out = fopen (outputFileName.c_str(),"w"); yyparse(); // this calls yylex() as needed fclose (tok_file_out); // close the str file } catch (...) { // if there is an error with the file syserrprintf ("File Error"); } string outputFileNameSTR = programName + ".str"; string outputFileNameAST = programName + ".ast"; try { FILE *outputFileSTR = fopen (outputFileNameSTR.c_str(),"w"); // writes the strings to the file dump_stringset (outputFileSTR); fclose (outputFileSTR); // close the str file } catch (...) { // if there is an error with the file string errout = "File Error: Failed to write to " + outputFileNameSTR + "."; syserrprintf (errout.c_str()); } try { FILE *outputFileAST = fopen (outputFileNameAST.c_str(),"w"); // prints the astree to a file dump_astree (outputFileAST, yyparse_astree); fclose (outputFileAST); // close the str file } catch (...) { // if there is an error with the file string errout2 = "File Error: Failed to write to " + outputFileNameAST + "."; syserrprintf (errout2.c_str()); } } } else{ syserrprintf ("Invalid Arguments"); } return get_exitstatus(); }
[ "konstantin.litov@gmail.com" ]
konstantin.litov@gmail.com
9eab765871c7d00a53d68e28fbab5dbc9a9a1676
c52d947f3af28925d5579397607b84e5af53cc4c
/src/hydro/hydro_diffusion/viscosity.cpp
e3d369e03a8193c070503c84b1730d6a44a60a97
[ "BSD-3-Clause" ]
permissive
michaeljennings11/Athena_Thermal_Instability
becca9a622b3ad1404d6d085d04ba6df3368f879
7f647e8640e35ab3dce1273ec1bbc90bf4d8901b
refs/heads/master
2022-11-05T17:47:45.858186
2020-06-27T20:02:04
2020-06-27T20:02:04
260,109,765
2
0
null
null
null
null
UTF-8
C++
false
false
48,832
cpp
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== // \brief functions to calculate viscous stresses // Athena++ headers #include "hydro_diffusion.hpp" #include "../../athena.hpp" #include "../../athena_arrays.hpp" #include "../../mesh/mesh.hpp" #include "../../coordinates/coordinates.hpp" #include "../hydro.hpp" #include "../../eos/eos.hpp" // These constants are in cgs */ static const Real mbar = (1.27)*(1.6733e-24); // mean molecular weight static const Real kb = 1.380658e-16; // Boltzmann constant static const Real gam = 5./3.; // adiabatic index static Real limiter2(const Real A, const Real B); static Real FourLimiter(const Real A, const Real B, const Real C, const Real D); static Real vanleer (const Real A, const Real B); static Real minmod(const Real A, const Real B); static Real mc(const Real A, const Real B); //---------------------------------------------------------------------------------------- //! \fn void HydroDiffusion::ViscousFlux_iso // \brief Calculate isotropic viscous stress as fluxes void HydroDiffusion::ViscousFlux_iso(const AthenaArray<Real> &prim, const AthenaArray<Real> &cons, AthenaArray<Real> *visflx) { AthenaArray<Real> &x1flux=visflx[X1DIR]; AthenaArray<Real> &x2flux=visflx[X2DIR]; AthenaArray<Real> &x3flux=visflx[X3DIR]; int il, iu, jl, ju, kl, ku; int is = pmb_->is; int js = pmb_->js; int ks = pmb_->ks; int ie = pmb_->ie; int je = pmb_->je; int ke = pmb_->ke; Real nu1, denf, flx1, flx2, flx3; Real nuiso2 = - TWO_3RD; Divv(prim, divv_); // Calculate the flux across each face. // i-direction jl=js, ju=je, kl=ks, ku=ke; if (MAGNETIC_FIELDS_ENABLED) { if (pmb_->block_size.nx2 > 1) { if (pmb_->block_size.nx3 == 1) // 2D MHD limits jl=js-1, ju=je+1, kl=ks, ku=ke; else // 3D MHD limits jl=js-1, ju=je+1, kl=ks-1, ku=ke+1; } } for (int k=kl; k<=ku; ++k) { for (int j=jl; j<=ju; ++j) { FaceXdx(k,j,is,ie+1,prim,fx_); FaceXdy(k,j,is,ie+1,prim,fy_); FaceXdz(k,j,is,ie+1,prim,fz_); for (int i=is; i<=ie+1; ++i) { nu1 = 0.5*(nu(ISO,k,j,i) + nu(ISO,k,j,i-1)); denf = 1.; //0.5*(prim(IDN,k,j,i) + prim(IDN,k,j,i-1)); flx1 = -denf*nu1*(fx_(i) + nuiso2*0.5*(divv_(k,j,i) + divv_(k,j,i-1))); flx2 = -denf*nu1*fy_(i); flx3 = -denf*nu1*fz_(i); x1flux(IM1,k,j,i) += flx1; x1flux(IM2,k,j,i) += flx2; x1flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x1flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i-1) + prim(IM1,k,j,i))*flx1 + (prim(IM2,k,j,i-1) + prim(IM2,k,j,i))*flx2 + (prim(IM3,k,j,i-1) + prim(IM3,k,j,i))*flx3); } } } // j-direction il=is, iu=ie, kl=ks, ku=ke; if (MAGNETIC_FIELDS_ENABLED) { if (pmb_->block_size.nx3 == 1) // 2D MHD limits il=is-1, iu=ie+1, kl=ks, ku=ke; else // 3D MHD limits il=is-1, iu=ie+1, kl=ks-1, ku=ke+1; } if (pmb_->block_size.nx2 > 1) { // modify x2flux for 2D or 3D for (int k=kl; k<=ku; ++k) { for (int j=js; j<=je+1; ++j) { // compute fluxes FaceYdx(k,j,is,ie,prim,fx_); FaceYdy(k,j,is,ie,prim,fy_); FaceYdz(k,j,is,ie,prim,fz_); // store fluxes for(int i=il; i<=iu; i++) { nu1 = 0.5*(nu(ISO,k,j,i) + nu(ISO,k,j-1,i)); denf = 1.; //0.5*(prim(IDN,k,j-1,i)+ prim(IDN,k,j,i)); flx1 = -denf*nu1*fx_(i); flx2 = -denf*nu1*(fy_(i) + nuiso2*0.5*(divv_(k,j-1,i) + divv_(k,j,i))); flx3 = -denf*nu1*fz_(i); x2flux(IM1,k,j,i) += flx1; x2flux(IM2,k,j,i) += flx2; x2flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x2flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j-1,i))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j-1,i))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j-1,i))*flx3); } } } } else { // modify x2flux for 1D // compute fluxes FaceYdx(ks,js,is,ie,prim,fx_); FaceYdy(ks,js,is,ie,prim,fy_); FaceYdz(ks,js,is,ie,prim,fz_); // store fluxes for(int i=il; i<=iu; i++) { nu1 = nu(ISO,ks,js,i); denf = 1.;//prim(IDN,ks,js,i); flx1 = -denf*nu1*fx_(i); flx2 = -denf*nu1*(fy_(i) + nuiso2*divv_(ks,js,i)); flx3 = -denf*nu1*fz_(i); x2flux(IM1,ks,js,i) += flx1; x2flux(IM2,ks,js,i) += flx2; x2flux(IM3,ks,js,i) += flx3; if (NON_BAROTROPIC_EOS) x2flux(IEN,ks,js,i) += prim(IM1,ks,js,i)*flx1 + prim(IM2,ks,js,i)*flx2 + prim(IM3,ks,js,i)*flx3; } for(int i=il; i<=iu; i++) { x2flux(IM1,ks,je+1,i) = x2flux(IM1,ks,js,i); x2flux(IM2,ks,je+1,i) = x2flux(IM2,ks,js,i); x2flux(IM3,ks,je+1,i) = x2flux(IM3,ks,js,i); if (NON_BAROTROPIC_EOS) x2flux(IEN,ks,je+1,i) = x2flux(IEN,ks,js,i); } } // k-direction // set the loop limits il=is, iu=ie, jl=js, ju=je; if (MAGNETIC_FIELDS_ENABLED) { if (pmb_->block_size.nx2 > 1) // 2D or 3D MHD limits il=is-1, iu=ie+1, jl=js-1, ju=je+1; else // 1D MHD limits il=is-1, iu=ie+1; } if (pmb_->block_size.nx3 > 1) { // modify x3flux for 3D for (int k=ks; k<=ke+1; ++k) { for (int j=jl; j<=ju; ++j) { // compute fluxes FaceZdx(k,j,is,ie,prim,fx_); FaceZdy(k,j,is,ie,prim,fy_); FaceZdz(k,j,is,ie,prim,fz_); // store fluxes for(int i=il; i<=iu; i++) { nu1 = 0.5*(nu(ISO,k,j,i) + nu(ISO,k-1,j,i)); denf = 1.;//0.5*(prim(IDN,k-1,j,i) + prim(IDN,k,j,i)); flx1 = -denf*nu1*fx_(i); flx2 = -denf*nu1*fy_(i); flx3 = -denf*nu1*(fz_(i) + nuiso2*0.5*(divv_(k-1,j,i) + divv_(k,j,i))); x3flux(IM1,k,j,i) += flx1; x3flux(IM2,k,j,i) += flx2; x3flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x3flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k-1,j,i))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k-1,j,i))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k-1,j,i))*flx3); } } } } else { // modify x2flux for 1D or 2D for (int j=jl; j<=ju; ++j) { // compute fluxes FaceZdx(ks,j,is,ie,prim,fx_); FaceZdy(ks,j,is,ie,prim,fy_); FaceZdz(ks,j,is,ie,prim,fz_); // store fluxes for(int i=il; i<=iu; i++) { nu1 = nu(ISO,ks,j,i); denf = 1.;//prim(IDN,ks,j,i); flx1 = -denf*nu1*fx_(i); flx2 = -denf*nu1*fy_(i); flx3 = -denf*nu1*(fz_(i) + nuiso2*divv_(ks,j,i)); x3flux(IM1,ks,j,i) += flx1; x3flux(IM2,ks,j,i) += flx2; x3flux(IM3,ks,j,i) += flx3; x3flux(IM1,ke+1,j,i) = x3flux(IM1,ks,j,i); x3flux(IM2,ke+1,j,i) = x3flux(IM2,ks,j,i); x3flux(IM3,ke+1,j,i) = x3flux(IM3,ks,j,i); if (NON_BAROTROPIC_EOS) { x3flux(IEN,ks,j,i) += prim(IM1,ks,j,i)*flx1 + prim(IM2,ks,j,i)*flx2 + prim(IM3,ks,j,i)*flx3; x3flux(IEN,ke+1,j,i) = x3flux(IEN,ks,j,i); } } } } return; } //------------------------------------------------------------------------------------- // Calculate divergence of momenta void HydroDiffusion::Divv(const AthenaArray<Real> &prim, AthenaArray<Real> &divv) { int is = pmb_->is; int js = pmb_->js; int ks = pmb_->ks; int ie = pmb_->ie; int je = pmb_->je; int ke = pmb_->ke; int il = is-1; int iu = ie+1; int jl, ju, kl, ku; Real area_p1, area; Real vel_p1, vel; if (pmb_->block_size.nx2 == 1) // 1D jl=js, ju=je, kl=ks, ku=ke; else if (pmb_->block_size.nx3 == 1) // 2D jl=js-1, ju=je+1, kl=ks, ku=ke; else // 3D jl=js-1, ju=je+1, kl=ks-1, ku=ke+1; for (int k=kl; k<=ku; ++k) { for (int j=jl; j<=ju; ++j) { // calculate x1-flux divergence pmb_->pcoord->Face1Area(k, j, il, iu+1, x1area_); #pragma omp simd for (int i=il; i<=iu; ++i) { area_p1 = x1area_(i+1); area = x1area_(i); vel_p1 = 0.5*(prim(IM1,k,j,i+1) + prim(IM1,k,j,i )); vel = 0.5*(prim(IM1,k,j,i ) + prim(IM1,k,j,i-1)); divv(k,j,i) = area_p1*vel_p1 - area*vel; } // calculate x2-flux divergnece if (pmb_->block_size.nx2 > 1) { pmb_->pcoord->Face2Area(k, j , il, iu, x2area_); pmb_->pcoord->Face2Area(k, j+1, il, iu, x2area_p1_); #pragma omp simd for (int i=il; i<=iu; ++i) { area_p1 = x2area_p1_(i); area = x2area_(i); vel_p1 = 0.5*(prim(IM2,k,j+1,i) + prim(IM2,k,j ,i)); vel = 0.5*(prim(IM2,k,j ,i) + prim(IM2,k,j-1,i)); divv(k,j,i) += area_p1*vel_p1 - area*vel; } } if (pmb_->block_size.nx3 > 1) { pmb_->pcoord->Face3Area(k , j, il, iu, x3area_); pmb_->pcoord->Face3Area(k+1, j, il, iu, x3area_p1_); #pragma omp simd for (int i=il; i<=iu; ++i) { area_p1 = x3area_p1_(i); area = x3area_(i); vel_p1 = 0.5*(prim(IM3,k+1,j,i) + prim(IM3, k ,j,i)); vel = 0.5*(prim(IM3,k ,j,i) + prim(IM3, k-1,j,i)); divv(k,j,i) += area_p1*vel_p1 - area*vel; } } pmb_->pcoord->CellVolume(k,j,il,iu,vol_); #pragma omp simd for (int i=il; i<=iu; ++i) { divv(k,j,i) = divv(k,j,i)/vol_(i); } } } return; } // v_{x1;x1} covariant derivative at x1 interface void HydroDiffusion::FaceXdx(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = 2.0*(prim(IM1,k,j,i) - prim(IM1,k,j,i-1)) / pco_->dx1v(i-1); } return; } // v_{x2;x1}+v_{x1;x2} covariant derivative at x1 interface void HydroDiffusion::FaceXdy(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx2 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h2f(i) * (prim(IM2,k,j,i)/pco_->h2v(i) - prim(IM2,k,j,i-1)/pco_->h2v(i-1)) / pco_->dx1v(i-1) // KGF: add the off-centered quantities first to preserve FP symmetry + 0.5*( (prim(IM1,k,j+1,i) + prim(IM1,k,j+1,i-1)) - (prim(IM1,k,j-1,i) + prim(IM1,k,j-1,i-1)) ) / pco_->h2f(i) / (pco_->dx2v(j-1) + pco_->dx2v(j)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h2f(i) * ( prim(IM2,k,j,i)/pco_->h2v(i) - prim(IM2,k,j,i-1)/pco_->h2v(i-1) ) / pco_->dx1v(i-1); } } return; } // v_{x3;x1}+v_{x1;x3} covariant derivative at x1 interface void HydroDiffusion::FaceXdz(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx3 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h31f(i) * (prim(IM3,k,j,i)/pco_->h31v(i) - prim(IM3,k,j,i-1)/pco_->h31v(i-1)) / pco_->dx1v(i-1) // KGF: add the off-centered quantities first to preserve FP symmetry + 0.5*( (prim(IM1,k+1,j,i) + prim(IM1,k+1,j,i-1)) - (prim(IM1,k-1,j,i) + prim(IM1,k-1,j,i-1)) ) / pco_->h31f(i)/pco_->h32v(j) // note, more terms than FaceXdy() line / (pco_->dx3v(k-1) + pco_->dx3v(k)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) len(i) = pco_->h31f(i) * ( prim(IM3,k,j,i)/pco_->h31v(i) - prim(IM3,k,j,i-1)/pco_->h31v(i-1) ) / pco_->dx1v(i-1); } return; } // v_{x1;x2}+v_{x2;x1} covariant derivative at x2 interface void HydroDiffusion::FaceYdx(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx2 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = (prim(IM1,k,j,i) - prim(IM1,k,j-1,i)) / pco_->h2v(i) / pco_->dx2v(j-1) + pco_->h2v(i)*0.5*( (prim(IM2,k,j,i+1) + prim(IM2,k,j-1,i+1)) /pco_->h2v(i+1) - (prim(IM2,k,j,i-1) + prim(IM2,k,j-1,i-1)) /pco_->h2v(i-1) ) / (pco_->dx1v(i-1) + pco_->dx1v(i)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h2v(i) * ( prim(IM2,k,j,i+1)/pco_->h2v(i+1) - prim(IM2,k,j,i-1)/pco_->h2v(i-1) ) / (pco_->dx1v(i-1) + pco_->dx1v(i)); } } return; } // v_{x2;x2} covariant derivative at x2 interface void HydroDiffusion::FaceYdy(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx2 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = 2.0*(prim(IM2,k,j,i) - prim(IM2,k,j-1,i)) / pco_->h2v(i) / pco_->dx2v(j-1) + (prim(IM1,k,j,i) + prim(IM1,k,j-1,i)) / pco_->h2v(i) * pco_->dh2vd1(i); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) len(i) = 2.0*prim(IM1,k,j,i) / pco_->h2v(i) * pco_->dh2vd1(i); } return; } // v_{x3;x2}+v_{x2;x3} covariant derivative at x2 interface void HydroDiffusion::FaceYdz(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx3 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h32f(j) * ( prim(IM3,k,j,i)/pco_->h32v(j) - prim(IM3,k,j-1,i)/pco_->h32v(j-1) ) / pco_->h2v(i) / pco_->dx2v(j-1) // KGF: add the off-centered quantities first to preserve FP symmetry + 0.5*( (prim(IM2,k+1,j,i) + prim(IM2,k+1,j-1,i)) - (prim(IM2,k-1,j,i) + prim(IM2,k-1,j-1,i)) ) / pco_->h31v(i) / pco_->h32f(j) / (pco_->dx3v(k-1) + pco_->dx3v(k)); } } else if (pmb_->block_size.nx2 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h32f(j) * ( prim(IM3,k,j,i)/pco_->h32v(j) - prim(IM3,k,j-1,i)/pco_->h32v(j-1) ) / pco_->h2v(i) / pco_->dx2v(j-1); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) len(i) = 0.0; } return; } // v_{x1;x3}+v_{x3;x1} covariant derivative at x3 interface void HydroDiffusion::FaceZdx(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx3 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = (prim(IM1,k,j,i) - prim(IM1,k-1,j,i))/pco_->dx3v(k-1) + 0.5*pco_->h31v(i)*( (prim(IM3,k,j,i+1) + prim(IM3,k-1,j,i+1))/pco_->h31v(i+1) -(prim(IM3,k,j,i-1) + prim(IM3,k-1,j,i-1))/pco_->h31v(i-1) ) / (pco_->dx1v(i-1) + pco_->dx1v(i)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h31v(i) * ( prim(IM3,k,j,i+1)/pco_->h31v(i+1) - prim(IM3,k,j,i-1)/pco_->h31v(i-1) ) / (pco_->dx1v(i-1) + pco_->dx1v(i)); } } return; } // v_{x2;x3}+v_{x3;x2} covariant derivative at x3 interface void HydroDiffusion::FaceZdy(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx3 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = (prim(IM2,k,j,i) - prim(IM2,k-1,j,i)) / pco_->h31v(i) / pco_->h32v(j) / pco_->dx3v(k-1) + 0.5*pco_->h32v(j) * ( (prim(IM3,k,j+1,i) + prim(IM3,k-1,j+1,i))/pco_->h32v(j+1) -(prim(IM3,k,j-1,i) + prim(IM3,k-1,j-1,i))/pco_->h32v(j-1) ) / pco_->h2v(i) / (pco_->dx2v(j-1) + pco_->dx2v(j)); } } else if (pmb_->block_size.nx2 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = pco_->h32v(j) * ( prim(IM3,k,j+1,i)/pco_->h32v(j+1) - prim(IM3,k,j-1,i)/pco_->h32v(j-1) ) / pco_->h2v(i) / (pco_->dx2v(j-1) + pco_->dx2v(j)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) len(i) = 0.0; } return; } // v_{x3;x3} covariant derivative at x3 interface void HydroDiffusion::FaceZdz(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &prim, AthenaArray<Real> &len) { if (pmb_->block_size.nx3 > 1) { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = 2.0*(prim(IM3,k,j,i) - prim(IM3,k-1,j,i)) / pco_->dx3v(k-1) / pco_->h31v(i) / pco_->h32v(j) + ((prim(IM1,k,j,i) + prim(IM1,k-1,j,i)) * pco_->dh31vd1(i)/pco_->h31v(i)) + ((prim(IM2,k,j,i) + prim(IM2,k-1,j,i)) * pco_->dh32vd2(j)/pco_->h32v(j)/pco_->h2v(i)); } } else { #pragma omp simd for (int i=il; i<=iu; ++i) { len(i) = 2.0*prim(IM1,k,j,i)*pco_->dh31vd1(i)/pco_->h31v(i) + 2.0*prim(IM2,k,j,i)*pco_->dh32vd2(j)/pco_->h32v(j)/pco_->h2v(i); } } return; } //---------------------------------------------------------------------------------------- //! \fn void HydroDiffusion::ViscousFluxAniso // \brief Calculate anisotropic viscous stress as fluxes void HydroDiffusion::ViscousFlux_aniso(const AthenaArray<Real> &prim, const AthenaArray<Real> &cons, AthenaArray<Real> *visflx, const FaceField &b, const AthenaArray<Real> &bcc) { const bool f2 = pmb_->block_size.nx2 > 1; const bool f3 = pmb_->block_size.nx3 > 1; AthenaArray<Real> &x1flux=visflx[X1DIR]; AthenaArray<Real> &x2flux=visflx[X2DIR]; AthenaArray<Real> &x3flux=visflx[X3DIR]; int il, iu, jl, ju, kl, ku; int is = pmb_->is; int js = pmb_->js; int ks = pmb_->ks; int ie = pmb_->ie; int je = pmb_->je; int ke = pmb_->ke; // Calculate the flux across each face. // ----------------------------------------------------------------- // // i direction jl=js, ju=je, kl=ks, ku=ke; if(f2) { if(f3) // 3D jl=js-1, ju=je+1, kl=ks-1, ku=ke+1; else // 2D jl=js-1, ju=je+1, kl=ks, ku=ke; } for (int k=kl; k<=ku; ++k) { for (int j=jl; j<=ju; ++j) { if (f3) { #pragma omp simd for (int i=is; i<=ie+1; ++i) { Real bx = b.x1f(k,j,i); Real by = 0.5*(bcc(IB2,k,j,i) + bcc(IB2,k,j,i-1)); Real bz = 0.5*(bcc(IB3,k,j,i) + bcc(IB3,k,j,i-1)); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 // x1 gradients Real dx = pco_->dx1v(i-1); // Gradient dVx/dx at i-1/2, j, k Real dvxdx = (prim(IM1,k,j,i) - prim(IM1,k,j,i-1)) / dx; // Gradient dVy/dx at i-1/2, j, k Real dvydx = (prim(IM2,k,j,i) - prim(IM2,k,j,i-1)) / dx; // Gradient dVz/dx at i-1/2, j, k Real dvzdx = (prim(IM3,k,j,i) - prim(IM3,k,j,i-1)) / dx; // x2 gradients Real dy = 0.5*(pco_->dx2v(j-1) + pco_->dx2v(j)); // Gradient dVx/dy at i-1/2, j, k Real dvxdy = FourLimiter(prim(IM1,k,j+1,i ) - prim(IM1,k,j ,i ), prim(IM1,k,j ,i ) - prim(IM1,k,j-1,i ), prim(IM1,k,j+1,i-1) - prim(IM1,k,j ,i-1), prim(IM1,k,j ,i-1) - prim(IM1,k,j-1,i-1)); dvxdy /= dy; // Gradient dVy/dy at i-1/2, j, k Real dvydy = FourLimiter(prim(IM2,k,j+1,i ) - prim(IM2,k,j ,i ), prim(IM2,k,j ,i ) - prim(IM2,k,j-1,i ), prim(IM2,k,j+1,i-1) - prim(IM2,k,j ,i-1), prim(IM2,k,j ,i-1) - prim(IM2,k,j-1,i-1)); dvydy /= dy; // Gradient dVz/dy at i-1/2, j, k Real dvzdy = FourLimiter(prim(IM3,k,j+1,i ) - prim(IM3,k,j ,i ), prim(IM3,k,j ,i ) - prim(IM3,k,j-1,i ), prim(IM3,k,j+1,i-1) - prim(IM3,k,j ,i-1), prim(IM3,k,j ,i-1) - prim(IM3,k,j-1,i-1)); dvzdy /= dy; // x3 gradients Real dz = 0.5*(pco_->dx3v(k-1) + pco_->dx3v(k)); // Gradient dVx/dz at i-1/2, j, k Real dvxdz = FourLimiter(prim(IM1,k+1,j,i ) - prim(IM1,k ,j,i ), prim(IM1,k ,j,i ) - prim(IM1,k-1,j,i ), prim(IM1,k+1,j,i-1) - prim(IM1,k ,j,i-1), prim(IM1,k ,j,i-1) - prim(IM1,k-1,j,i-1)); dvxdz /=dz; // Gradient dVy/dz at i-1/2, j, k Real dvydz = FourLimiter(prim(IM2,k+1,j,i ) - prim(IM2,k ,j,i ), prim(IM2,k ,j,i ) - prim(IM2,k-1,j,i ), prim(IM2,k+1,j,i-1) - prim(IM2,k ,j,i-1), prim(IM2,k ,j,i-1) - prim(IM2,k-1,j,i-1)); dvydz /=dz; // Gradient dVx/dz at i-1/2, j, k Real dvzdz = FourLimiter(prim(IM3,k+1,j,i ) - prim(IM3,k ,j,i ), prim(IM3,k ,j,i ) - prim(IM3,k-1,j,i ), prim(IM3,k+1,j,i-1) - prim(IM3,k ,j,i-1), prim(IM3,k ,j,i-1) - prim(IM3,k-1,j,i-1)); dvzdz /=dz; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv += by*(bx*dvxdy + by*dvydy + bz*dvzdy); bbdv += bz*(bx*dvxdz + by*dvydz + bz*dvzdz); bbdv /= bsq; // NB: nu_aniso is a kinematic viscosity, since we multiply by density Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k,j,i-1)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k,j,i-1)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx + dvydy + dvzdz)); // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; // NB: Flux sign opposite to old athena Real flx1 = -delta_p*(bx*bx/bsq - ONE_3RD); Real flx2 = -delta_p*(bx*by/bsq); Real flx3 = -delta_p*(bx*bz/bsq); x1flux(IM1,k,j,i) += flx1; x1flux(IM2,k,j,i) += flx2; x1flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x1flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j,i-1))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j,i-1))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j,i-1))*flx3); } } else if (f2){ // 2D #pragma omp simd for (int i=is; i<=ie+1; ++i) { Real bx = b.x1f(k,j,i); Real by = 0.5*(bcc(IB2,k,j,i) + bcc(IB2,k,j,i-1)); Real bz = 0.5*(bcc(IB3,k,j,i) + bcc(IB3,k,j,i-1)); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 // x1 gradients Real dx = pco_->dx1v(i-1); // Gradient dVx/dx at i-1/2, j, k Real dvxdx = (prim(IM1,k,j,i) - prim(IM1,k,j,i-1)) / dx; // Gradient dVy/dx at i-1/2, j, k Real dvydx = (prim(IM2,k,j,i) - prim(IM2,k,j,i-1)) / dx; // Gradient dVz/dx at i-1/2, j, k Real dvzdx = (prim(IM3,k,j,i) - prim(IM3,k,j,i-1)) / dx; // x2 gradients Real dy = 0.5*(pco_->dx2v(j-1) + pco_->dx2v(j)); // Gradient dVx/dy at i-1/2, j, k Real dvxdy = FourLimiter(prim(IM1,k,j+1,i ) - prim(IM1,k,j ,i ), prim(IM1,k,j ,i ) - prim(IM1,k,j-1,i ), prim(IM1,k,j+1,i-1) - prim(IM1,k,j ,i-1), prim(IM1,k,j ,i-1) - prim(IM1,k,j-1,i-1)); dvxdy /= dy; // Gradient dVy/dy at i-1/2, j, k Real dvydy = FourLimiter(prim(IM2,k,j+1,i ) - prim(IM2,k,j ,i ), prim(IM2,k,j ,i ) - prim(IM2,k,j-1,i ), prim(IM2,k,j+1,i-1) - prim(IM2,k,j ,i-1), prim(IM2,k,j ,i-1) - prim(IM2,k,j-1,i-1)); dvydy /= dy; // Gradient dVz/dy at i-1/2, j, k Real dvzdy = FourLimiter(prim(IM3,k,j+1,i ) - prim(IM3,k,j ,i ), prim(IM3,k,j ,i ) - prim(IM3,k,j-1,i ), prim(IM3,k,j+1,i-1) - prim(IM3,k,j ,i-1), prim(IM3,k,j ,i-1) - prim(IM3,k,j-1,i-1)); dvzdy /= dy; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv += by*(bx*dvxdy + by*dvydy + bz*dvzdy); bbdv /= bsq; // NB: nu_aniso is a kinematic viscosity, since we multiply by density Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k,j,i-1)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k,j,i-1)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx + dvydy)); // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; // NB: Flux sign opposite to old athena Real flx1 = -delta_p*(bx*bx/bsq - ONE_3RD); Real flx2 = -delta_p*(bx*by/bsq); Real flx3 = -delta_p*(bx*bz/bsq); x1flux(IM1,k,j,i) += flx1; x1flux(IM2,k,j,i) += flx2; x1flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x1flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j,i-1))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j,i-1))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j,i-1))*flx3); } } else { // 1D #pragma omp simd for (int i=is; i<=ie+1; ++i) { Real bx = b.x1f(k,j,i); Real by = 0.5*(bcc(IB2,k,j,i) + bcc(IB2,k,j,i-1)); Real bz = 0.5*(bcc(IB3,k,j,i) + bcc(IB3,k,j,i-1)); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 // x1 gradients Real dx = pco_->dx1v(i-1); // Gradient dVx/dx at i-1/2, j, k Real dvxdx = (prim(IM1,k,j,i) - prim(IM1,k,j,i-1)) / dx; // Gradient dVy/dx at i-1/2, j, k Real dvydx = (prim(IM2,k,j,i) - prim(IM2,k,j,i-1)) / dx; // Gradient dVz/dx at i-1/2, j, k Real dvzdx = (prim(IM3,k,j,i) - prim(IM3,k,j,i-1)) / dx; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv /= bsq; // NB: nu_aniso is a kinematic viscosity, since we multiply by density Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k,j,i-1)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k,j,i-1)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx)); //std::cout << "### WARNING in MIRROR" << std::endl; // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; // NB: Flux sign opposite to old athena Real flx1 = -delta_p*(bx*bx/bsq - ONE_3RD); Real flx2 = -delta_p*(bx*by/bsq); Real flx3 = -delta_p*(bx*bz/bsq); x1flux(IM1,k,j,i) += flx1; x1flux(IM2,k,j,i) += flx2; x1flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x1flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j,i-1))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j,i-1))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j,i-1))*flx3); } } }} // ----------------------------------------------------------------- // // j direction if(f3) // 3D il=is-1, iu=ie+1, kl=ks-1, ku=ke+1; else // 2D il=is-1, iu=ie+1, kl=ks, ku=ke; if (f2) { for (int k=kl; k<=ku; ++k) { for (int j=js; j<=je+1; ++j) { if (f3){ // 3D #pragma omp simd for(int i=il; i<=iu; i++) { Real bx = 0.5*(bcc(IB1,k,j,i) + bcc(IB1,k,j-1,i)); Real by = b.x2f(k,j,i); Real bz = 0.5*(bcc(IB3,k,j,i) + bcc(IB3,k,j-1,i)); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 Real dx = 0.5*(pco_->dx1v(i-1) + pco_->dx1v(i)); // Gradient dVx/dx at i, j-1/2, k Real dvxdx = FourLimiter(prim(IM1,k,j ,i+1) - prim(IM1,k,j ,i ), prim(IM1,k,j ,i ) - prim(IM1,k,j ,i-1), prim(IM1,k,j-1,i+1) - prim(IM1,k,j-1,i ), prim(IM1,k,j-1,i ) - prim(IM1,k,j-1,i-1)); dvxdx /= dx; // Gradient dVx/dx at i, j-1/2, k Real dvydx = FourLimiter(prim(IM2,k,j ,i+1) - prim(IM2,k,j ,i ), prim(IM2,k,j ,i ) - prim(IM2,k,j ,i-1), prim(IM2,k,j-1,i+1) - prim(IM2,k,j-1,i ), prim(IM2,k,j-1,i ) - prim(IM2,k,j-1,i-1)); dvydx /= dx; // Gradient dVx/dx at i, j-1/2, k Real dvzdx = FourLimiter(prim(IM3,k,j ,i+1) - prim(IM3,k,j ,i ), prim(IM3,k,j ,i ) - prim(IM3,k,j ,i-1), prim(IM3,k,j-1,i+1) - prim(IM3,k,j-1,i ), prim(IM3,k,j-1,i ) - prim(IM3,k,j-1,i-1)); dvzdx /= dx; Real dy = pco_->dx2v(j-1); // Gradient dVx/dy at i, j-1/2, k Real dvxdy = (prim(IM1,k,j,i) - prim(IM1,k,j-1,i)) / dy; // Gradient dVx/dy at i, j-1/2, k Real dvydy = (prim(IM2,k,j,i) - prim(IM2,k,j-1,i)) / dy; // Gradient dVx/dy at i, j-1/2, k Real dvzdy = (prim(IM3,k,j,i) - prim(IM3,k,j-1,i)) / dy; Real dz = 0.5*(pco_->dx3v(k-1) + pco_->dx3v(k)); // Gradient dVx/dz at i, j-1/2, k Real dvxdz = FourLimiter(prim(IM1,k+1,j ,i) - prim(IM1,k ,j ,i), prim(IM1,k ,j ,i) - prim(IM1,k-1,j ,i), prim(IM1,k+1,j-1,i) - prim(IM1,k ,j-1,i), prim(IM1,k ,j-1,i) - prim(IM1,k-1,j-1,i)); dvxdz /= dz; // Gradient dVx/dz at i, j-1/2, k Real dvydz = FourLimiter(prim(IM2,k+1,j ,i) - prim(IM2,k ,j ,i), prim(IM2,k ,j ,i) - prim(IM2,k-1,j ,i), prim(IM2,k+1,j-1,i) - prim(IM2,k ,j-1,i), prim(IM2,k ,j-1,i) - prim(IM2,k-1,j-1,i)); dvydz /= dz; // Gradient dVx/dz at i, j-1/2, k Real dvzdz = FourLimiter(prim(IM3,k+1,j ,i) - prim(IM3,k ,j ,i), prim(IM3,k ,j ,i) - prim(IM3,k-1,j ,i), prim(IM3,k+1,j-1,i) - prim(IM3,k ,j-1,i), prim(IM3,k ,j-1,i) - prim(IM3,k-1,j-1,i)); dvzdz /= dz; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv += by*(bx*dvxdy + by*dvydy + bz*dvzdy); bbdv += bz*(bx*dvxdz + by*dvydz + bz*dvzdz); bbdv /= bsq; Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k,j-1,i)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k,j-1,i)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx + dvydy + dvzdz)); // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; Real flx1 = -delta_p*(by*bx/bsq); Real flx2 = -delta_p*(by*by/bsq - ONE_3RD); Real flx3 = -delta_p*(by*bz/bsq); x2flux(IM1,k,j,i) += flx1; x2flux(IM2,k,j,i) += flx2; x2flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x2flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j-1,i))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j-1,i))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j-1,i))*flx3); } } else { #pragma omp simd for(int i=il; i<=iu; i++) { Real bx = 0.5*(bcc(IB1,k,j,i) + bcc(IB1,k,j-1,i)); Real by = b.x2f(k,j,i); Real bz = 0.5*(bcc(IB3,k,j,i) + bcc(IB3,k,j-1,i)); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 Real dx = 0.5*(pco_->dx1v(i-1) + pco_->dx1v(i)); // Gradient dVx/dx at i, j-1/2, k Real dvxdx = FourLimiter(prim(IM1,k,j ,i+1) - prim(IM1,k,j ,i ), prim(IM1,k,j ,i ) - prim(IM1,k,j ,i-1), prim(IM1,k,j-1,i+1) - prim(IM1,k,j-1,i ), prim(IM1,k,j-1,i ) - prim(IM1,k,j-1,i-1)); dvxdx /= dx; // Gradient dVx/dx at i, j-1/2, k Real dvydx = FourLimiter(prim(IM2,k,j ,i+1) - prim(IM2,k,j ,i ), prim(IM2,k,j ,i ) - prim(IM2,k,j ,i-1), prim(IM2,k,j-1,i+1) - prim(IM2,k,j-1,i ), prim(IM2,k,j-1,i ) - prim(IM2,k,j-1,i-1)); dvydx /= dx; // Gradient dVx/dx at i, j-1/2, k Real dvzdx = FourLimiter(prim(IM3,k,j ,i+1) - prim(IM3,k,j ,i ), prim(IM3,k,j ,i ) - prim(IM3,k,j ,i-1), prim(IM3,k,j-1,i+1) - prim(IM3,k,j-1,i ), prim(IM3,k,j-1,i ) - prim(IM3,k,j-1,i-1)); dvzdx /= dx; Real dy = pco_->dx2v(j-1); // Gradient dVx/dy at i, j-1/2, k Real dvxdy = (prim(IM1,k,j,i) - prim(IM1,k,j-1,i)) / dy; // Gradient dVx/dy at i, j-1/2, k Real dvydy = (prim(IM2,k,j,i) - prim(IM2,k,j-1,i)) / dy; // Gradient dVx/dy at i, j-1/2, k Real dvzdy = (prim(IM3,k,j,i) - prim(IM3,k,j-1,i)) / dy; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv += by*(bx*dvxdy + by*dvydy + bz*dvzdy); bbdv /= bsq; Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k,j-1,i)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k,j-1,i)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx + dvydy)); // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; Real flx1 = -delta_p*(by*bx/bsq); Real flx2 = -delta_p*(by*by/bsq - ONE_3RD); Real flx3 = -delta_p*(by*bz/bsq); x2flux(IM1,k,j,i) += flx1; x2flux(IM2,k,j,i) += flx2; x2flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x2flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k,j-1,i))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k,j-1,i))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k,j-1,i))*flx3); } } }} } // 1D Do nothing // ----------------------------------------------------------------- // // k direction il=is-1, iu=ie+1, jl=js-1, ju=je+1; if (f3) { // 3D for (int k=ks; k<=ke+1; ++k) { for (int j=jl; j<=ju; ++j) { #pragma omp simd for(int i=il; i<=iu; i++) { Real bx = 0.5*(bcc(IB1,k,j,i) + bcc(IB1,k-1,j,i)); Real by = 0.5*(bcc(IB2,k,j,i) + bcc(IB2,k-1,j,i)); Real bz = b.x3f(k,j,i); Real bsq = bx*bx + by*by + bz*bz; bsq = std::max(bsq,TINY_NUMBER); // In case bsq=0 Real dx = 0.5*(pco_->dx1v(i-1) + pco_->dx1v(i)); // Gradient dVx/dx at i, j, k-1/2 Real dvxdx = FourLimiter(prim(IM1,k ,j,i+1) - prim(IM1,k ,j,i ), prim(IM1,k ,j,i ) - prim(IM1,k ,j,i-1), prim(IM1,k-1,j,i+1) - prim(IM1,k-1,j,i ), prim(IM1,k-1,j,i ) - prim(IM1,k-1,j,i-1)); dvxdx /= dx; /// Gradient dVz/dx at i, j, k-1/2 Real dvydx = FourLimiter(prim(IM2,k ,j,i+1) - prim(IM2,k ,j,i ), prim(IM2,k ,j,i ) - prim(IM2,k ,j,i-1), prim(IM2,k-1,j,i+1) - prim(IM2,k-1,j,i ), prim(IM2,k-1,j,i ) - prim(IM2,k-1,j,i-1)); dvydx /= dx; // Gradient dVz/dx at i, j, k-1/2 Real dvzdx = FourLimiter(prim(IM3,k ,j,i+1) - prim(IM3,k ,j,i ), prim(IM3,k ,j,i ) - prim(IM3,k ,j,i-1), prim(IM3,k-1,j,i+1) - prim(IM3,k-1,j,i ), prim(IM3,k-1,j,i ) - prim(IM3,k-1,j,i-1)); dvzdx /= dx; Real dy = 0.5*(pco_->dx2v(j-1) + pco_->dx2v(j)); // Gradient dVx/dy at i, j, k-1/2 Real dvxdy = FourLimiter(prim(IM1,k ,j+1,i) - prim(IM1,k ,j ,i), prim(IM1,k ,j ,i) - prim(IM1,k ,j-1,i), prim(IM1,k-1,j+1,i) - prim(IM1,k-1,j ,i), prim(IM1,k-1,j ,i) - prim(IM1,k-1,j-1,i)); dvxdy /= dy; // Gradient dVx/dy at i, j, k-1/2 Real dvydy = FourLimiter(prim(IM2,k ,j+1,i) - prim(IM2,k ,j ,i), prim(IM2,k ,j ,i) - prim(IM2,k ,j-1,i), prim(IM2,k-1,j+1,i) - prim(IM2,k-1,j ,i), prim(IM2,k-1,j ,i) - prim(IM2,k-1,j-1,i)); dvydy /= dy; // Gradient dVx/dy at i, j, k-1/2 Real dvzdy = FourLimiter(prim(IM3,k ,j+1,i) - prim(IM3,k ,j ,i), prim(IM3,k ,j ,i) - prim(IM3,k ,j-1,i), prim(IM3,k-1,j+1,i) - prim(IM3,k-1,j ,i), prim(IM3,k-1,j ,i) - prim(IM3,k-1,j-1,i)); dvzdy /= dy; Real dz = pco_->dx3v(k-1); // Gradient dVx/dz at i, j, k-1/2 Real dvxdz = (prim(IM1,k,j,i) - prim(IM1,k-1,j,i)) / dz; // Gradient dVy/dz at i, j, k-1/2 Real dvydz = (prim(IM2,k,j,i) - prim(IM2,k-1,j,i)) / dz; // Gradient dVz/dz at i, j, k-1/2 Real dvzdz = (prim(IM3,k,j,i) - prim(IM3,k-1,j,i)) / dz; // Compute BB:GV Real bbdv = bx*(bx*dvxdx + by*dvydx + bz*dvzdx); bbdv += by*(bx*dvxdy + by*dvydy + bz*dvzdy); bbdv += bz*(bx*dvxdz + by*dvydz + bz*dvzdz); bbdv /= bsq; Real nu1 = 0.5*(nu(ANI,k,j,i) + nu(ANI,k-1,j,i)); Real denf = 1.;// 0.5*(prim(IDN,k,j,i) + prim(IDN,k-1,j,i)); Real delta_p = nu1*denf*(bbdv - ONE_3RD*(dvxdx + dvydy + dvzdz)); // Apply mirror and/or firehose limiters if (mirror_limit && delta_p>0.5*bsq) delta_p = 0.5*bsq; if (firehose_limit && delta_p<-1.0*bsq) delta_p = -1.0*bsq; //dp(0,k,j,i) = delta_p; // NB: Flux sign opposite to old athena Real flx1 = -delta_p*(bz*bx/bsq); Real flx2 = -delta_p*(bz*by/bsq); Real flx3 = -delta_p*(bz*bz/bsq - ONE_3RD); x3flux(IM1,k,j,i) += flx1; x3flux(IM2,k,j,i) += flx2; x3flux(IM3,k,j,i) += flx3; if (NON_BAROTROPIC_EOS) x3flux(IEN,k,j,i) += 0.5*((prim(IM1,k,j,i) + prim(IM1,k-1,j,i))*flx1 + (prim(IM2,k,j,i) + prim(IM2,k-1,j,i))*flx2 + (prim(IM3,k,j,i) + prim(IM3,k-1,j,i))*flx3); } }} } // 1D, 2D, no fluxes return; } //---------------------------------------------------------------------------------------- // constant viscosity void ConstViscosity(HydroDiffusion *phdif, MeshBlock *pmb, const AthenaArray<Real> &prim, const AthenaArray<Real> &bcc, int is, int ie, int js, int je, int ks, int ke) { if (phdif->nu_iso > 0.0) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) phdif->nu(ISO,k,j,i) = phdif->nu_iso; } } } if (phdif->nu_aniso > 0.0) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) phdif->nu(ANI,k,j,i) = phdif->nu_aniso; } } } return; } /*----------------------------------------------------------------------------*/ /* limiter2 and limiter4: call slope limiters to preserve monotonicity */ static Real limiter2(const Real A, const Real B) { /* slope limiter */ return mc(A,B); } static Real FourLimiter(const Real A, const Real B, const Real C, const Real D) { return limiter2(limiter2(A,B),limiter2(C,D)); } /*----------------------------------------------------------------------------*/ /* vanleer: van Leer slope limiter */ static Real vanleer(const Real A, const Real B) { if (A*B > 0) { return 2.0*A*B/(A+B); } else { return 0.0; } } /*----------------------------------------------------------------------------*/ /* minmod: minmod slope limiter */ static Real minmod(const Real A, const Real B) { if (A*B > 0) { if (A > 0) { return std::min(A,B); } else { return std::max(A,B); } } else { return 0.0; } } /*----------------------------------------------------------------------------*/ /* mc: monotonized central slope limiter */ static Real mc(const Real A, const Real B) { return minmod(2.0*minmod(A,B), (A + B)/2.0); }
[ "robertmjenningsjr@berkeley.edu" ]
robertmjenningsjr@berkeley.edu
1a023031817dc2268a9b9d05414df59f84f0eeb4
62c9b78524d33b2c5f179cda69783249d84db996
/771-Jewels_and_Stones.cpp
62c93810fba8d5c8a6031498620650019893d43f
[]
no_license
reuben12358/Leetcode_Problems
34a613fb076048b87402c3684dd6885932bfcaec
b1deb489b4a59374afdb6a6ae6604d1dbb5438b9
refs/heads/master
2022-12-26T11:23:51.818847
2020-09-28T03:47:20
2020-09-28T03:47:20
297,519,319
0
0
null
null
null
null
UTF-8
C++
false
false
352
cpp
#include <string> using namespace std; class Solution { public: int numJewelsInStones(string J, string S) { int count = 0; for (int i = 0; i < J.size(); ++i) { for (int j = 0; j < S.size(); ++j) { if (J.at(i) == S.at(j)) count++; } } return count; } };
[ "rdcu001@ucr.edu" ]
rdcu001@ucr.edu
d81a31e3285bbed45918782116c53df584e7ba63
191460258090bcabe392785948025887696ccd1b
/src/xenia/cpu/test/xe-cpu-hir-test.cc
6b20a7b4414b77dd8df8ccbc05fec96c65543338
[]
no_license
DrChat/xenia
1b81ab13298229cb568c1385774f47792a802767
0dc06a7e6fedaa4dd7bbe4e3c34bc288a58f6c49
refs/heads/master
2020-04-05T18:29:57.710202
2015-05-20T05:31:37
2015-05-20T05:31:37
34,922,300
5
5
null
2015-05-01T20:21:14
2015-05-01T20:21:14
null
UTF-8
C++
false
false
1,546
cc
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2014 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #define CATCH_CONFIG_RUNNER #include "third_party/catch/single_include/catch.hpp" #include "xenia/base/debugging.h" #include "xenia/base/string.h" #include "xenia/cpu/test/util.h" namespace xe { namespace cpu { namespace test { using xe::cpu::frontend::PPCContext; using xe::cpu::Runtime; int main(std::vector<std::wstring>& args) { std::vector<std::string> narrow_args; auto narrow_argv = new char* [args.size()]; for (size_t i = 0; i < args.size(); ++i) { auto narrow_arg = xe::to_string(args[i]); narrow_argv[i] = const_cast<char*>(narrow_arg.data()); narrow_args.push_back(std::move(narrow_arg)); } int ret = Catch::Session().run(int(args.size()), narrow_argv); if (ret) { #if XE_PLATFORM_WIN32 // Visual Studio kills the console on shutdown, so prevent that. if (xe::debugging::IsDebuggerAttached()) { xe::debugging::Break(); } #endif // XE_PLATFORM_WIN32 } return ret; } } // namespace test } // namespace cpu } // namespace xe DEFINE_ENTRY_POINT(L"xe-cpu-hir-test", L"?", xe::cpu::test::main);
[ "ben.vanik@gmail.com" ]
ben.vanik@gmail.com
ac89e539f64a0d63b1a0902b9c81f8dfb406da0d
2f986abb0b85df78506f61d9741eb31b924ed7e5
/SomeVM/Disassembler.cpp
dca7b1dc0ccc7f80ca28fe8720e50d2eb0d318b8
[ "MIT" ]
permissive
Xxmmy/SomeVM
7ae6db618ab88a4b5b284668de730393ef4fefb3
360363572631b00ea14c2ad770cb2b53a0242c6c
refs/heads/master
2021-01-23T16:30:52.391573
2016-08-17T11:28:59
2016-08-17T11:33:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
#include "Disassembler.hpp" namespace dbr { namespace svm { Disassembler::Disassembler() {} Disassembler::~Disassembler() {} } }
[ "adiverso93@gmail.com" ]
adiverso93@gmail.com
f74a77adaa0f0377972c65eb43714247b0c0ccab
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/net/config/netoc/netocx.cpp
1e2440db2ff4186970c1948e725798d883986f6a
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,399
cpp
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997. // // File: N E T O C X . C P P // // Contents: Custom installation functions for various optional // components. // // Notes: // // Author: danielwe 19 Jun 1997 // //---------------------------------------------------------------------------- #include "pch.h" #pragma hdrstop #include "netoc.h" #include "netocx.h" #include "ncmisc.h" #include "ncreg.h" #include "ncsetup.h" #include "ncsvc.h" #include "snmpocx.h" static const WCHAR c_szFileSpec[] = L"*.*"; static const WCHAR c_szWinsPath[] = L"\\wins"; static const WCHAR c_szRegKeyWinsParams[] = L"System\\CurrentControlSet\\Services\\WINS\\Parameters"; static const WCHAR c_szRegValWinsBackupDir[] = L"BackupDirPath"; //+--------------------------------------------------------------------------- // // Function: HrOcExtWINS // // Purpose: NetOC external message handler // // Arguments: // pnocd [] // uMsg [] // wParam [] // lParam [] // // Returns: // // Author: danielwe 17 Sep 1998 // // Notes: // HRESULT HrOcExtWINS(PNETOCDATA pnocd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HRESULT hr = S_OK; Assert(pnocd); switch (uMsg) { case NETOCM_POST_INSTALL: hr = HrOcWinsOnInstall(pnocd); break; } TraceError("HrOcExtWINS", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcExtDNS // // Purpose: NetOC external message handler // // Arguments: // pnocd [] // uMsg [] // wParam [] // lParam [] // // Returns: // // Author: danielwe 17 Sep 1998 // // Notes: // HRESULT HrOcExtDNS(PNETOCDATA pnocd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HRESULT hr = S_OK; Assert(pnocd); switch (uMsg) { case NETOCM_POST_INSTALL: hr = HrOcDnsOnInstall(pnocd); break; } TraceError("HrOcExtDNS", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcExtSNMP // // Purpose: NetOC external message handler // // Arguments: // pnocd [] // uMsg [] // wParam [] // lParam [] // // Returns: // // Author: danielwe 17 Sep 1998 // // Notes: // HRESULT HrOcExtSNMP(PNETOCDATA pnocd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HRESULT hr = S_OK; Assert(pnocd); switch (uMsg) { case NETOCM_POST_INSTALL: hr = HrOcSnmpOnInstall(pnocd); break; } TraceError("HrOcExtSNMP", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrSetWinsServiceRecoveryOption // // Purpose: Sets the recovery options for the WINS service // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: danielwe 26 May 1999 // // Notes: // HRESULT HrSetWinsServiceRecoveryOption(PNETOCDATA pnocd) { CServiceManager sm; CService service; HRESULT hr = S_OK; SC_ACTION sra [4] = { { SC_ACTION_RESTART, 15*1000 }, // restart after 15 seconds { SC_ACTION_RESTART, 15*1000 }, // restart after 15 seconds { SC_ACTION_RESTART, 15*1000 }, // restart after 15 seconds { SC_ACTION_NONE, 30*1000 }, }; SERVICE_FAILURE_ACTIONS sfa = { 60 * 60, // dwResetPeriod is 1 hr L"", // no reboot message L"", // no command to execute 4, // 3 attempts to restart the server and stop after that sra }; hr = sm.HrOpenService(&service, L"WINS"); if (S_OK == hr) { hr = service.HrSetServiceRestartRecoveryOption(&sfa); } TraceError("HrSetWinsServiceRecoveryOption", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcWinsOnInstall // // Purpose: Called by optional components installer code to handle // additional installation requirements for WINS Server. // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: danielwe 19 Jun 1997 // // Notes: // HRESULT HrOcWinsOnInstall(PNETOCDATA pnocd) { HRESULT hr = S_OK; if (pnocd->eit == IT_INSTALL) { hr = HrHandleStaticIpDependency(pnocd); if (SUCCEEDED(hr)) { hr = HrSetWinsServiceRecoveryOption(pnocd); } } else if (pnocd->eit == IT_UPGRADE) { HKEY hkey; // Upgrade the BackupDirPath value from whatever it was to // REG_EXPAND_SZ hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE, c_szRegKeyWinsParams, KEY_ALL_ACCESS, &hkey); if (SUCCEEDED(hr)) { DWORD dwType; LPBYTE pbData = NULL; DWORD cbData; hr = HrRegQueryValueWithAlloc(hkey, c_szRegValWinsBackupDir, &dwType, &pbData, &cbData); if (SUCCEEDED(hr)) { switch (dwType) { case REG_MULTI_SZ: case REG_SZ: PWSTR pszNew; // This cast will give us the first string of the MULTI_SZ pszNew = reinterpret_cast<PWSTR>(pbData); TraceTag(ttidNetOc, "Resetting %S to %S", c_szRegValWinsBackupDir, pszNew); hr = HrRegSetSz(hkey, c_szRegValWinsBackupDir, pszNew); break; } MemFree(pbData); } RegCloseKey(hkey); } // This process is non-fatal TraceError("HrOcWinsOnInstall - Failed to upgrade BackupDirPath - " "non-fatal", hr); // overwrite hr on purpose hr = HrSetWinsServiceRecoveryOption(pnocd); } else if (pnocd->eit == IT_REMOVE) { WCHAR szWinDir[MAX_PATH]; if (GetSystemDirectory(szWinDir, celems(szWinDir))) { lstrcatW(szWinDir, c_szWinsPath); // szWinDir should now be something like c:\winnt\system32\wins hr = HrDeleteFileSpecification(c_szFileSpec, szWinDir); } else { hr = HrFromLastWin32Error(); } if (FAILED(hr)) { TraceError("HrOcWinsOnInstall: failed to delete files, continuing...", hr); hr = S_OK; } } TraceError("HrOcWinsOnInstall", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcDnsOnInstall // // Purpose: Called by optional components installer code to handle // additional installation requirements for DNS Server. // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: danielwe 19 Jun 1997 // // Notes: // HRESULT HrOcDnsOnInstall(PNETOCDATA pnocd) { HRESULT hr = S_OK; if (pnocd->eit == IT_INSTALL) { hr = HrHandleStaticIpDependency(pnocd); } TraceError("HrOcDnsOnInstall", hr); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcSnmpAgent // // Purpose: Installs the SNMP agent parameters // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: FlorinT 10/05/1998 // // Notes: // HRESULT HrOcSnmpAgent(PNETOCDATA pnocd) { tstring tstrVariable; PWSTR pTstrArray = NULL; HRESULT hr; // Read SNMP answer file params and save them to the registry //-------- read the 'Contact Name' parameter hr = HrSetupGetFirstString(g_ocmData.hinfAnswerFile, AF_SECTION, AF_SYSNAME, &tstrVariable); if (hr == S_OK) { hr = SnmpRegWriteTstring(REG_KEY_AGENT, SNMP_CONTACT, tstrVariable); } if (hr == S_OK || hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) { //-------- read the 'Location' parameter hr = HrSetupGetFirstString(g_ocmData.hinfAnswerFile, AF_SECTION, AF_SYSLOCATION, &tstrVariable); } if (hr == S_OK) { hr = SnmpRegWriteTstring(REG_KEY_AGENT, SNMP_LOCATION, tstrVariable); } if (hr == S_OK || hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) { //-------- read the 'Service' parameter hr = HrSetupGetFirstMultiSzFieldWithAlloc(g_ocmData.hinfAnswerFile, AF_SECTION, AF_SYSSERVICES, &pTstrArray); } if (hr == S_OK) { DWORD dwServices = SnmpStrArrayToServices(pTstrArray); delete pTstrArray; hr = SnmpRegWriteDword(REG_KEY_AGENT, SNMP_SERVICES, dwServices); } return (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) ? S_OK : hr; } //+--------------------------------------------------------------------------- // // Function: HrOcSnmpTraps // // Purpose: Installs the traps SNMP parameters defined in the answer file // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: FlorinT 10/05/1998 // // Notes: // HRESULT HrOcSnmpTraps(PNETOCDATA pnocd) { tstring tstrVariable; PWSTR pTstrArray = NULL; HRESULT hr; // Read SNMP answer file params and save them to the registry //-------- read the 'Trap community' parameter hr = HrSetupGetFirstString(g_ocmData.hinfAnswerFile, AF_SECTION, AF_TRAPCOMMUNITY, &tstrVariable); if (hr == S_OK) { //-------- read the 'Trap destinations' parameter HrSetupGetFirstMultiSzFieldWithAlloc(g_ocmData.hinfAnswerFile, AF_SECTION, AF_TRAPDEST, &pTstrArray); hr = SnmpRegWriteTraps(tstrVariable, pTstrArray); delete pTstrArray; } return (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) ? S_OK : hr; } // bitmask values for 'pFlag' parameter for HrOcSnmpSecurity() // they indicate which of the SNMP SECuritySETtings were defined through // the answerfile. #define SNMP_SECSET_COMMUNITIES 0x00000001 #define SNMP_SECSET_AUTHFLAG 0x00000002 #define SNMP_SECSET_PERMMGR 0x00000004 //+--------------------------------------------------------------------------- // // Function: HrOcSnmpSecurituy // // Purpose: Installs the security SNMP parameters defined in the answer file // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: FlorinT 10/05/1998 // // Notes: // HRESULT HrOcSnmpSecurity(PNETOCDATA pnocd, DWORD *pFlags) { BOOL bVariable = FALSE; PWSTR pTstrArray = NULL; HRESULT hr; // Read SNMP answer file params and save them to the registry //-------- read the 'Accepted communities' parameter hr = HrSetupGetFirstMultiSzFieldWithAlloc(g_ocmData.hinfAnswerFile, AF_SECTION, AF_ACCEPTCOMMNAME, &pTstrArray); if (hr == S_OK) { if (pFlags) (*pFlags) |= SNMP_SECSET_COMMUNITIES; hr = SnmpRegWriteCommunities(pTstrArray); delete pTstrArray; } if (hr == S_OK || hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) { //-------- read the 'EnableAuthenticationTraps' parameter hr = HrSetupGetFirstStringAsBool(g_ocmData.hinfAnswerFile, AF_SECTION, AF_SENDAUTH, &bVariable); if (hr == S_OK) { if (pFlags) (*pFlags) |= SNMP_SECSET_AUTHFLAG; hr = SnmpRegWriteDword(REG_KEY_SNMP_PARAMETERS, REG_VALUE_AUTHENTICATION_TRAPS, bVariable); } } if (hr == S_OK || hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) { //-------- read the 'Permitted Managers' parameter hr = HrSetupGetFirstStringAsBool(g_ocmData.hinfAnswerFile, AF_SECTION, AF_ANYHOST, &bVariable); } if (hr == S_OK) { pTstrArray = NULL; // if not 'any host', get the list of hosts from the inf file if (bVariable == FALSE) { hr = HrSetupGetFirstMultiSzFieldWithAlloc(g_ocmData.hinfAnswerFile, AF_SECTION, AF_LIMITHOST, &pTstrArray); } // at least clear up the 'permitted managers' list (bVariable = TRUE) // at most, write the allowed managers to the registry if (hr == S_OK) { if (pFlags) (*pFlags) |= SNMP_SECSET_PERMMGR; hr = SnmpRegWritePermittedMgrs(bVariable, pTstrArray); } if (pTstrArray != NULL) delete pTstrArray; } return (hr == HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND)) ? S_OK : hr; } //+--------------------------------------------------------------------------- // // Function: HrOcSnmpDefCommunity // // Purpose: Installs the default SNMP community. // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: FlorinT 10/05/1998 // // Notes: // HRESULT HrOcSnmpDefCommunity(PNETOCDATA pnocd) { HRESULT hr = S_OK; hr = SnmpRegWriteDefCommunity(); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcSnmpUpgParams // // Purpose: makes all the registry changes needed when upgrading to Win2K // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: FlorinT 10/05/1998 // // Notes: // HRESULT HrOcSnmpUpgParams(PNETOCDATA pnocd) { HRESULT hr = S_OK; hr = SnmpRegUpgEnableAuthTraps(); return hr; } //+--------------------------------------------------------------------------- // // Function: HrOcSnmpOnInstall // // Purpose: Called by optional components installer code to handle // additional installation requirements for SNMP. // // Arguments: // pnocd [in] Pointer to NETOC data. // // Returns: S_OK if successful, Win32 error otherwise. // // Author: danielwe 15 Sep 1998 // // Notes: // HRESULT HrOcSnmpOnInstall(PNETOCDATA pnocd) { HRESULT hr = S_OK; DWORD secFlags = 0; if ((pnocd->eit == IT_INSTALL) | (pnocd->eit == IT_UPGRADE)) { // --ft:10/14/98-- bug #237203 - success if there is no answer file! if (g_ocmData.hinfAnswerFile != NULL) { hr = HrOcSnmpSecurity(pnocd, &secFlags); if (hr == S_OK) hr = HrOcSnmpTraps(pnocd); if (hr == S_OK) hr = HrOcSnmpAgent(pnocd); } } // configure the 'public' community as a read-only community only if: // fresh installing and (there is no answer_file or there is an answer_file but it doesn't // configure any community) if (hr == S_OK && pnocd->eit == IT_INSTALL && !(secFlags & SNMP_SECSET_COMMUNITIES)) { hr = HrOcSnmpDefCommunity(pnocd); } // on upgrade only look at the old EnableAuthTraps value and copy it to the new location if (hr == S_OK && pnocd->eit == IT_UPGRADE) { // don't care here about the return code. The upgrade from W2K to W2K fail here and we // don't need to fail in this case. Any failure in upgrading the setting from NT4 to W2K // will result in having the default parameter. HrOcSnmpUpgParams(pnocd); } if (hr == S_OK && (pnocd->eit == IT_INSTALL || pnocd->eit == IT_UPGRADE) ) { // set admin dacl to ValidCommunities subkey hr = SnmpAddAdminAclToKey(REG_KEY_VALID_COMMUNITIES); if (hr == S_OK) { // set admin dacl to PermittedManagers subkey hr = SnmpAddAdminAclToKey(REG_KEY_PERMITTED_MANAGERS); } } TraceError("HrOcSnmpOnInstall", hr); return (hr == HRESULT_FROM_SETUPAPI(ERROR_SECTION_NOT_FOUND)) ? S_OK : hr; }
[ "112426112@qq.com" ]
112426112@qq.com
795be5d2bc0c143a17077998af971b8fcc7cca17
0debcc39799a78bfab203d2080b25f9d599cf1dc
/Source/ServerSettings/mainwindow.h
588cca7ed20f72b80b7b48bfd463065261afef07
[]
no_license
FanKaiyu369745966/BatteryCabinet
946c6ac6f78150c1ecf50cccaa77da3a48654af4
db1157b2796aba8a5faf90d30751ca737929dcf2
refs/heads/master
2020-12-10T02:41:24.117105
2020-01-14T01:03:32
2020-01-14T01:03:32
233,484,279
0
1
null
null
null
null
UTF-8
C++
false
false
215
h
#pragma once #include <QMainWindow> #include "ui_mainwindow.h" class mainwindow : public QMainWindow { Q_OBJECT public: mainwindow(QWidget *parent = Q_NULLPTR); ~mainwindow(); private: Ui::mainwindow ui; };
[ "369745966@163.com" ]
369745966@163.com
d660f6141582954b038880602bc2cb2e7bc3da4e
7af486bf75ef8852f7dae87bd7ab2ddb772ee85a
/pruebas/TouchLEDstrip/TouchLEDstrip.ino
45831ae7a97f7ff5187156e267175da17a6f1e9f
[]
no_license
NataliaCombariza/Reencuentro-Natural
693feea00dbd6665c0496d0b8a88ba253f7c6308
c0131a47f20fbbe3bf1ccf106e09c84aa98547f9
refs/heads/main
2023-07-03T12:12:08.446457
2021-08-04T14:35:24
2021-08-04T14:35:24
392,451,078
0
0
null
null
null
null
UTF-8
C++
false
false
5,312
ino
//Capacitive sensor and LED strip //Libraries #include <FastLED.h> //Initialize Strips #define LED_PIN 6 #define NUM_LEDS 25 #define BRIGHTNESS 255 #define LED_PIN2 8 #define NUM_LEDS2 29 #define BRIGHTNESS2 255 #define UPDATES_PER_SECOND 100 CRGB fuzzy[NUM_LEDS]; CRGB strip[NUM_LEDS2]; //Capacitive sensor initialization #include <Wire.h> #include "Adafruit_MPR121.h" #ifndef _BV #define _BV(bit) (1 << (bit)) #endif // You can have up to 4 on one i2c bus but one is enough for testing! Adafruit_MPR121 cap = Adafruit_MPR121(); // Keeps track of the last pins touched // so we know when buttons are 'released' uint8_t br[2];// brightness uint16_t lasttouched = 0; uint16_t currtouched = 0; void setup() { Serial.begin(9600); // GRB color code for strip LEDS.addLeds<WS2812, LED_PIN2, RGB>(strip, NUM_LEDS2); // RGB color code for fuzzy leds LEDS.addLeds<WS2811, LED_PIN, RGB>(fuzzy, NUM_LEDS); //To give different values of brightness for both strips br[0]= 250; br[1]= 50; LEDS.show(); while (!Serial) { // needed to keep leonardo/micro from starting too fast! delay(10); } Serial.println("Adafruit MPR121 Capacitive Touch sensor test"); // Default address is 0x5A, if tied to 3.3V its 0x5B // If tied to SDA its 0x5C and if SCL then 0x5D if (!cap.begin(0x5A)) { Serial.println("MPR121 not found, check wiring?"); while (1); } Serial.println("MPR121 found!"); } void loop() { //Brightness initialization LEDS[0].setCorrection(CRGB(br[0],br[0],br[0])); LEDS[1].setCorrection(CRGB(br[1],br[1],br[1])); // Get the currently touched pads currtouched = cap.touched(); for (uint8_t i=0; i<12; i++) { // it if *is* touched and *wasnt* touched before, alert! if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) { Serial.print(i); Serial.println(" touched"); } // if it *was* touched and now *isnt*, alert! if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) { Serial.print(i); Serial.println(" released"); } } //Commands for every sensor when is touched if(currtouched & _BV(5)){ Serial.println("uno"); fuzzy[0] = CRGB ::Goldenrod; FastLED.show(); fuzzy[1] = CRGB::Goldenrod; FastLED.show(); fuzzy[2] = CRGB::Goldenrod; FastLED.show(); fuzzy[3] = CRGB::Goldenrod; FastLED.show(); fuzzy[4] = CRGB( 190,170,20); FastLED.show(); } if(currtouched & _BV(2)){ Serial.println("dos"); fuzzy[5] = CRGB::Goldenrod; FastLED.show(); fuzzy[6] = CRGB( 190,170,20); FastLED.show(); fuzzy[7] = CRGB( 140,150,10); FastLED.show(); fuzzy[8] = CRGB::Goldenrod; FastLED.show(); fuzzy[9] = CRGB( 140,150,10); FastLED.show(); } if(currtouched & _BV(3)){ Serial.println("tres"); fuzzy[10] = CRGB::Goldenrod; FastLED.show(); fuzzy[11] = CRGB( 140,150,10); FastLED.show(); fuzzy[12] = CRGB( 190,170,20); FastLED.show(); fuzzy[13] = CRGB::Goldenrod; FastLED.show(); fuzzy[14] = CRGB( 190,170,20); FastLED.show(); } if(currtouched & _BV(4)){ Serial.println("cuatro"); fuzzy[15] = CRGB( 190,170,20); FastLED.show(); fuzzy[16] = CRGB( 190,170,20); FastLED.show(); fuzzy[17] = CRGB::Goldenrod; FastLED.show(); fuzzy[18] = CRGB( 190,170,20); FastLED.show(); fuzzy[19] = CRGB::Goldenrod; //Cinta strip[0] = CRGB(160,20,150); FastLED.show(); strip[1] = CRGB( 150, 10, 40); FastLED.show(); strip[2] = CRGB(40,50,180); FastLED.show(); strip[3] = CRGB(160,20,150); FastLED.show(); strip[4] = CRGB( 150, 10, 40); FastLED.show(); strip[5] = CRGB(160,10,150); FastLED.show(); strip[6] = CRGB( 150, 10, 40); FastLED.show(); strip[7] = CRGB(160,10,150); FastLED.show(); strip[8] = CRGB(40,50,180); FastLED.show(); strip[9] = CRGB( 60, 40, 200); FastLED.show(); strip[10] = CRGB( 150, 10, 40); FastLED.show(); } if(currtouched & _BV(1)){ Serial.println("cinco"); fuzzy[20] = CRGB( 190,170,20); FastLED.show(); fuzzy[21] = CRGB::Goldenrod; FastLED.show(); fuzzy[22] = CRGB::Goldenrod; FastLED.show(); fuzzy[23] = CRGB( 190,170,20); FastLED.show(); fuzzy[24] = CRGB::Goldenrod; FastLED.show(); //Cinta strip[18] = CRGB(40,50,180); FastLED.show(); strip[19] = CRGB( 60, 50, 200); FastLED.show(); strip[20] = CRGB( 150, 10, 40); FastLED.show(); strip[11] = CRGB( 60, 40, 200); FastLED.show(); strip[12] = CRGB(160,20,150); FastLED.show(); strip[13] = CRGB(160,20,150); FastLED.show(); strip[14] = CRGB( 150, 100, 40); FastLED.show(); strip[15] = CRGB(160,20,150); FastLED.show(); strip[16] = CRGB( 60, 40, 200); FastLED.show(); strip[17] = CRGB( 150, 10, 40); FastLED.show(); //colibri strip[27] = CRGB( 180,20,120); FastLED.show(); strip[26] = CRGB( 130,20,170); FastLED.show(); strip[25] = CRGB(40,60,180); FastLED.show(); strip[28] = CRGB(130,20,170); FastLED.show(); strip[29] = CRGB( 180,20,120); FastLED.show(); } if(currtouched & _BV(0)){ FastLED.clear(); // clear all pixel data FastLED.show(); } }
[ "vncombariza@gmail.com" ]
vncombariza@gmail.com
96b08e44cef5881f3f46b80b4ae61fc50aeea1cf
57e822f4aa0ef9d30194ccbf2c490828038c2ab7
/Platform/PlatformErrorResolve.hpp
58c7ea3a7b0924f2bfd987d4699cd78522b631ea
[]
no_license
Industrialice/StdLib2018
ce93cb59d6c4baa8350a2152d9a7c2e10bc0aeb6
6cbebf842daea1cdadb80dcb3562616ddbe811f1
refs/heads/master
2021-06-21T12:37:48.259786
2019-09-06T06:12:54
2019-09-06T06:12:54
132,740,797
0
0
null
null
null
null
UTF-8
C++
false
false
119
hpp
#pragma once namespace StdLib { [[nodiscard]] NOINLINE Error<> PlatformErrorResolve(const char *message = nullptr); }
[ "iindustrialice@gmail.com" ]
iindustrialice@gmail.com
9a168c23508d6cf1d587757abc4c778f01750bdf
538b9f53d032bc96555c8983a52673a3f316828c
/library/console/main.cpp
307e3e0fde50d1b5822f1c9cb7c1e5c3eb4ed1d1
[]
no_license
Antollo/Easypt
62f475b58450f2492684345d1e004a86517821cb
d567e5b902443348280fbc4768d49629431a7a36
refs/heads/master
2020-03-27T15:55:48.820111
2019-08-21T09:31:26
2019-08-21T09:31:26
146,748,421
3
0
null
null
null
null
UTF-8
C++
false
false
6,682
cpp
#ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #endif #include <iostream> #include <cstdio> #include <string> #include "nobject.h" object::objectPtr write (object::objectPtr obj, object::arrayType& args) { for(auto& arg : args) { if (arg->hasSignature(name("String"))) std::cout << *std::any_cast<std::string>(&arg->getValue()); else if (arg->hasSignature(name("Int"))) std::cout << *std::any_cast<int>(&arg->getValue()); else if (arg->hasSignature(name("Boolean"))) std::cout << *std::any_cast<bool>(&arg->getValue()); else if (arg->hasSignature(name("Double"))) std::cout << *std::any_cast<double>(&arg->getValue()); else if (arg->hasSignature(name("Basic"))) std::cout << *std::any_cast<std::string>(&(arg->READ(name("toString"))->CALL()->getValue())); else throw(WrongTypeOfArgument("Wrong type of argument while calling ", obj->getFullNameString())); }; return obj->getParent(); } object::objectPtr writeLine (object::objectPtr obj, object::arrayType& args) { write(obj, args); std::cout << std::endl; return obj->getParent(); } object::objectPtr read (object::objectPtr obj, object::arrayType& args) { std::string buffer; asyncTasks::unregisterThisThread(); std::cin >> buffer; asyncTasks::registerThisThread(); return obj->READ(name("String"), true)->CALL()->setValue(buffer); } object::objectPtr readLine (object::objectPtr obj, object::arrayType& args) { std::string buffer; asyncTasks::unregisterThisThread(); std::getline(std::cin, buffer); asyncTasks::registerThisThread(); return obj->READ(name("String"), true)->CALL()->setValue(buffer); } object::objectPtr scan (object::objectPtr obj, object::arrayType& args) { std::string buffer; for(auto& arg : args) { asyncTasks::unregisterThisThread(); std::cin >> buffer; asyncTasks::registerThisThread(); if (arg->hasSignature(name("String"))) arg->getValue() = buffer; else if (arg->hasSignature(name("Int"))) { try { arg->getValue() = std::stoi(buffer); } catch (std::invalid_argument&) { throw(InvalidValue("Invalid input value in ", obj->getFullNameString())); } catch (std::out_of_range&) { throw(OutOfRange("Out of range in ", obj->getFullNameString())); } } else if (arg->hasSignature(name("Boolean"))) { try { arg->getValue() = (bool) std::stoi(buffer); } catch (std::invalid_argument&) { throw(InvalidValue("Invalid input value in ", obj->getFullNameString())); } catch (std::out_of_range&) { throw(OutOfRange("Out of range in ", obj->getFullNameString())); } } else if (arg->hasSignature(name("Double"))) { try { arg->getValue() = std::stod(buffer); } catch (std::invalid_argument&) { throw(InvalidValue("Invalid input value in ", obj->getFullNameString())); } catch (std::out_of_range&) { throw(OutOfRange("Out of range in ", obj->getFullNameString())); } } else throw(WrongTypeOfArgument("Wrong type of argument while calling ", obj->getFullNameString())); }; return obj->getParent(); } object::objectPtr beep (object::objectPtr obj, object::arrayType& args) { std::cout << '\a'; return obj->getParent(); } object::objectPtr controlSequence (object::objectPtr obj, object::arrayType& args) { for(auto& arg : args) { if (arg->hasSignature(name("String"))) std::cout << ("\033[" + *std::any_cast<std::string>(&arg->getValue())); else throw(WrongTypeOfArgument("Wrong type of argument while calling ", obj->getFullNameString())); }; return obj->getParent(); } object::objectPtr fWriteInt (object::objectPtr obj, object::arrayType& args) { std::printf("%d", *std::any_cast<int>(&args.at(0)->getValue())); return obj->getParent(); } object::objectPtr fWriteDouble (object::objectPtr obj, object::arrayType& args) { std::printf("%lf", *std::any_cast<double>(&args.at(0)->getValue())); return obj->getParent(); } object::objectPtr fWriteString (object::objectPtr obj, object::arrayType& args) { std::printf("%s", std::any_cast<std::string>(&args.at(0)->getValue())->c_str()); return obj->getParent(); } object::objectPtr fScanInt (object::objectPtr obj, object::arrayType& args) { std::scanf("%i", std::any_cast<int>(&args.at(0)->getValue())); return obj->getParent(); } object::objectPtr fScanDouble (object::objectPtr obj, object::arrayType& args) { std::scanf("%lf", std::any_cast<double>(&args.at(0)->getValue())); return obj->getParent(); } object::objectPtr fScanString16 (object::objectPtr obj, object::arrayType& args) { char temp[17]; scanf("%16s", temp); *std::any_cast<std::string>(&args.at(0)->getValue()) = std::string(temp); return obj->getParent(); } object::objectPtr fScanString256 (object::objectPtr obj, object::arrayType& args) { char temp[257]; scanf("%256s", temp); *std::any_cast<std::string>(&args.at(0)->getValue()) = std::string(temp); return obj->getParent(); } object::objectPtr initConsole (object::objectPtr obj, object::arrayType& args) { obj->addChild(makeObject(write, name("write"))) ->addChild(makeObject(writeLine, name("writeLine"))) ->addChild(makeObject(read, name("read"))) ->addChild(makeObject(readLine, name("readLine"))) ->addChild(makeObject(scan, name("scan"))) ->addChild(makeObject(beep, name("beep"))) ->addChild(makeObject(controlSequence, name("controlSequence"))) ->addChild(constructObject(obj, "Object", nullptr)->setName("f") ->addChild(makeObject(fWriteInt, name("writeInt"))) ->addChild(makeObject(fWriteDouble, name("writeDouble"))) ->addChild(makeObject(fWriteString, name("writeString"))) ->addChild(makeObject(fScanInt, name("scanInt"))) ->addChild(makeObject(fScanDouble, name("scanDouble"))) ->addChild(makeObject(fScanString16, name("scanString16"))) ->addChild(makeObject(fScanString256, name("scanString256"))) ); return nullptr; }
[ "antoninowinowski@hotmail.com" ]
antoninowinowski@hotmail.com
13838e34669da0b9e8a6421a85ac1e01ae31e82d
719389cc1c67d23080b701e6bfed093553a15d4f
/src/main/cpp/skizzay/cddd/nullable.h
491504b1807cb425f15c0a55a905204318846d81
[ "MIT" ]
permissive
skizzay/cddd
6456dbde04a4e6b9536c9004e9e188f2dba72d7d
b5df5d390b52d3dbdb56f06c6a8664e0203a2c84
refs/heads/master
2023-06-01T04:43:43.942990
2023-01-02T01:39:02
2023-01-02T01:39:02
20,401,873
5
2
MIT
2023-04-21T21:32:02
2014-06-02T11:36:16
C++
UTF-8
C++
false
false
1,001
h
#pragma once #include <concepts> #include <memory> #include <optional> #include <type_traits> #include <variant> namespace skizzay::cddd { template <typename T> inline constexpr std::optional<T> null_value = std::nullopt; template <typename T> inline constexpr std::optional<T> null_value<std::optional<T>> = std::nullopt; template <typename T> inline constexpr T const *null_value<T *> = nullptr; template <typename T> inline std::shared_ptr<T> const null_value<std::shared_ptr<T>> = {}; template <typename T, typename D> inline constexpr std::unique_ptr<T, D> null_value<std::unique_ptr<T, D>> = {}; template <typename... Ts> requires( std::same_as<Ts, std::monostate> || ...) inline constexpr std::variant<Ts...> null_value<std::variant<Ts...>> = std::monostate{}; template <typename T> using nullable_t = std::remove_const_t<decltype(null_value<T>)>; namespace concepts { template <typename T> concept nullable = std::same_as<T, nullable_t<T>>; } } // namespace skizzay::cddd
[ "andrewford55139@gmail.com" ]
andrewford55139@gmail.com
4551a0df54658c415e9de441f673056e11d48424
d94a7ed1357454ec5e6aacd94f53753ba6f79d76
/Tominator/Tominator/include/Modes/Mode05_ClawSortingMode.h
4e78d4c09ca2e24dd66642c77561d9798995db9a
[]
no_license
Patrick-Batenburg/cpp-tominator
2ab45a8cbbdc6b04c2fb026494df6752144aa4c4
b980e035bd493462bf9a5901996181b029c2759c
refs/heads/master
2020-11-23T22:21:17.264679
2020-08-21T17:11:15
2020-08-21T17:11:15
227,844,619
0
0
null
null
null
null
UTF-8
C++
false
false
595
h
#pragma once #include "BaseMode.h" class ClawSortingMode : public BaseMode { public: /** Initializes a new instance of the SortingMode class. */ ClawSortingMode(); /** Deconstruct the instance of the SortingMode class. */ ~ClawSortingMode(); void Initialize(Machine* machine); /** Returns a string that represents the current mode. Only useful for comparisons and debug purposes. @return A string that represents the current mode. */ virtual String ToString(); private: /** Defines a set of instructions. */ virtual void HandlePlaceholder(Machine* machine); };
[ "zammypatrick@gmail.com" ]
zammypatrick@gmail.com
3aaf4cdc19539175ea5e094ebbbb32eed95ce347
3289d3523bf2a1a649024b8b4ce8634f23a4faad
/src/support/allocators/secure.h
64e1c7d0ee174abbd0c2d43f08b2c921b16229ed
[ "MIT" ]
permissive
mirzaei-ce/core-hellebit
fa06159b25ac5a0ff133c1816349eb95a514306e
bd56d29dffb10313b587785151126e2a365c17ed
refs/heads/master
2021-08-11T10:28:40.204699
2017-11-13T15:03:09
2017-11-13T15:03:09
110,562,624
0
0
null
null
null
null
UTF-8
C++
false
false
2,084
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef HELLEBIT_SUPPORT_ALLOCATORS_SECURE_H #define HELLEBIT_SUPPORT_ALLOCATORS_SECURE_H #include "support/pagelocker.h" #include <string> // // Allocator that locks its contents from being paged // out of memory and clears its contents before deletion. // template <typename T> struct secure_allocator : public std::allocator<T> { // MSVC8 default copy constructor is broken typedef std::allocator<T> base; typedef typename base::size_type size_type; typedef typename base::difference_type difference_type; typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::value_type value_type; secure_allocator() throw() {} secure_allocator(const secure_allocator& a) throw() : base(a) {} template <typename U> secure_allocator(const secure_allocator<U>& a) throw() : base(a) { } ~secure_allocator() throw() {} template <typename _Other> struct rebind { typedef secure_allocator<_Other> other; }; T* allocate(std::size_t n, const void* hint = 0) { T* p; p = std::allocator<T>::allocate(n, hint); if (p != NULL) LockedPageManager::Instance().LockRange(p, sizeof(T) * n); return p; } void deallocate(T* p, std::size_t n) { if (p != NULL) { memory_cleanse(p, sizeof(T) * n); LockedPageManager::Instance().UnlockRange(p, sizeof(T) * n); } std::allocator<T>::deallocate(p, n); } }; // This is exactly like std::string, but with a custom allocator. typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString; #endif // HELLEBIT_SUPPORT_ALLOCATORS_SECURE_H
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
4203c2ffaed2364921cf6f08686ff42506275b69
419e13a18447e783b89a21b1055234ceb0396b3e
/sources/ArkanoidLayer.h
ec025951b1f53023e8077a55775640504ba34003
[]
no_license
nikkursin/Arkanoid
b59758554ee2a94aa22ce2ac952a8813f0dc668d
19e3fced9a847bd66b5f260cc93e0d803474e385
refs/heads/master
2023-07-07T03:58:38.898957
2021-08-05T13:35:09
2021-08-05T13:35:09
393,054,577
1
0
null
null
null
null
UTF-8
C++
false
false
610
h
#pragma once #include <cocos2d.h> #include "Paddle.h" #include "Block.h" #include "Ball.h" class ArkanoidLayer : public cocos2d::Layer { public: using Super = cocos2d::Layer; static cocos2d::RefPtr<cocos2d::Scene> createScene(); virtual bool init() override; void CheckCollision(float dt); void Collision(Ball* ball, Block* block); void Collision(Ball* ball, Paddle* paddle); void MoveBall(float dt); void WinCheck(float dt); void LoseCheck(float dt); CREATE_FUNC(ArkanoidLayer); private: Paddle* paddle; Ball* ball ; Block* block; };
[ "nikkursin18@gmail.com" ]
nikkursin18@gmail.com
24d75b6f50e089927b6a63b07ce51275c7b1f50a
7090a02153e4733b28550fdca126e81d394aa660
/evoai/test/evolution_spec.cpp
d704b4ae8b4f45888aaa6a9928a92a555235b905
[]
no_license
cpanhuber/evoai
ac9ab791891ca89d98cda4c7a18458271f5ae4d1
d1688b89b21c4bf8cf3860854034dec383e35fcc
refs/heads/master
2021-05-25T17:24:16.639218
2020-04-19T21:44:39
2020-04-19T21:44:39
253,842,421
0
0
null
null
null
null
UTF-8
C++
false
false
11,463
cpp
#include <evoai/evolution/evolution.h> #include <evoai/evolution/mutation/tingri.h> #include <evoai/evolution/population.h> #include <evoai/common/types.h> #include <evoai/graph/activation/relu.h> #include <evoai/graph/graph.h> #include <evoai/graph/loss/mean_squared_error.h> #include "mock/mock_random_generator.h" #include <gtest/gtest.h> namespace { using namespace evoai; TEST(Population, CreatePopulation) { mutation::Tingri tingri; tingri.settings.kill_initial_mean = 1.0; tingri.settings.kill_change_deviation = 0.0; tingri.settings.revive_initial_mean = 2.0; tingri.settings.revive_change_deviation = 0.0; tingri.settings.mutancy_initial_mean = 3.0; tingri.settings.mutancy_change_deviation = 0.0; tingri.settings.weight_initial_mean = 4.0; tingri.settings.weight_initial_deviation = 0.0; test::MockRandomGenerator mock_generator; mock_generator.output = 1000000000; // ~0.24 in uniform([0, 1]) for gcc implementation using GraphType = NeuralGraph<2, 1, 3, 5, activation::RelU, aggregation::Accumulator, activation::RelU>; auto population = detail::CreatePopulation<GraphType>(100, tingri, mock_generator); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_EQ(100, population.size()); std::for_each(population.begin(), population.end(), [&tolerance](auto& specimen) { EXPECT_NEAR(static_cast<ValueType>(3.0), specimen.mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(2.0), specimen.revive_prior, tolerance); EXPECT_NEAR(static_cast<ValueType>(1.0), specimen.kill_prior, tolerance); EXPECT_TRUE((specimen.adjacency.array() == static_cast<ValueType>(4.0)).all()); }); } class EvolutionFixture : public ::testing::Test { public: using ActivationTracker = detail::ActivationTracker<4, activation::RelU>; using GraphType = NeuralGraph<2, 1, 1, 3, ActivationTracker, aggregation::Accumulator, activation::RelU>; void SetUp() { adjacency(2, 0) = 1.0; adjacency(2, 1) = 1.5; adjacency(3, 2) = 2.0; } GraphType::AdjacencyType adjacency = GraphType::Traits::AdjacencyType::Zero(); ActivationTracker tracker; Vector<GraphType::k_input_neurons> input; }; TEST_F(EvolutionFixture, ActivationTracker_WhenNoActivations) { input << -1.0, -2.0; detail::Predict<GraphType>(input, adjacency, tracker); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(0.0), tracker.accumulated_activations(0), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), tracker.accumulated_activations(1), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), tracker.accumulated_activations(2), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), tracker.accumulated_activations(3), tolerance); } TEST_F(EvolutionFixture, ActivationTracker_WhenSomeActivations) { input << 1.0, 0.0; detail::Predict<GraphType>(input, adjacency, tracker); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(3.0), tracker.accumulated_activations(0), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), tracker.accumulated_activations(1), tolerance); EXPECT_NEAR(static_cast<ValueType>(2.0), tracker.accumulated_activations(2), tolerance); EXPECT_NEAR(static_cast<ValueType>(2.0), tracker.accumulated_activations(3), tolerance); } TEST_F(EvolutionFixture, ActivationTracker_WhenAllActivations) { input << 1.0, 2.0; detail::Predict<GraphType>(input, adjacency, tracker); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(3.0), tracker.accumulated_activations(0), tolerance); EXPECT_NEAR(static_cast<ValueType>(6.0), tracker.accumulated_activations(1), tolerance); EXPECT_NEAR(static_cast<ValueType>(8.0), tracker.accumulated_activations(2), tolerance); EXPECT_NEAR(static_cast<ValueType>(8.0), tracker.accumulated_activations(3), tolerance); } TEST_F(EvolutionFixture, ActivationTracker_WhenRecursiveActivations) { adjacency(2, 2) = 1.0; input << 1.0, 2.0; detail::Predict<GraphType>(input, adjacency, tracker); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(3.0), tracker.accumulated_activations(0), tolerance); EXPECT_NEAR(static_cast<ValueType>(6.0), tracker.accumulated_activations(1), tolerance); EXPECT_NEAR(static_cast<ValueType>(12.0), tracker.accumulated_activations(2), tolerance); EXPECT_NEAR(static_cast<ValueType>(8.0), tracker.accumulated_activations(3), tolerance); } TEST_F(EvolutionFixture, Score) { using Population = detail::Population<GraphType, mutation::Tingri::Properties>; using Specimen = detail::Specimen<GraphType, mutation::Tingri::Properties>; Specimen specimen; specimen.adjacency = adjacency; Population population; population.push_back(specimen); input << 1.0, 2.0; Vector<1> truth; truth << 14.0; // graph output: // 1.0 1.0 1.0 1.0 // 2.0 2.0 2.0 2.0 // 0.0 4.0 4.0 4.0 // 0.0 0.0 8.0 8.0 = 16.0 auto [scores, activations] = detail::Score<loss::MeanSquaredError>(population, input, truth); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(4.0), scores[0], tolerance); EXPECT_NEAR(static_cast<ValueType>(3.0), activations[0](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(6.0), activations[0](1), tolerance); EXPECT_NEAR(static_cast<ValueType>(8.0), activations[0](2), tolerance); EXPECT_NEAR(static_cast<ValueType>(8.0), activations[0](3), tolerance); } TEST(Evolution, Fitness) { detail::Scores losses{0.0, 3.0, 1.5, 6.0}; auto fitness = detail::Fitness(losses); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(1.0), fitness[0], tolerance); EXPECT_NEAR(static_cast<ValueType>(0.5), fitness[1], tolerance); EXPECT_NEAR(static_cast<ValueType>(0.75), fitness[2], tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), fitness[3], tolerance); } TEST(Evolution, Select) { using ActivationTracker = detail::ActivationTracker<4, activation::RelU>; using GraphType = NeuralGraph<2, 1, 1, 3, ActivationTracker, aggregation::Accumulator, activation::RelU>; detail::Scores fitness{0.3, 0.4, 0.4, 0.8, 0.1}; detail::Population<GraphType, mutation::Tingri::Properties> population_in; population_in.resize(5); population_in[0].mutancy = static_cast<ValueType>(0.0); population_in[1].mutancy = static_cast<ValueType>(1.0); population_in[2].mutancy = static_cast<ValueType>(2.0); population_in[3].mutancy = static_cast<ValueType>(3.0); population_in[4].mutancy = static_cast<ValueType>(4.0); detail::ActivationSummary<4> activation_summary; activation_summary.resize(5); activation_summary[0].fill(0.0); activation_summary[1].fill(1.0); activation_summary[2].fill(2.0); activation_summary[3].fill(3.0); activation_summary[4].fill(4.0); auto [population_out, activations_out] = Select(population_in, activation_summary, fitness); // 2, 3, 3, 0, 1 auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(static_cast<ValueType>(2.0), population_out[0].mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(3.0), population_out[1].mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(3.0), population_out[2].mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), population_out[3].mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(1.0), population_out[4].mutancy, tolerance); EXPECT_NEAR(static_cast<ValueType>(2.0), activations_out[0](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(3.0), activations_out[1](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(3.0), activations_out[2](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.0), activations_out[3](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(1.0), activations_out[4](0), tolerance); EXPECT_NEAR(static_cast<ValueType>(0.4), population_out[0].fitness_score, tolerance); EXPECT_NEAR(static_cast<ValueType>(0.8), population_out[1].fitness_score, tolerance); EXPECT_NEAR(static_cast<ValueType>(0.8), population_out[2].fitness_score, tolerance); EXPECT_NEAR(static_cast<ValueType>(0.3), population_out[3].fitness_score, tolerance); EXPECT_NEAR(static_cast<ValueType>(0.4), population_out[4].fitness_score, tolerance); } TEST(Evolution, Mutate) { test::MockRandomGenerator mock_generator; mock_generator.output = 1000000000; // ~0.24 in uniform([0, 1]) for gcc implementation using GraphType = NeuralGraph<2, 1, 3, 5, activation::RelU, aggregation::Accumulator, activation::RelU>; detail::Specimen<GraphType, mutation::Tingri::Properties> specimen; specimen.mutancy = 0.5; specimen.kill_prior = 0.5; specimen.revive_prior = 0.5; Vector<6> activations; activations << 4.0, 1.0, 0.0, 1.0, 7.0, 5.0; detail::Population<GraphType, mutation::Tingri::Properties> population; population.push_back(specimen); mutation::Tingri tingri; detail::ActivationSummary<6> activation_summary; activation_summary.push_back(activations); detail::Mutate(population, tingri, activation_summary, mock_generator); auto expected = mutation::detail::SampleNormal(static_cast<ValueType>(0.5), static_cast<ValueType>(0.01), mock_generator); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(expected, population[0].mutancy, tolerance); EXPECT_NEAR(expected, population[0].revive_prior, tolerance); EXPECT_NEAR(expected, population[0].kill_prior, tolerance); } TEST(Evolution, Evolve) { test::MockRandomGenerator mock_generator; mock_generator.output = 1000000000; // ~0.24 in uniform([0, 1]) for gcc implementation // Graph with one input, one output, one hidden using GraphType = NeuralGraph<1, 1, 1, 2, activation::RelU, aggregation::Accumulator, activation::RelU>; // population with one connected and one unconnected graph detail::Specimen<GraphType, mutation::Tingri::Properties> specimen_connected; specimen_connected.adjacency.fill(static_cast<ValueType>(0.0)); specimen_connected.adjacency(1, 0) = static_cast<ValueType>(1.0); specimen_connected.adjacency(2, 1) = static_cast<ValueType>(1.0); specimen_connected.mutancy = 1.0; detail::Specimen<GraphType, mutation::Tingri::Properties> specimen_unconnected; specimen_unconnected.adjacency.fill(static_cast<ValueType>(0.0)); detail::Population<GraphType, mutation::Tingri::Properties> population; specimen_unconnected.mutancy = 0.0; population.push_back(specimen_connected); population.push_back(specimen_unconnected); // expect the input to activate the output Vector<1> input; input << static_cast<ValueType>(1.0); Vector<1> truth; truth << static_cast<ValueType>(1.0); mutation::Tingri tingri; population = detail::Evolve<loss::MeanSquaredError>(population, tingri, input, truth, mock_generator); // Expect the unconnected specimen to disappear, two connected mutated ones to remain auto expected = mutation::detail::SampleNormal(static_cast<ValueType>(1.0), static_cast<ValueType>(0.01), mock_generator); auto tolerance = static_cast<ValueType>(1e-5); EXPECT_NEAR(expected, population[0].mutancy, tolerance); EXPECT_NEAR(expected, population[1].mutancy, tolerance); } } // namespace
[ "christianpanhuber@hotmail.com" ]
christianpanhuber@hotmail.com
75eeadc78151828d5d9a50234a43e29097485773
631280063424be0e291a9b31ba8ff7d02b3671b1
/Synthie/ToneInstrument.cpp
dda91a0f677443d4d13d620704812b3c2f1b1898
[]
no_license
mmarinetti/CSE471_Project1
a95592e03b214b460b55ae61d96efc71a87929f5
8a9e3cae5ff6e1b5134afacf352778c4aea53c7d
refs/heads/master
2021-01-16T00:58:04.004339
2014-03-14T03:28:28
2014-03-14T03:28:28
17,306,882
0
1
null
null
null
null
UTF-8
C++
false
false
2,339
cpp
#include "StdAfx.h" #include "ToneInstrument.h" #include "Notes.h" CToneInstrument::CToneInstrument(void) { m_duration = 0.1; m_attack = m_release = .05; } CToneInstrument::~CToneInstrument(void) { } void CToneInstrument::Start() { m_sinewave.SetSampleRate(GetSampleRate()); m_sinewave.Start(); m_time = 0; } bool CToneInstrument::Generate() { // Tell the component to generate an audio sample m_sinewave.Generate(); // Read the component's sample and make it our resulting frame. m_frame[0] = m_sinewave.Frame(0); m_frame[1] = m_sinewave.Frame(1); //ATTACK AND RELEASE IMPLEMENATION double factor = 0; if(m_time < m_attack){ factor = m_time*1./m_attack; m_frame[0] *= factor; m_frame[1] *= factor; } else if(m_time > ((m_duration * GetSecondsPerBeat()) - m_release)){ factor = m_time*-1./m_release + (1./m_release)*(m_duration*GetSecondsPerBeat()); m_frame[0] *= factor; m_frame[1] *= factor; } // Update time m_time += GetSamplePeriod(); // We return true until the time reaches the duration. return m_time < (m_duration * GetSecondsPerBeat()); } void CToneInstrument::SetNote(CNote *note) { // Get a list of all attribute nodes and the // length of that list CComPtr<IXMLDOMNamedNodeMap> attributes; note->Node()->get_attributes(&attributes); long len; attributes->get_length(&len); // Loop over the list of attributes for(int i=0; i<len; i++) { // Get attribute i CComPtr<IXMLDOMNode> attrib; attributes->get_item(i, &attrib); // Get the name of the attribute CComBSTR name; attrib->get_nodeName(&name); // Get the value of the attribute. A CComVariant is a variable // that can have any type. It loads the attribute value as a // string (UNICODE), but we can then change it to an integer // (VT_I4) or double (VT_R8) using the ChangeType function // and then read its integer or double value from a member variable. CComVariant value; attrib->get_nodeValue(&value); if(name == "duration") { value.ChangeType(VT_R8); SetDuration(value.dblVal); } else if(name == "note") { SetFreq(NoteToFrequency(value.bstrVal)); } } }
[ "torresaa@msu.edu" ]
torresaa@msu.edu
ae1aea6556310d4a06b23e4dba31f88947cbe963
c393d50a5cbe1e1b274025a7b3a84a571d97ecc5
/stamptool/tmp/moc_mainwindow.cpp
25d2289fd453c753068b11cf4dc43e0dd240d47a
[]
no_license
EagleLin/lin
bc940cc2f490cea973fea243f984e4bafc897ff0
ce4bb87ea67755e54e2ed0a713740478e6a0ee91
refs/heads/master
2021-05-02T17:52:08.972733
2018-07-25T01:21:06
2018-07-25T01:21:06
61,784,587
0
0
null
null
null
null
UTF-8
C++
false
false
3,434
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[4]; char stringdata0[38]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 15), // "slotLoadUsrData" QT_MOC_LITERAL(2, 27, 0), // "" QT_MOC_LITERAL(3, 28, 9) // "sFilePath" }, "MainWindow\0slotLoadUsrData\0\0sFilePath" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 19, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::QString, 3, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindow *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->slotLoadUsrData((*reinterpret_cast< QString(*)>(_a[1]))); break; default: ; } } } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ "645871021@qq.com" ]
645871021@qq.com
fe0b5e9f526921d633fd43a0320ed69f0b6fa9ea
1f451f9315eb6a30b29f5dd8737020b17d07b492
/src/sqlite/statement.cxx
ba788e4eedf073ab9ddef0696eebadc7b7086729
[ "Apache-2.0" ]
permissive
bruxisma/apex
82fbc1103d15cf73fbd69e8ecabe4a18c804a930
8d88e6167e460a74e2c42a4d11d7f8e70adb5102
refs/heads/main
2023-03-05T11:47:32.735876
2020-11-17T01:14:26
2020-11-17T01:14:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
449
cxx
#include <apex/sqlite/statement.hpp> #include <sqlite3.h> namespace apex::sqlite { statement::statement () : handle { nullptr, sqlite3_finalize } { } statement::pointer statement::get () const noexcept { return this->handle.get(); } bool statement::is_readonly () const noexcept { return sqlite3_stmt_readonly(this->get()); } bool statement::is_busy () const noexcept { return sqlite3_stmt_busy(this->get()); } } /* namespace apex::sqlite */
[ "63051+slurps-mad-rips@users.noreply.github.com" ]
63051+slurps-mad-rips@users.noreply.github.com
07048960ed53049439e3b8ea5018116b902c2f97
68de5fb07a214ef076a31c0d61f30c9bf94d8711
/Tests/TestPhysics/Behaviours/NameTag.cpp
de6ff43e91a115ea124f25cf4d03ccb952ac4ea1
[ "MIT" ]
permissive
0xflotus/Acid
c2058d883dce9b3b38f6bdd0edd49860d762902a
cf680a13c3894822920737dcf1b7d17aef74a474
refs/heads/master
2020-04-06T12:31:07.380810
2018-11-11T23:43:13
2018-11-12T02:49:40
157,458,752
0
0
MIT
2018-11-13T23:02:21
2018-11-13T23:02:20
null
UTF-8
C++
false
false
1,772
cpp
#include "NameTag.hpp" #include <Objects/GameObject.hpp> #include <Scenes/Scenes.hpp> #include <Uis/Uis.hpp> #include <Maths/Visual/DriverConstant.hpp> namespace test { const float NameTag::TEXT_SIZE = 8.0f; const float NameTag::VIEW_DISTANCE = 16.0f; NameTag::NameTag(const float &heightOffset) : m_heightOffset(heightOffset), m_transform(Transform()), m_text(std::make_unique<Text>(Uis::Get()->GetContainer(), UiBound(Vector2(0.5f, 0.5f), "Centre", true), TEXT_SIZE, "Undefined", FontType::Resource("Fonts/ProximaNova", "Regular"), TEXT_JUSTIFY_CENTRE)) { m_text->SetTextColour(Colour("#ffffff")); m_text->SetBorderColour(Colour("#262626")); m_text->SetBorderDriver<DriverConstant>(0.1f); } void NameTag::Start() { m_text->SetString(GetGameObject()->GetName()); } void NameTag::Update() { // Calculates the tag position, this component should be added after a rigidbody body. Vector3 worldPosition = GetGameObject()->GetTransform().GetPosition(); worldPosition.m_y += m_heightOffset; m_transform.SetPosition(worldPosition); m_transform.SetRotation(Vector3::ZERO); // Quick way to change alpha values, only if you know the driver type for sure! float toCamera = Scenes::Get()->GetCamera()->GetPosition().Distance(worldPosition); ((DriverConstant *)m_text->GetAlphaDriver())->SetConstant(std::clamp((VIEW_DISTANCE - toCamera) / VIEW_DISTANCE, 0.0f, 1.0f)); // Will always face the screen, like a particle. m_text->SetLockRotation(true); m_text->SetWorldTransform(m_transform); } void NameTag::Decode(const Metadata &metadata) { m_heightOffset = metadata.GetChild<float>("Height Offset"); } void NameTag::Encode(Metadata &metadata) const { metadata.SetChild<float>("Height Offset", m_heightOffset); } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
9b801f76a2e34059a4590f0775ef7da6c72e175c
717571eb490eefaec0cd52dc1b49b1e59da31361
/include/BLIB/Graphics/Sprite.hpp
9cda25213443d81db0028624792ac4d8173bd2b2
[]
no_license
benreid24/BLIB
d726c48ceab133071e6bf81a638f3217ce4dfe5a
a5e4cf2eba649089940c2414e3dce57b654e0d59
refs/heads/master
2023-08-31T23:02:12.963457
2023-07-25T19:25:43
2023-07-25T19:25:43
234,001,128
1
0
null
2023-09-10T23:09:36
2020-01-15T04:54:14
C++
UTF-8
C++
false
false
1,422
hpp
#ifndef BLIB_GRAPHICS_SPRITE_HPP #define BLIB_GRAPHICS_SPRITE_HPP #include <BLIB/Components/Sprite.hpp> #include <BLIB/Graphics/Components/OverlayScalable.hpp> #include <BLIB/Graphics/Components/Textured.hpp> #include <BLIB/Graphics/Components/Transform2D.hpp> #include <BLIB/Graphics/Drawable.hpp> namespace bl { namespace engine { class Engine; } namespace gfx { /** * @brief SFML-like sprite class to render images in scenes or overlays. Wraps the ECS interface * * @ingroup Graphics */ class Sprite : public Drawable<com::Sprite> , public bcom::OverlayScalable , public bcom::Textured { public: /** * @brief Creates an uninitialized sprite */ Sprite() = default; /** * @brief Creates the ECS backing for the sprite * * @param engine The game engine instance * @param texture The texture for the sprite * @param region The region to render from the texture */ Sprite(engine::Engine& engine, rc::res::TextureRef texture, const sf::FloatRect& region = {}); /** * @brief Creates the ECS backing for the sprite * * @param engine The game engine instance * @param texture The texture for the sprite * @param region The region to render from the texture */ void create(engine::Engine& engine, rc::res::TextureRef texture, const sf::FloatRect& region = {}); }; } // namespace gfx } // namespace bl #endif
[ "reidben24@gmail.com" ]
reidben24@gmail.com
934236402b2759b59d736d2e173fa64eb1f0848b
caf6ae544fce3b332b40a03462c0646a32c913e1
/master/qtcplus/client/SWGTimeData.h
57ce43a6af726ae1bba44cdc5b45133bdb5851bc
[ "Apache-2.0" ]
permissive
coinsecure/plugins
827eb0ce03a6a23b4819a618ee47600161bec1c7
ad6f08881020c268b530d5242d9deed8d2ec84de
refs/heads/master
2020-05-30T07:17:56.255709
2016-11-27T22:22:23
2016-11-27T22:22:23
63,496,663
3
5
null
null
null
null
UTF-8
C++
false
false
2,056
h
/** * Coinsecure Api Documentation * To generate an API key, please visit <a href='https://coinsecure.in/api' target='_new' class='homeapi'>https://coinsecure.in/api</a>.<br>Guidelines for use can be accessed at <a href='https://api.coinsecure.in/v1/guidelines'>https://api.coinsecure.in/v1/guidelines</a>.<br>Programming Language Libraries for use can be accessed at <a href='https://api.coinsecure.in/v1/code-libraries'>https://api.coinsecure.in/v1/code-libraries</a>. * * OpenAPI spec version: beta * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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. */ /* * SWGTimeData.h * * */ #ifndef SWGTimeData_H_ #define SWGTimeData_H_ #include <QJsonObject> #include "SWGObject.h" namespace Swagger { class SWGTimeData: public SWGObject { public: SWGTimeData(); SWGTimeData(QString* json); virtual ~SWGTimeData(); void init(); void cleanup(); QString asJson (); QJsonObject* asJsonObject(); void fromJsonObject(QJsonObject &json); SWGTimeData* fromJson(QString &jsonString); qint64 getTime(); void setTime(qint64 time); qint64 getVerifiedTime(); void setVerifiedTime(qint64 verified_time); qint64 getCompletedTime(); void setCompletedTime(qint64 completed_time); private: qint64 time; qint64 verified_time; qint64 completed_time; }; } /* namespace Swagger */ #endif /* SWGTimeData_H_ */
[ "vivek0@users.noreply.github.com" ]
vivek0@users.noreply.github.com
f55d500e9f660b0aae26d2a9711491284132b5cb
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/15/52/12.cpp
e7b8ff339d729c263da49e71f8a083074f709863
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,437
cpp
#include <cmath> #include <cstdio> #include <cctype> #include <cstdlib> #include <climits> #include <cstring> #include <vector> #include <string> #include <iostream> #include <cassert> #include <algorithm> using namespace std; #define foreach(e,x) for(__typeof((x).begin()) e=(x).begin(); e!=(x).end(); ++e) const long long N = 1000 + 10; long long n, k; long long a[N]; long long r[N]; void solve() { cin >> n >> k; for(long long i = 0; i < n - k + 1; ++ i) { scanf("%lld", a + i); } long long sum = 0; for(long long i = 0; i < k; ++ i) { long long maxv = 0, minv = 0; long long cur = 0; for(long long j = i + k; j < n; j += k) { cur += a[j - k + 1] - a[j - k]; maxv = max(maxv, cur); minv = min(minv, cur); } r[i] = maxv - minv; sum -= minv; } sum = ((a[0] - sum) % k + k) % k; long long ans = 0; for(long long i = 0; i < k; ++ i) { ans = max(ans, r[i]); } long long go = 0; for(long long i = 0; i < k; ++ i) { go += ans - r[i]; } if (go < sum) { ++ ans; } cout << ans << endl; } int main() { //freopen("B-small-attempt0.in", "r", stdin); freopen("B-small-attempt0.out", "w", stdout); //freopen("B-small-attempt1.in", "r", stdin); freopen("B-small-attempt1.out", "w", stdout); freopen("B-large.in", "r", stdin); freopen("B-large.out", "w", stdout); int test_case; cin >> test_case; for(int i = 0; i < test_case; ++ i) { printf("Case #%d: ", i + 1); solve(); } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
4b1e65563210b0e51083796b6c287a00620cc616
d514636c43099f00a264da7846fcee5842468429
/Labs/Numerical/nics/nics.h
39b51cae364d515b8712e7c90ff927f985ad10c0
[ "MIT" ]
permissive
jadnohra/jad-pre-2015-dabblings
92de27c6184a255dfdb4ed9ee2148d4bf71ced1e
368cbd39c6371b3e48b0c67d9a83fc20eee41346
refs/heads/master
2021-07-22T20:07:18.651650
2017-11-03T11:31:18
2017-11-03T11:31:18
109,386,288
0
0
null
null
null
null
UTF-8
C++
false
false
23,864
h
#ifndef NICS_H #define NICS_H #pragma warning( push ) #pragma warning( disable : 4996 ) #pragma warning( disable : 4003 ) #pragma warning( disable : 4291 ) #include "../flann/src/cpp/flann/flann.hpp" #if 0 //#pragma comment( lib, "../../flann/build/lib/Release/flann_cpp_s") #else #pragma comment( lib, "../../flann/build/lib/Debug/flann_cpp_s") #endif #include "../randomc/randomc.h" #pragma comment( lib, "../../randomc/randomc/release/randomc") namespace nics { template<typename Graph, typename Vertex, typename DistT> struct Rrt { typedef Vertex(*randConfFunc)(void* ctx); typedef Vertex(*newConfFunc)(void* ctx, const Vertex& v, const DistT& dq); typedef Vertex(*nearestFunc)(void* ctx, const Vertex& v, Graph& G); typedef void(*addFunc)(void* ctx, Graph& G, const Vertex& from, const Vertex& to); static Vertex next(void* ctx, Graph& G, DistT dq, randConfFunc randConf, nearestFunc nearest, newConfFunc newConf, addFunc add) { Vertex qrand = randConf(ctx); Vertex qnear = nearest(ctx, qrand, G); Vertex qnew = newConf(ctx, qnear, dq); add(ctx, G, qnear, qnew); return qnew; } }; template<typename T> struct Array { struct ChainEl { T* el; unsigned char* valid; ChainEl* next; int first_invalid; }; typedef void(*dtorFunc)(void* ctxt, T* el); static void _dtor(void* ctxt, ChainEl* cel, int size, dtorFunc dtor) { if (cel) { if (cel->next) _dtor(ctxt, cel->next, size, dtor); if (dtor) { for (int i=0;i<size;++i) if (cel->valid[i]) dtor(ctxt, cel->el+i); } free(cel->el); free(cel->valid); free(cel); } } void* ctxt; ChainEl* cel; int chain_count; int chain_size; dtorFunc dtor; Array(int chain_size_ = 32,dtorFunc dtor_ = 0) : ctxt(0), cel(0), chain_count(0), chain_size(chain_size_), dtor(dtor_) {} ~Array() { _dtor(ctxt, cel, chain_size, dtor); } ChainEl* alloc() { ChainEl* cel = (ChainEl*) malloc(sizeof(ChainEl)); cel->first_invalid = 0; cel->el = (T*) malloc(chain_size*sizeof(T)); cel->valid = (unsigned char*) malloc(chain_size*sizeof(unsigned char)); for (int i=0;i<chain_size;++i) cel->valid[i]=0; cel->next = 0; return cel; } struct Add { Array& arr; ChainEl* cel; int i; Add(Array& arr_) : arr(arr_), cel(arr_.cel) { if (cel) while (cel->first_invalid >= arr.chain_size && cel->next) cel = cel->next; i = (cel ? cel->first_invalid : -1); } T* add() { if (cel == 0) { cel = arr.cel = arr.alloc(); i=0; cel->first_invalid = i+1; cel->valid[i]=1; return &cel->el[i++]; } while(1) { while(i<arr.chain_size && cel->valid[i]) i++; if (i+1>=arr.chain_size) { cel->first_invalid = i+1; cel = cel->next = arr.alloc(); i=0; cel->valid[i]=1; cel->first_invalid = i+1; return &cel->el[i++]; } else { cel->first_invalid = i+1; cel->valid[i]=1; return &cel->el[i++]; } } } }; struct Iter { Array& arr; ChainEl* cel; int i; Iter(Array& arr_) : arr(arr_), cel(arr_.cel), i(0) {} T* next() { while(cel) { while(i<arr.chain_size && !cel->valid[i]) i++; if (i+1>=arr.chain_size) { cel = cel->next; i=0; } else { return &cel->el[i++]; } } return 0; } }; }; struct CubeNd { template <typename T, int Dim, int Di> struct Impl { static void build_cube_rec(T* cube, T radius, int& index) { int i; i= index; Impl<T, Dim, Di+1>::build_cube_rec(cube, radius, index); while(i < index) cube[(i++)*Dim+Di] = -radius; i= index; Impl<T, Dim, Di+1>::build_cube_rec(cube, radius, index); while(i < index) cube[(i++)*Dim+Di] = radius; } }; template <typename T, int Dim> struct Impl<T, Dim, Dim> { static void build_cube_rec(T* cube, T radius, int& index) { index++; } }; template <typename T, int Dim> static void build_cube(T* cube, T radius) { int index = 0; Impl<T, Dim, 0>::build_cube_rec(cube, radius, index); } }; struct ChoiceNd { template <int Dim, int Di> struct Impl { static void build_choices_rec(int* cube, int& index) { int i; i= index; Impl<Dim, Di+1>::build_choices_rec(cube, index); while(i < index) cube[(i++)*Dim+Di] = -1; i= index; Impl<Dim, Di+1>::build_choices_rec(cube, index); while(i < index) cube[(i++)*Dim+Di] = 0; i= index; Impl<Dim, Di+1>::build_choices_rec(cube, index); while(i < index) cube[(i++)*Dim+Di] = 1; } }; template <int Dim> struct Impl<Dim, Dim> { static void build_choices_rec(int* cube, int& index) { index++; } }; template <int Dim> static void build_choices(int* cube) { int index = 0; Impl<Dim, 0>::build_choices_rec(cube, index); } }; template<typename T, int Dim> struct Rrt_Rn { enum { D = Dim }; typedef T Type; typedef T Scalar; typedef Rrt_Rn<T, Dim> This; typedef flann::Matrix<T> Matrix; typedef flann::L2<T> DistAlgo; typedef flann::Index<DistAlgo> Index; typedef T* Vertex; typedef Rrt<Index, Vertex, T> RrtImpl; struct Point { T v[Dim]; }; Index* index; T bound_min[Dim]; T bound_max[Dim]; T vertex_rand[Dim]; T vertex_new[Dim]; T dq; typedef Array<Point> Points; Points points; flann::Matrix<size_t> query_indices; flann::Matrix<T> query_dists; flann::SearchParams query_params; CRandomMersenne random; Rrt_Rn() : index(0), random(0), query_indices(new size_t[1*Dim], 1, Dim), query_dists(new T[1*Dim], 1, Dim), points(1024, 0) {} ~Rrt_Rn() { delete index; } void setBound(int di, T min, T max) { bound_min[di] = min; bound_max[di] = max; } void setBounds(T min, T max) { for (int i=0;i<Dim;++i) setBound(i, min, max); } Vertex init(T min, T max, T dq_) { dq = dq_; setBounds(min, max); //flann::AutotunedIndexParams params; // this causes problems with getPoint //flann::KMeansIndexParams params; // crashes in rtt_test1 at index 2560 flann::KDTreeIndexParams params; //flann::LinearIndexParams params; //flann::CompositeIndexParams params; Points::Add add(points); Vertex v = add.add()->v; for (int i=0; i<Dim; ++i) v[i] = bound_min[i] + T(0.5) * (bound_max[i]-bound_min[i]); Matrix m(v, 1, Dim); index = new Index(m, params); index->buildIndex(); return vertex_new; } Vertex next() { return RrtImpl::next(this, *index, dq, sRandConf, sNearest, sNewConf, sAdd); } Vertex nextRand() { Vertex v = randConf(); add(*index, 0, v); return v; } static T lenSq(Vertex v) { T l=T(0); for (int i=0; i<Dim; ++i) l += v[i]*v[i]; return l; } static void copy(Vertex src, Vertex dest) { for (int i=0; i<Dim; ++i) dest[i]=src[i]; } static void add(Vertex a, Vertex b, Vertex c) { for (int i=0; i<Dim; ++i) c[i]=a[i]+b[i]; } void _rand_0_1(Vertex v) { for (int i=0; i<Dim; ++i) v[i] = T(random.Random()); } void rand_0_1(Vertex v) { do _rand_0_1(v); while(lenSq(v)==T(0)); } void rand_m1_1(Vertex v) { rand_0_1(v); for (int i=0; i<Dim; ++i) v[i] = T((random.IRandom(0,1)*2)-1) * v[i]; } void rand_nv(Vertex v) { rand_m1_1(v); T in = T(1)/lenSq(v); for (int i=0; i<Dim; ++i) v[i] *= in; } Vertex randConf() { for (int i=0; i<Dim; ++i) vertex_rand[i] = bound_min[i] + T(random.Random()) * (bound_max[i]-bound_min[i]); return vertex_rand; } Vertex newConf(const Vertex& v, const T& dq) { // TODO: should this not be clipped to the boundaries? check the paper. T dv[Dim]; rand_nv(dv); for (int i=0; i<Dim; ++i) vertex_new[i] = v[i]+(dv[i]*dq); return vertex_new; } Vertex nearest(const Vertex& v, Index& G) { Matrix query(v, 1, Dim); index->knnSearch(query, query_indices, query_dists, Dim, query_params); return G.getPoint(*query_indices[0]); } void add(Index& G, const Vertex& from, const Vertex& to) { Points::Add add(points); Vertex v = add.add()->v; copy(to, v); Matrix m(v, 1, Dim); G.addPoints(m); } static Vertex sRandConf(void* ctx) { return ((This*) ctx)->randConf(); } static Vertex sNewConf(void* ctx, const Vertex& v, const T& dq) { return ((This*) ctx)->newConf(v, dq); } static Vertex sNearest(void* ctx, const Vertex& v, Index& G) { return ((This*) ctx)->nearest(v, G); } static void sAdd(void* ctx, Index& G, const Vertex& from, const Vertex& to) { return ((This*) ctx)->add(G, from, to); } static void build_cube(T* cube, T radius) { CubeNd::build_cube<Type, D>(cube, radius); } static void build_choices(int* cube) { ChoiceNd::build_choices<D>(cube); } }; void flann_test1() { typedef float T; int Dim = 1; typedef flann::Matrix<T> Matrix; typedef flann::L2<T> DistAlgo; typedef flann::Index<DistAlgo> Index; typedef Rrt<Index, void*, T> RrtImpl; flann::AutotunedIndexParams params; T data[] = { 0.0f, 1.0f, 10.0f, 20.0f, 100.0f }; Matrix m(data, 5, Dim); Index index(m, params); index.buildIndex(); { flann::AutotunedIndexParams params; T data[] = { 101.0f }; Matrix m(data, 1, Dim); index.addPoints(m); } { T qdata[] = { 8.0f, 101.5f }; Matrix mq(qdata, 2, Dim); flann::Matrix<size_t> indices(new size_t[mq.rows*Dim], mq.rows, Dim); flann::Matrix<T> dists(new T[mq.rows*Dim], mq.rows, Dim); flann::SearchParams sparams; index.knnSearch(mq, indices, dists, Dim, sparams); int x=0;x; for (size_t i=0;i<indices.rows;++i) { size_t qi = *indices[i]; T di = *dists[i]; int x=0;x; } } } void flann_test2() { typedef float T; int Dim = 2; typedef flann::Matrix<T> Matrix; typedef flann::L2<T> DistAlgo; typedef flann::Index<DistAlgo> Index; typedef Rrt<Index, void*, T> RrtImpl; //flann::AutotunedIndexParams params; flann::KDTreeIndexParams params; T data[] = { 0.0f,0.0f, 5.0f,5.0f, 10.0f,10.0f, 20.0f,20.0f, 100.0f,100.0f }; Matrix m(data, 5, Dim); Index index(m, params); index.buildIndex(); { T data[] = { 101.0f,101.0f }; Matrix m(data, 1, Dim); index.addPoints(m); } { T qdata[] = { 1.0f,1.0f, 101.5f,101.5f }; Matrix mq(qdata, 2, Dim); flann::Matrix<size_t> indices(new size_t[mq.rows*Dim], mq.rows, Dim); flann::Matrix<T> dists(new T[mq.rows*Dim], mq.rows, Dim); flann::SearchParams sparams; index.knnSearch(mq, indices, dists, Dim, sparams); int x=0;x; for (size_t i=0;i<indices.rows;++i) { size_t qi = *indices[i]; T di = *dists[i]; T* v = index.getPoint(qi); int x=0;x; } } } } #pragma warning( pop ) namespace nics { namespace fp754 { enum { FLTMASK_SGN = 0x80000000, FLTMASK_EXP = 0x7F800000, FLTMASK_MANT = 0x007FFFFF, FLTSHIFT_EXP = 23, FLTCT_EXPm23 = 0x34000000, FLTCT_EXPm24 = 0x33800000, FLTCT_MANTLP = 0x00000001, FLTCT_EXP127 = 0x7F000000, FLTCT_EXPm126 = 0x00800000, FLTCT_EXP0 = 0x3F800000, FLTCT_NAN = 0xFFFFFFFF, FLTCT_pINF = 0x7F800000, FLTCT_nINF = 0xFF800000, }; float h2f(unsigned int hex) { float f; *((unsigned int*) ((void*) &f)) = hex; return f; } unsigned int f2h(float f) { unsigned int hex = *((unsigned int*) ((void*) &f)); return hex; } float nextFloat(float f) { const unsigned int hex = f2h(f); const unsigned int sgn = (hex & FLTMASK_SGN); const unsigned int exp = (hex & FLTMASK_EXP); const unsigned int mant = (hex & FLTMASK_MANT); if (hex == 0) return h2f(0 | FLTCT_EXPm126 | (0) ); if (mant != FLTMASK_MANT) return h2f(sgn | exp | (mant+1) ); if (exp < FLTCT_EXP127) return h2f(sgn | (exp+ (1<<FLTSHIFT_EXP) ) | (0) ); return f; } float prevFloat(float f) { const unsigned int hex = f2h(f); const unsigned int sgn = (hex & FLTMASK_SGN); const unsigned int exp = (hex & FLTMASK_EXP); const unsigned int mant = (hex & FLTMASK_MANT); if (hex == 0) return h2f( (unsigned int) ( FLTMASK_SGN | FLTCT_EXPm126 | 0 ) ); if (mant != 0) return h2f(sgn | exp | (mant-1) ); if (exp != 0) return h2f(sgn | (exp- (1<<FLTSHIFT_EXP)) | (FLTMASK_MANT) ); return f; } float prevFloats(float f, int cnt) { float x = f; for (int i=0;i<cnt;++i) x = prevFloat(x); return x; } float nextFloats(float f, int cnt) { float x = f; for (int i=0;i<cnt;++i) x = nextFloat(x); return x; } float walkFloats(float f, int cnt) { if (cnt > 0) return nextFloats(f, cnt); return prevFloats(f, -cnt); } float floatMachineEps() { return 0.5f * h2f(FLTCT_EXPm23); } bool isDenorm(float f) { unsigned int hex = f2h(f); return (hex & FLTMASK_EXP) == 0; } bool isNegBitSet(float f) { unsigned int hex = f2h(f); return (hex & FLTMASK_SGN) == FLTMASK_SGN; } float negBitf(float f) { return isNegBitSet(f) ? -1.0f : 1.0f; } // #include <float.h> // void getX87Precision() // { // unsigned int fp87 = _control87( 0, 0 ); // if ( (fp87 & _MCW_PC) == _PC_64) // return 64; // if ( (fp87 & _MCW_PC) == _PC_53) // return 53; // if ( (fp87 & _MCW_PC) == _PC_24) // return 24; // // return 0; // } } namespace fp754 { template<int MantissaBits> struct float_reduce_chop { enum { Mask = (unsigned int(-1))<< (23-MantissaBits) }; static float reduce(float f) { static int guard[(23-MantissaBits)+1]; using namespace fp754; return h2f(f2h(f)&Mask); } }; template<int MantissaBits> struct float_reduce_round { enum { Mask = (unsigned int(-1))<< (23-MantissaBits) }; enum { RoundEps = (unsigned int(1))<< (23-MantissaBits) }; static float reduce(float f) { using namespace fp754; static int guard[(23-MantissaBits)-1]; if (f < 0.0f) return -reduce(-f); float rnd_mul = h2f(FLTCT_EXP0 | (RoundEps>>1)); float r = h2f(f2h(f * rnd_mul) & Mask); return r; } }; template<typename Reduce> struct float_reduce { float v; static float reduce(float f) { return Reduce::reduce(f); } float_reduce() {} float_reduce(const float f) { v = reduce(f); } //operator float() { return v; } operator double() { return double(v); } float_reduce operator-() { return float_reduce(-v); } float_reduce operator+(const float_reduce& v1) { float o = reduce(v+v1.v); return float_reduce(o); } float_reduce operator-(const float_reduce& v1) { float o = reduce(v-v1.v); return float_reduce(o); } float_reduce operator*(const float_reduce& v1) { float o = reduce(v*v1.v); return float_reduce(o); } float_reduce operator/(const float_reduce& v1) { float o = reduce(v/v1.v); return float_reduce(o); } float_reduce& operator*=(const float_reduce& v1) { v = reduce(v*v1.v); return *this; } float_reduce& operator+=(const float_reduce& v1) { v = reduce(v+v1.v); return *this; } float_reduce& operator/=(const float_reduce& v1) { v = reduce(v/v1.v); return *this; } bool operator==(const float_reduce& v1) const { return v >= v1.v; } bool operator>=(const float_reduce& v1) const { return v >= v1.v; } bool operator>(const float_reduce& v1) const { return v > v1.v; } bool operator<(const float_reduce& v1) const { return v < v1.v; } }; template<typename Reduce> float_reduce<Reduce> abs(float_reduce<Reduce> v) { return v.0 >= 0.0f ? v : -v; } } template<typename T> T m_abs(T v) { return v >= T(0) ? v : -v; } template<typename T> T m_max(T v1, T v2) { return v1 >= v2 ? v1 : v2; } template<typename T> T m_min(T v1, T v2) { return v1 >= v2 ? v1 : v2; } template<typename T> struct UnsignedType {}; template<> struct UnsignedType<int> { typedef unsigned int UT; }; template<> struct UnsignedType<char> { typedef unsigned char UT; }; template<> struct UnsignedType<short> { typedef unsigned short UT; }; template<typename T, typename UT = UnsignedType<T>::UT > // T must be unsigned struct tbint { typedef UT ui; ui m_1[4]; int m_sign; unsigned int m_size; unsigned int size() const { return m_size; } void setSize(unsigned int s) { m_size = s; } int& sign() { return m_sign; } const int& sign() const { return m_sign; } ui& part(unsigned int i) { return m_1[i]; } const ui& part(unsigned int i) const { return m_1[i]; } ui epart(unsigned int i) const { return i >= size() ? 0 : m_1[i]; } tbint() : m_size(0) {} tbint(UT i, int sgn=1) : m_size(1) { part(0) = i; sign() = sgn; } template<typename UJ> void setu(UJ j, int sgn=1) { sign()=sgn; setSize(sizeof(UJ)/sizeof(UT)); const UJ mask = (UJ) UT(-1); for (unsigned int i=0;i<m_size;++i) { part(i)=j&mask; j >>= (sizeof(UT)*8); } trim(); } template<typename J> void set(const J j) { typedef UnsignedType<J>::UT UJ; if (j>=0) setu((UJ) j, 1); else setu((UJ) -j, -1); } template<typename UJ> void getu(UJ& j) { j = 0; for (unsigned int i=0;i<m_size;++i) { j |= (UJ(part(i)) << (i*sizeof(UT)*8)); } } template<typename UJ> void overflowsu() { int zc = 0; for (unsigned int i=0, j=m_size-1; i<m_size && part(j)==0; ++i, --j) zc++; return (m_size-zc)*sizeof(UT) > sizeof(UJ); } template<typename J> void get(J& j) { typedef UnsignedType<J>::UT UJ; UJ uj; getu(uj); j = sign() * J(uj); } template<typename J> J get() { J j; get(j); return j; } void trim() { int zc = 0; for (unsigned int i=0, j=m_size-1; i<m_size && part(j)==0; ++i, --j) zc++; setSize(m_size-zc); } void add(const tbint& a, const tbint& b) { add(a, b, b.sign()); } void sub(const tbint& a, const tbint& b) { add(a, b, -1*b.sign()); } void add(const tbint& a, const tbint& b, int bsign) { if (a.sign() == bsign) { bool al = (a.size() <= b.size()); const tbint& sl = al ? a : b; const tbint& sg = al ? b : a; unsigned int ms = m_max(a.size(), b.size()); if (a.size() == b.size()) { setSize(ms+1); part(ms) = 0; } else setSize(ms); ui carry = 0; sign() = a.sign(); for (unsigned int i=0; i<ms; ++i) { ui ai = sl.epart(i); ui bi = sg.part(i); ui s = ai+bi+carry; carry = s >= ai ? 0 : 1; part(i) = s; } if (carry) part(ms) = carry; } else { ui ap = (a.sign() >= 0); const tbint& sp = ap ? a : b; const tbint& sn = ap ? b : a; if (_abs_gte(sp, sn)) { _sub_abs_gl(sp, sn); } else { _sub_abs_gl(sn, sp); sign() = -1; } } } bool _abs_gte(const tbint& a, const tbint& b) { unsigned int ms = m_max(a.size(), b.size()); for (unsigned int i=ms-1, j=0; j<ms; --i, ++j) { ui ai = a.epart(i); ui bi = b.epart(i); if (ai > bi) return true; else if (ai < bi) return false; } return true; } void _sub_abs_gl(const tbint& g, const tbint& l) { unsigned int ms = g.size(); setSize(ms); ui carry = 0; sign() = 1; int zc = 0; for (unsigned int i=0; i<ms; ++i) { ui ai = l.epart(i); ui bi = g.part(i); ui s = (bi-carry)-ai; carry = s >= bi ? 1 : 0; part(i) = s; } trim(); } void zeroParts() { for (unsigned int i=0;i<m_size; ++i) part(i) = 0; } void mul(const tbint& a, const tbint& b) { sign() = a.sign()*b.sign(); unsigned int ms = 2*m_max(a.size(), b.size()); setSize(ms); zeroParts(); struct Impl { ui low; ui high; ui shift; Impl() { low = 0; for (int i=0;i<sizeof(ui)*8/2;++i) low |= 1<<i; high = ~(low); shift = sizeof(ui)*8/2; } static void add(tbint& self, const ui& v, ui pc, ui carry = 0) { unsigned int i = pc; do { ui s = self.part(i) + v + carry; carry = (s >= self.part(i) ? 0 : 1); self.part(i) = s; ++i; } while(i < self.size() && carry); } static void addhi(const Impl& impl, tbint& self, const ui& v, ui pc) { const ui vl = v & impl.low; const ui vh = v & impl.high; ui s = self.part(pc) + (vl << impl.shift); ui carry = (s >= self.part(pc) ? 0 : 1); self.part(pc) = s; add(self, vh >> impl.shift, pc+1, carry); } }; static const Impl impl; for (unsigned int i=0; i<b.size(); ++i) { ui bi = b.part(i); ui bil = bi & impl.low; ui bih = (bi & impl.high) >> impl.shift; for (unsigned int j=0; j<a.size(); ++j) { ui ai = a.part(j); ui ail = ai & impl.low; ui aih = (ai & impl.high) >> impl.shift; ui p1 = bil*ail; ui p2 = bil*aih; ui p3 = bih*ail; ui p4 = bih*aih; Impl::add(*this, p1, i+j); Impl::addhi(impl, *this, p2, i+j); Impl::addhi(impl, *this, p3, i+j); Impl::add(*this, p4, i+j+1); } } } int cmp(const tbint& b_) const { const tbint& a_ = *this; if (a_.sign() == b_.sign()) { unsigned int ms = m_max(a_.size(), b_.size()); bool al = (a_.size() <= b_.size()); const tbint& a = al ? a_ : b_; const tbint& b = al ? b_ : a_; int result = 0; for (unsigned int i=0; i<ms && result==0; ++i) { ui ai = a.epart(i); ui bi = b.part(i); if (ai > bi) result = a.sign(); else if (ai > bi) result = -a.sign(); } return result; } else { // TODO: zero case! return (a_.sign() > b_.sign() ? 1 : -1); } } bool isZero() const { int zc = 0; for (unsigned int i=0, j=m_size-1; i<m_size && part(j)==0; ++i, --j) zc++; return (m_size-zc == 0); } bool isOne() const { int zc = 0; for (unsigned int i=0, j=m_size-1; i<m_size && part(j)==0; ++i, --j) zc++; return (m_size-zc == 1 && part(0)==1); } bool isMinusOne() const { int zc = 0; for (unsigned int i=0, j=m_size-1; i<m_size && part(j)==0; ++i, --j) zc++; return (m_size-zc == 1 && part(0)==1 && sign()==-1); } void copy(const tbint& a) { setSize(a.size()); for (unsigned int i=0; i<size(); ++i) part(i) = a.part(i); sign() = a.sign(); } void gdc(const tbint& a_, const tbint& b_) { int rel = a_.cmp(b_); if (rel == 0) { copy(a_); } else { tbint a, b; tbint diff; a.copy(a_); a.sign() = 1; b.copy(b_); b.sign() = 1; diff.sub(a, b); while(!diff.isOne() && !diff.isMinusOne() && !diff.isZero()) { if (diff.sign() >= 0) a.copy(diff); else b.copy(diff); diff.sub(a, b); } if (diff.isZero()) { copy(a); } else { copy(diff); sign() = 1; } } } }; typedef tbint<int> bint; typedef tbint<char> bint8; typedef tbint<short> bint16; template<typename BINT> struct trational { BINT num, denom; void add(const trational& a, const trational& b) { BINT num1; num1.mul(a.num, b.denom); BINT num2; num2.mul(a.denom, b.num); num.add(num1, num2); denom.mul(a.denom, b.denom); reduce(); } void reduce() { } }; } #endif // NICS_H
[ "pinkfish@e0e46c49-be69-4f5a-ad62-21024a331aea" ]
pinkfish@e0e46c49-be69-4f5a-ad62-21024a331aea
dcfe6c1b69f716462c8cd8b882155d64eae6d1c1
24bc4990e9d0bef6a42a6f86dc783785b10dbd42
/components/live_caption/views/caption_bubble_model.cc
b33f96c9267f6e561fef4de670b6aef5cdfb752d
[ "BSD-3-Clause" ]
permissive
nwjs/chromium.src
7736ce86a9a0b810449a3b80a4af15de9ef9115d
454f26d09b2f6204c096b47f778705eab1e3ba46
refs/heads/nw75
2023-08-31T08:01:39.796085
2023-04-19T17:25:53
2023-04-19T17:25:53
50,512,158
161
201
BSD-3-Clause
2023-05-08T03:19:09
2016-01-27T14:17:03
null
UTF-8
C++
false
false
3,297
cc
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/live_caption/views/caption_bubble_model.h" #include "base/functional/callback_forward.h" #include "base/metrics/histogram_functions.h" #include "components/live_caption/caption_bubble_context.h" #include "components/live_caption/views/caption_bubble.h" namespace { // The caption bubble contains 2 lines of text in its normal size and 8 lines // in its expanded size, so the maximum number of lines before truncating is 9. constexpr int kMaxLines = 9; } // namespace namespace captions { CaptionBubbleModel::CaptionBubbleModel(CaptionBubbleContext* context, OnCaptionBubbleClosedCallback callback) : caption_bubble_closed_callback_(callback), context_(context) { DCHECK(context_); } CaptionBubbleModel::~CaptionBubbleModel() { if (observer_) observer_->SetModel(nullptr); } void CaptionBubbleModel::SetObserver(CaptionBubble* observer) { if (observer_) return; observer_ = observer; if (observer_) { observer_->OnTextChanged(); observer_->OnErrorChanged( CaptionBubbleErrorType::kGeneric, base::RepeatingClosure(), base::BindRepeating( [](CaptionBubbleErrorType error_type, bool checked) {})); } } void CaptionBubbleModel::RemoveObserver() { observer_ = nullptr; } void CaptionBubbleModel::OnTextChanged() { if (observer_) observer_->OnTextChanged(); } void CaptionBubbleModel::SetPartialText(const std::string& partial_text) { partial_text_ = partial_text; OnTextChanged(); if (has_error_) { has_error_ = false; if (observer_) observer_->OnErrorChanged( CaptionBubbleErrorType::kGeneric, base::RepeatingClosure(), base::BindRepeating( [](CaptionBubbleErrorType error_type, bool checked) {})); } } void CaptionBubbleModel::CloseButtonPressed() { caption_bubble_closed_callback_.Run(context_->GetSessionId()); Close(); } void CaptionBubbleModel::Close() { is_closed_ = true; ClearText(); } void CaptionBubbleModel::OnError( CaptionBubbleErrorType error_type, OnErrorClickedCallback error_clicked_callback, OnDoNotShowAgainClickedCallback error_silenced_callback) { has_error_ = true; error_type_ = error_type; if (observer_) { base::UmaHistogramEnumeration( "Accessibility.LiveCaption.CaptionBubbleError", error_type); observer_->OnErrorChanged(error_type, std::move(error_clicked_callback), std::move(error_silenced_callback)); } } void CaptionBubbleModel::ClearText() { partial_text_.clear(); final_text_.clear(); OnTextChanged(); } void CaptionBubbleModel::CommitPartialText() { final_text_ += partial_text_; partial_text_.clear(); if (!observer_) return; // Truncate the final text to kMaxLines lines long. This time, alert the // observer that the text has changed. const size_t num_lines = observer_->GetNumLinesInLabel(); if (num_lines > kMaxLines) { const size_t truncate_index = observer_->GetTextIndexOfLineInLabel(num_lines - kMaxLines); final_text_.erase(0, truncate_index); OnTextChanged(); } } } // namespace captions
[ "roger@nwjs.io" ]
roger@nwjs.io
3fa3e99d8c5cbf121e9207f619d33d1b337beda2
dfb7297f114bbff7a89fea86cb9b8e0e16243d01
/PAT/PAT/1047_cin版,动不动时.cpp
acc4f2595d8a9290443a61fa977e1953546457cf
[]
no_license
rainingapple/algorithm-competition-code
c06bd549d44e14c64e808d7026a0204d285f1fb3
809bff5cdf092568de47def7d24d36edef8d0c1e
refs/heads/main
2023-03-30T13:11:23.359366
2021-04-09T01:29:18
2021-04-09T01:29:18
343,407,072
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
//#include<iostream> //#include<algorithm> //#include<vector> //#include<map> //using namespace std; //string stu[40005]; //bool cmp(const int& s1, const int& s2) { // return stu[s1] < stu[s2]; //} //int main() { // int n, k; // scanf("%d%d", &n, &k); // vector<vector<int>> m(k+1); // for (int i = 1;i <= n;i++) { // cin >> stu[i]; // int total; // cin >> total; // for (int j = 0;j < total;j++) { // int temp; // scanf("%d", &temp); // m[temp].push_back(i); // } // } // for (int i = 1;i <= k;i++) { // printf("%d %d\n", i, m[i].size()); // sort(m[i].begin(), m[i].end(), cmp); // for (int j = 0;j < m[i].size();j++) { // printf("%s\n", stu[m[i][j]].c_str()); // } // } // return 0; //}
[ "825140645@qq.com" ]
825140645@qq.com
921b6864650b7130f2009d3e7bf011d0969a88e5
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/UnityEngine_Networking_UnityEngine_Networking_Sync3645530894.h
368fc7b14bac8b2c14494cee7c58e9687c30ac4d
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
3,064
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Collections.Generic.List`1<System.Object> struct List_1_t2058570427; // UnityEngine.Networking.NetworkBehaviour struct NetworkBehaviour_t3873055601; // UnityEngine.Networking.SyncList`1/SyncListChanged<System.Object> struct SyncListChanged_t1055719745; #include "mscorlib_System_Object2689449295.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.SyncList`1<System.Object> struct SyncList_1_t3645530894 : public Il2CppObject { public: // System.Collections.Generic.List`1<T> UnityEngine.Networking.SyncList`1::m_Objects List_1_t2058570427 * ___m_Objects_0; // UnityEngine.Networking.NetworkBehaviour UnityEngine.Networking.SyncList`1::m_Behaviour NetworkBehaviour_t3873055601 * ___m_Behaviour_1; // System.Int32 UnityEngine.Networking.SyncList`1::m_CmdHash int32_t ___m_CmdHash_2; // UnityEngine.Networking.SyncList`1/SyncListChanged<T> UnityEngine.Networking.SyncList`1::m_Callback SyncListChanged_t1055719745 * ___m_Callback_3; public: inline static int32_t get_offset_of_m_Objects_0() { return static_cast<int32_t>(offsetof(SyncList_1_t3645530894, ___m_Objects_0)); } inline List_1_t2058570427 * get_m_Objects_0() const { return ___m_Objects_0; } inline List_1_t2058570427 ** get_address_of_m_Objects_0() { return &___m_Objects_0; } inline void set_m_Objects_0(List_1_t2058570427 * value) { ___m_Objects_0 = value; Il2CppCodeGenWriteBarrier(&___m_Objects_0, value); } inline static int32_t get_offset_of_m_Behaviour_1() { return static_cast<int32_t>(offsetof(SyncList_1_t3645530894, ___m_Behaviour_1)); } inline NetworkBehaviour_t3873055601 * get_m_Behaviour_1() const { return ___m_Behaviour_1; } inline NetworkBehaviour_t3873055601 ** get_address_of_m_Behaviour_1() { return &___m_Behaviour_1; } inline void set_m_Behaviour_1(NetworkBehaviour_t3873055601 * value) { ___m_Behaviour_1 = value; Il2CppCodeGenWriteBarrier(&___m_Behaviour_1, value); } inline static int32_t get_offset_of_m_CmdHash_2() { return static_cast<int32_t>(offsetof(SyncList_1_t3645530894, ___m_CmdHash_2)); } inline int32_t get_m_CmdHash_2() const { return ___m_CmdHash_2; } inline int32_t* get_address_of_m_CmdHash_2() { return &___m_CmdHash_2; } inline void set_m_CmdHash_2(int32_t value) { ___m_CmdHash_2 = value; } inline static int32_t get_offset_of_m_Callback_3() { return static_cast<int32_t>(offsetof(SyncList_1_t3645530894, ___m_Callback_3)); } inline SyncListChanged_t1055719745 * get_m_Callback_3() const { return ___m_Callback_3; } inline SyncListChanged_t1055719745 ** get_address_of_m_Callback_3() { return &___m_Callback_3; } inline void set_m_Callback_3(SyncListChanged_t1055719745 * value) { ___m_Callback_3 = value; Il2CppCodeGenWriteBarrier(&___m_Callback_3, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "gdesmarais@gsngames.com" ]
gdesmarais@gsngames.com
34f6a5b13be4ae8e484f089a16e9d8c22830378f
ca0d65a2519697f1fab4d0467271e032f72feed5
/darts-x86/omp2cd-examples/tests/ompcodeletclause-test/ompcodeletclause.output.darts.cpp
4cdef93e6142638db260219a5ecfffdb3cfe2a54
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jandres742/omp2cd
fca943f38e77ff9d32d066c6713e4556cf30fd54
15f64d65c41a1b9238af81fe2627c1b8e12ceca7
refs/heads/master
2020-12-24T11:09:41.811053
2017-06-28T19:23:40
2017-06-28T19:23:40
73,186,762
6
1
null
null
null
null
UTF-8
C++
false
false
11,342
cpp
#include "ompcodeletclause.output.darts.h" using namespace darts; using namespace std; int NUM_THREADS; /*Function: main, ID: 1*/ int main(int argc, char** argv) { getOMPNumThreads(); getOMPSchedulePolicy(); getTPLoopThresholds(); getNumTPs(); affin = new ThreadAffinity( ompNumThreads / NUMTPS - 1, NUMTPS, COMPACT, getDARTSTPPolicy(), getDARTSMCPolicy()); affinMaskRes = affin->generateMask(); myDARTSRuntime = new Runtime(affin); RuntimeFinalCodelet = &(myDARTSRuntime->finalSignal); /*main:1*/ /*CompoundStmt:5*/ srand(time((time_t*)((void*)0))); int size, i; if (argc <= 1) { size = 31; } else { size = atoi(argv[1]); } if (size < 0) { printf("Size should be greater than 0\n"); return 0; } NUM_THREADS = omp_get_max_threads(); int* inVector = (int*)malloc(size * sizeof(int)); int* outVector = (int*)malloc(NUM_THREADS * sizeof(int)); int threadID = -1; for (i = 0; i < size; i++) { inVector[i] = rand() % 100 - 50; } int sequentialSum = 0; for (i = 0; i < size; i++) { sequentialSum += inVector[i]; } int parallelSum = 0; if (affinMaskRes) { myDARTSRuntime->run(launch<TP57>(ompNumThreads * DARTS_CODELETS_MULT, 0, RuntimeFinalCodelet, (int*)&((i)), (int**)&((inVector)), (int**)&((outVector)), (int*)&((parallelSum)), (int*)&((size)), (int*)&((threadID)))); } if (sequentialSum != parallelSum || threadID != 0) { printf("Error in master test\n"); } for (i = 0; i < NUM_THREADS; i++) { if (outVector[i] != (sequentialSum + 10)) { printf("Error: outVector[%d] =%d != %d\n", i, outVector[i], sequentialSum + 10); } } free(inVector); free(outVector); return 0; } /*TP57: OMPParallelDirective*/ void TP57::_barrierCodelets57::fire(void) { TP57* myTP = static_cast<TP57*>(myTP_); myTP->controlTPParent->nextCodelet->decDep(); } void TP57::_checkInCodelets59::fire(void) { if (this->getID() == 0) { invoke<TP59>(myTP, 1, this->getID(), myTP, &(*(this->inputsTPParent->inVector_darts57)), &(*(this->inputsTPParent->parallelSum_darts57)), &(*(this->inputsTPParent->size_darts57)), &(*(this->inputsTPParent->threadID_darts57))); } else { myTP->checkInCodelets70[this->getID()].decDep(); } } void TP57::_checkInCodelets70::fire(void) { /*printing node 70: DeclStmt*/ this->inputsTPParent->initLoop_darts57[this->getID()] = 0; /*printing node 71: DeclStmt*/ this->inputsTPParent->endLoop_darts57[this->getID()] = NUM_THREADS; /*Signaling next codelet from last stmt in the codelet*/ /*Signaling next codelet region: 70 nextRegion: 72 */ myTP->controlTPParent->checkInCodelets72[this->getID()].decDep(); } void TP57::_checkInCodelets72::fire(void) { /*printOMPForCodeletFireCode, inlined: 1*/ /*region 72 1*/ /*Init the vars for this region*/ /*Initialize the vars of the inlined region*/ this->inputsTPParent->endLoop_darts72[this->getLocalID()] = &(this->inputsTPParent ->endLoop_darts57[this->getLocalID()]) /*OMP_SHARED_PRIVATE - INPUT INLINED*/; this->inputsTPParent->i_darts72 = new int[myTP->numThreads] /*OMP_PRIVATE - INPUT INLINED*/; this->inputsTPParent->initLoop_darts72[this->getLocalID()] = &(this->inputsTPParent ->initLoop_darts57[this->getLocalID()]) /*OMP_SHARED_PRIVATE - INPUT INLINED*/; this->inputsTPParent->outVector_darts72 = (this->inputsTPParent->outVector_darts57) /*OMP_SHARED - INPUT INLINED*/; /*printing node 73: ForStmt*/ /*var: endLoop*/ /*var: i*/ /*var: initLoop*/ /*var: outVector*/ int* i = &(this->inputsTPParent->i_darts72[this->getLocalID()]); (void)i /*OMP_PRIVATE*/; int** outVector = (this->inputsTPParent->outVector_darts72); (void)outVector /*OMP_SHARED*/; for (int i_darts_counter_temp72 = (*(myTP->initLoop_darts72[this->getID()])); i_darts_counter_temp72 < (*(myTP->endLoop_darts72[this->getID()])); i_darts_counter_temp72++) { { (*(outVector))[(i_darts_counter_temp72)] = 10; } } /*Signaling next codelet from last stmt in the codelet*/ /*Signaling omp region's barrier*/ myTP->controlTPParent->barrierCodelets72[0].decDep(); } void TP57::_barrierCodelets72::fire(void) { TP57* myTP = static_cast<TP57*>(myTP_); { for (size_t codeletsCounter = 0; codeletsCounter < myTP->numThreads; codeletsCounter++) { myTP->checkInCodelets104[codeletsCounter].decDep(); } } } void TP57::_checkInCodelets104::fire(void) { /*Select the thread executing OMPSingleDirective 104*/ if (!__sync_val_compare_and_swap(&(myTP->TP104_alreadyLaunched), 0, 1)) { /*Init the vars for this region*/ /*Initialize the vars of the inlined region*/ this->inputsTPParent->outVector_darts104 = (this->inputsTPParent->outVector_darts57) /*OMP_SHARED - VAR INLINED*/; this->inputsTPParent->parallelSum_darts104 = (this->inputsTPParent->parallelSum_darts57) /*OMP_SHARED - VAR INLINED*/; /*printing node 106: ForStmt*/ { /*Loop's init*/ (this->inputsTPParent->i_darts104) = 0; int i_darts_counter_temp104 = (this->inputsTPParent->i_darts104); for (; i_darts_counter_temp104 < NUM_THREADS; i_darts_counter_temp104++) { (*(this->inputsTPParent->outVector_darts104))[i_darts_counter_temp104] += (*(this->inputsTPParent->parallelSum_darts104)); } (this->inputsTPParent->i_darts104) = i_darts_counter_temp104; } /*Signaling next codelet from last stmt in the codelet*/ /*Signaling omp region's barrier*/ myTP->controlTPParent->barrierCodelets104[0].decDep(); } else { /*Signaling omp region's barrier*/ myTP->barrierCodelets104[0].decDep(); } } void TP57::_barrierCodelets104::fire(void) { TP57* myTP = static_cast<TP57*>(myTP_); myTP->TPParent->barrierCodelets57[0].setDep(0); myTP->add(&(myTP->TPParent->barrierCodelets57[0])); } TP57::TP57(int in_numThreads, int in_mainCodeletID, Codelet* in_nextCodelet, int* in_i, int** in_inVector, int** in_outVector, int* in_parallelSum, int* in_size, int* in_threadID) : ThreadedProcedure(in_numThreads, in_mainCodeletID) , nextCodelet(in_nextCodelet) , TPParent(this) , controlTPParent(this) , inputsTPParent(this) , i_darts57(in_i) /*OMP_SHARED - INPUT*/ , inVector_darts57(in_inVector) /*OMP_SHARED - INPUT*/ , outVector_darts57(in_outVector) /*OMP_SHARED - INPUT*/ , parallelSum_darts57(in_parallelSum) /*OMP_SHARED - INPUT*/ , size_darts57(in_size) /*OMP_SHARED - INPUT*/ , threadID_darts57(in_threadID) /*OMP_SHARED - INPUT*/ , endLoop_darts57(new int[this->numThreads]) /*VARIABLE*/ , initLoop_darts57(new int[this->numThreads]) /*VARIABLE*/ , endLoop_darts72(new int*[this->numThreads]) , i_darts72(new int[this->numThreads]) /*OMP_PRIVATE - INPUT*/ , initLoop_darts72(new int*[this->numThreads]) , TP59Ptr(nullptr) , TP59_alreadyLaunched(0) , TP72_alreadyLaunched(0) , TP104_alreadyLaunched(0) , barrierCodelets57(new _barrierCodelets57[1]) , checkInCodelets59(new _checkInCodelets59[this->numThreads]) , checkInCodelets70(new _checkInCodelets70[this->numThreads]) , checkInCodelets72(new _checkInCodelets72[this->numThreads]) , barrierCodelets72(new _barrierCodelets72[1]) , checkInCodelets104(new _checkInCodelets104[this->numThreads]) , barrierCodelets104(new _barrierCodelets104[1]) { /*Initialize inputs and vars.*/ /*Initialize Codelets*/ barrierCodelets57[0] = _barrierCodelets57(ompNumThreads, ompNumThreads, this, 0); barrierCodelets104[0] = _barrierCodelets104(this->numThreads, this->numThreads, this, 0); barrierCodelets72[0] = _barrierCodelets72(this->numThreads, this->numThreads, this, 0); _checkInCodelets104* checkInCodelets104Ptr = (this->checkInCodelets104); _checkInCodelets72* checkInCodelets72Ptr = (this->checkInCodelets72); _checkInCodelets70* checkInCodelets70Ptr = (this->checkInCodelets70); _checkInCodelets59* checkInCodelets59Ptr = (this->checkInCodelets59); for (size_t codeletCounter = 0; codeletCounter < (size_t)this->numThreads; codeletCounter++) { (*checkInCodelets104Ptr) = _checkInCodelets104(1, 1, this, codeletCounter); checkInCodelets104Ptr++; (*checkInCodelets72Ptr) = _checkInCodelets72(1, 1, this, codeletCounter); checkInCodelets72Ptr++; (*checkInCodelets70Ptr) = _checkInCodelets70(1, 1, this, codeletCounter); checkInCodelets70Ptr++; (*checkInCodelets59Ptr) = _checkInCodelets59(1, 1, this, codeletCounter); (*checkInCodelets59Ptr).decDep(); checkInCodelets59Ptr++; } } TP57::~TP57() { delete[] endLoop_darts57; delete[] initLoop_darts57; delete[] endLoop_darts72; delete[] initLoop_darts72; delete[] barrierCodelets57; delete[] barrierCodelets104; delete[] checkInCodelets104; delete[] barrierCodelets72; delete[] checkInCodelets72; delete[] checkInCodelets70; delete[] checkInCodelets59; } /*TP59: OMPMasterDirective*/ void TP59::_checkInCodelets61::fire(void) { /*Init the vars for this region*/ /*printing node 61: BinaryOperator*/ (*(this->inputsTPParent->threadID_darts59)) = omp_get_thread_num(); /*printing node 63: ForStmt*/ { int* i = &(this->inputsTPParent->i_darts59); (void)i /*OMP_PRIVATE*/; int** inVector = (this->inputsTPParent->inVector_darts59); (void)inVector /*OMP_SHARED*/; int* parallelSum = (this->inputsTPParent->parallelSum_darts59); (void)parallelSum /*OMP_SHARED*/; int* size = (this->inputsTPParent->size_darts59); (void)size /*OMP_SHARED*/; /*Loop's init*/ (this->inputsTPParent->i_darts59) = 0; int i_darts_counter_temp59 = (this->inputsTPParent->i_darts59); for (; (i_darts_counter_temp59) < (*(size)); (i_darts_counter_temp59)++) { (*(parallelSum)) += (*(inVector))[(i_darts_counter_temp59)]; } (this->inputsTPParent->i_darts59) = i_darts_counter_temp59; } /*Signaling next codelet from last stmt in the codelet*/ /*Find and signal the next codelet*/ myTP->controlTPParent->TPParent->checkInCodelets70[this->getID()].decDep(); } TP59::TP59(int in_numThreads, int in_mainCodeletID, TP57* in_TPParent, int** in_inVector, int* in_parallelSum, int* in_size, int* in_threadID) : ompOMPMasterDirectiveTP(in_numThreads, in_mainCodeletID) , TPParent(in_TPParent) , controlTPParent(this) , inputsTPParent(this) , inVector_darts59(in_inVector) /*OMP_SHARED - INPUT*/ , parallelSum_darts59(in_parallelSum) /*OMP_SHARED - INPUT*/ , size_darts59(in_size) /*OMP_SHARED - INPUT*/ , threadID_darts59(in_threadID) /*OMP_SHARED - INPUT*/ , checkInCodelets61(1, 1, this, this->mainCodeletID) { /*Initialize inputs and vars.*/ /*Initialize Codelets*/ checkInCodelets61.decDep(); } TP59::~TP59() {}
[ "jandres742@gmail.com" ]
jandres742@gmail.com
7fc9924cb2377e0b6b6b4ee365defc96d1c2a5ee
ea3a9593e3b762b504839d436d2d78de08ce3e42
/Contest 5 quy hoach dong/di_chuyen_ve_goc_toa_do.cpp
63d70760c7c8f70493152428100a1dfeccf5255a
[]
no_license
docongban/Zcode_CTDL-GT
87a690f413af570c27ee4db494f96ea35eb30c0d
41cd48bf9de926f17058119fb5335e294329a706
refs/heads/main
2023-06-27T03:37:23.037502
2021-07-05T14:48:28
2021-07-05T14:48:28
383,173,620
1
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
/*Code By BanDC*/ //VS Code #include<bits/stdc++.h> using namespace std; long long tmp[100][100]; void Handle(int n,int m) { memset(tmp, 0, sizeof(tmp)); for(int i=0;i<100;i++) tmp[i][0]=1; for(int j=0;j<100;j++) tmp[0][j]=1; tmp[0][0]=0; for(int i=0;i<100;i++) { for(int j=0;j<100;j++) { if(i==0||j==0) continue; tmp[i][j]=tmp[i-1][j]+tmp[i][j-1]; } } cout<<tmp[n][m]; } int main() { //Handle(); int t; cin>>t; while(t--) { int n,m; cin>>n>>m; //cout<<tmp[n][m]<<endl; Handle(n,m);cout<<endl; } return 0; }
[ "banto2172001@gmail.com" ]
banto2172001@gmail.com
c1fa3f7a17500f97a78efa342e385da43aec28e7
1f032ac06a2fc792859a57099e04d2b9bc43f387
/ac/a3/6b/2b/01e10650bbd0f27933d3857ab183fd2f3e8596ef0343d883a3386ef607dbb555cbdb593f5bc328988bb038249130a64b735adc6a80f7aa45cdf54b24/sw.cpp
db6c0a4095d61db6ac98f743cf2a49b12b334336
[]
no_license
SoftwareNetwork/specifications
9d6d97c136d2b03af45669bad2bcb00fda9d2e26
ba960f416e4728a43aa3e41af16a7bdd82006ec3
refs/heads/master
2023-08-16T13:17:25.996674
2023-08-15T10:45:47
2023-08-15T10:45:47
145,738,888
0
0
null
null
null
null
UTF-8
C++
false
false
9,290
cpp
void build(Solution &s) { auto &fontconfig = s.addTarget<LibraryTarget>("freedesktop.fontconfig.fontconfig", "2.13.92"); fontconfig += RemoteFile("https://www.freedesktop.org/software/fontconfig/release/fontconfig-{v}.tar.gz"); fontconfig.ApiName = "SW_FONTCONFIG_LIBRARY_API"; fontconfig.setChecks("fontconfig", true); fontconfig += "fc-case/fccase.h", "fc-lang/fclang.h", "fontconfig/.*\\.h"_rr, "src/.*\\.c"_rr, "src/.*\\.h"_rr; fontconfig.Public += "."_id; fontconfig.Public += "src"_id; fontconfig.Public += "FLEXIBLE_ARRAY_MEMBER=1"_d; fontconfig.Public += "HAVE_DIRENT_H=1"_d; fontconfig.Public += "HAVE_FT_GET_BDF_PROPERTY=1"_d; fontconfig.Public += "HAVE_FT_GET_NEXT_CHAR=1"_d; fontconfig.Public += "HAVE_FT_GET_PS_FONT_INFO=1"_d; fontconfig.Public += "HAVE_FT_HAS_PS_GLYPH_NAMES=1"_d; fontconfig.Public += "HAVE_FT_SELECT_SIZE=1"_d; fontconfig += "FC_GPERF_SIZE_T=size_t"_d; fontconfig += "FC_TEMPLATEDIR=\"fontconfig/conf.avail\""_d; if (fontconfig.getBuildSettings().TargetOS.Type == OSType::Windows) { fontconfig.Public += "FC_CACHEDIR=\"LOCAL_APPDATA_FONTCONFIG_CACHE\""_d; fontconfig.Public += "FC_DEFAULT_FONTS=\"WINDOWSFONTDIR\""_d; } else { fontconfig.Public += "FC_CACHEDIR=\"~/.fontconfig/cache/fontconfig\""_d; fontconfig.Public += "FC_DEFAULT_FONTS=\"/usr/share/fonts\""_d; fontconfig.Public += "FONTCONFIG_PATH=\"/etc/fonts/conf.d\""_d; fontconfig.Public += "HAVE_INTEL_ATOMIC_PRIMITIVES"_d; } fontconfig.Public += "org.sw.demo.expat"_dep; fontconfig.Public += "org.sw.demo.freetype"_dep; fontconfig.Public -= "org.sw.demo.tronkko.dirent-master"_dep; { #if SW_CPP_DRIVER_API_VERSION >= 2 struct MyRule : sw::IRule { mutable std::shared_ptr<sw::builder::Command> c; sw::IRulePtr clone() const override { return std::make_unique<MyRule>(*this); } void setup(const Target &t) override { auto nt = t.as<NativeCompiledTarget *>(); for (auto &i : nt->getMergeObject().gatherIncludeDirectories()) { c->push_back("-I"); c->push_back(i); } } }; auto &t = fontconfig; auto cb = t.addCommand(); cb << cmd::prog(t.getRule("cpp")) << cmd::wdir(t.BinaryDir) << "-E" << cmd::in("src/fcobjshash.gperf.h") ; auto c = cb.getCommand(); auto r = std::make_unique<MyRule>(); r->c = c; fontconfig.addRule("fcobjshash", std::move(r)); #elif SW_CPP_DRIVER_API_VERSION == 1 std::shared_ptr<sw::Program> cc1(fontconfig.findProgramByExtension(".cpp")->clone()); auto cc = std::static_pointer_cast<sw::NativeCompiler>(cc1); cc->IncludeDirectories.push_back(fontconfig.SourceDir); auto c = cc->createCommand(fontconfig.getMainBuild()); c->working_directory = fontconfig.BinaryDir; c->arguments.push_back("-E"); c->arguments.push_back((fontconfig.SourceDir / "src/fcobjshash.gperf.h").u8string()); c->addInput(fontconfig.SourceDir / "src/fcobjshash.gperf.h"); fontconfig.Storage.push_back(c); fontconfig.add(sw::CallbackType::EndPrepare, [cc, &fontconfig]() { cc->merge(fontconfig); cc->getCommand(fontconfig); }); #else #error "too old sw" #endif { auto o3 = fontconfig.BinaryDir / "fcobjshash.gperf"; auto c1 = fontconfig.addCommand(); *c | *c1.getCommand(); c1 << cmd::prog("org.sw.demo.gnu.sed.sed"_dep) << "s/^ *//;s/ *, */,/" | fontconfig.addCommand() << cmd::prog("org.sw.demo.gnu.gawk.gawk"_dep) << "\\\n\ /CUT_OUT_BEGIN/ { no_write=1; next; }; \\\n\ /CUT_OUT_END/ { no_write=0; next; }; \\\n\ /^$$/||/^#/ { next; }; \\\n\ { if (!no_write) print; next; }; \\\n\ " << cmd::std_out(o3); fontconfig.addCommand() << cmd::prog("org.sw.demo.gnu.gperf"_dep) << cmd::wdir(fontconfig.BinaryDir) << "--pic" << "-m100" << cmd::in(o3) << cmd::std_out("fcobjshash.h") ; } } fontconfig.writeFileOnce("fcaliastail.h"); fontconfig.writeFileOnce("fcftaliastail.h"); fontconfig.writeFileOnce("fcstdint.h", "#include <stdint.h>"); fontconfig.replaceInFileOnce("fontconfig/fontconfig.h", "#define FcPublic", "#define FcPublic extern SW_FONTCONFIG_LIBRARY_API"); if (fontconfig.getBuildSettings().TargetOS.Type == OSType::Windows) { fontconfig.Public += "org.sw.demo.tronkko.dirent-master"_dep; fontconfig.replaceInFileOnce("src/fccache.c", "#include <sys/time.h>", "//#include <sys/time.h>"); fontconfig.replaceInFileOnce("src/fcfreetype.c", "advances[3] = {};", "advances[3] = {0};"); fontconfig.writeFileOnce("unistd.h", R"( #pragma once #include <stdlib.h> #include <io.h> #include <process.h> #include <direct.h> #define srandom srand #define random rand #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ typedef int mode_t; #include <stdint.h> #ifdef _WIN64 #define ssize_t int64_t #else #define ssize_t int32_t #endif )"); } else { fontconfig.writeFileOnce("fcalias.h"); fontconfig.writeFileOnce("fcftalias.h"); } } void check(Checker &c) { auto &s = c.addSet("fontconfig"); s.checkFunctionExists("fstatfs"); s.checkFunctionExists("fstatvfs"); s.checkFunctionExists("getexecname"); s.checkFunctionExists("getopt"); s.checkFunctionExists("getopt_long"); s.checkFunctionExists("getprogname"); s.checkFunctionExists("link"); s.checkFunctionExists("lrand48"); s.checkFunctionExists("lstat"); s.checkFunctionExists("mkdtemp"); s.checkFunctionExists("mkostemp"); s.checkFunctionExists("mkstemp"); s.checkFunctionExists("mmap"); s.checkFunctionExists("rand"); s.checkFunctionExists("random"); s.checkFunctionExists("random_r"); s.checkFunctionExists("rand_r"); s.checkFunctionExists("readlink"); s.checkFunctionExists("vprintf"); s.checkFunctionExists("_mktemp_s"); s.checkIncludeExists("dirent.h"); s.checkIncludeExists("fcntl.h"); s.checkIncludeExists("inttypes.h"); s.checkIncludeExists("memory.h"); s.checkIncludeExists("sched.h"); s.checkIncludeExists("stddef.h"); s.checkIncludeExists("stdint.h"); s.checkIncludeExists("stdlib.h"); s.checkIncludeExists("strings.h"); s.checkIncludeExists("string.h"); s.checkIncludeExists("sys/mount.h"); s.checkIncludeExists("sys/param.h"); s.checkIncludeExists("sys/statfs.h"); s.checkIncludeExists("sys/statvfs.h"); s.checkIncludeExists("sys/stat.h"); s.checkIncludeExists("sys/types.h"); s.checkIncludeExists("sys/vfs.h"); s.checkIncludeExists("unistd.h"); s.checkTypeSize("pid_t"); s.checkTypeSize("size_t"); s.checkTypeSize("void *"); s.checkTypeAlignment("double"); s.checkTypeAlignment("void *"); { auto &c = s.checkSymbolExists("posix_fadvise"); c.Parameters.Includes.push_back("fcntl.h"); } { auto &c = s.checkStructMemberExists("FT_Bitmap_Size", "y_ppem"); } { auto &c = s.checkStructMemberExists("struct dirent", "d_type"); c.Parameters.Includes.push_back("dirent.h"); } { auto &c = s.checkStructMemberExists("struct statfs", "f_flags"); c.Parameters.Includes.push_back("sys/stat.h"); } { auto &c = s.checkStructMemberExists("struct statfs", "f_fstypename"); c.Parameters.Includes.push_back("sys/stat.h"); } { auto &c = s.checkStructMemberExists("struct statvfs", "f_basetype"); c.Parameters.Includes.push_back("sys/stat.h"); } { auto &c = s.checkStructMemberExists("struct statvfs", "f_fstypename"); c.Parameters.Includes.push_back("sys/stat.h"); } { auto &c = s.checkStructMemberExists("struct stat", "st_mtim"); c.Parameters.Includes.push_back("sys/stat.h"); } { auto &c = s.checkStructMemberExists("TT_OS2", "usLowerOpticalPointSize"); } { auto &c = s.checkStructMemberExists("TT_OS2", "usUpperOpticalPointSize"); } s.checkSourceCompiles("STDC_HEADERS", R"sw_xxx( #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <float.h> int main() {return 0;} )sw_xxx"); s.checkDeclarationExists("__SUNPRO_C"); }
[ "cppanbot@gmail.com" ]
cppanbot@gmail.com
e4033b1547fc016d27ec1b348c630917b11094e3
d8cabb3e0df24ac70ed78a7828291532c25fec55
/UVA_1/r_10246 - Asterix and Obelix.cc
08bbcbaaa7d7340d785bf2c5e7f0d11668311af3
[]
no_license
Bekon0700/Competitive_Programming
207bb28418d49a2223efb917c7ddf07dfdf4f284
ff93fdb2ada1bafabca13431bec7a78a9754e1b8
refs/heads/master
2022-10-16T09:38:13.865274
2020-06-08T13:12:34
2020-06-08T13:12:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,354
cc
#include <stdio.h> #define INF 3000000000 long long mat[90][90],par[90][90],fc[90],fmat[90][90]; void ini(long long n) { long long i,j; for(i=1;i<n;i++) for(j=1;j<n;j++) { mat[i][j] = INF; fmat[i][j]=par[i][j] = 0 ; } for(i=1;i<n;i++) { mat[i][i] = 0 ; } } void f(long long n) { long long i,j,k; for(i=1;i<n;i++) for(j=1;j<n;j++) if(mat[i][j] < INF) { if(fc[i] > fc[j]) fmat[i][j] = fc[i]; else fmat[i][j] = fc[j]; } } void floyed(long long n) { long long i,j,k,max; for(k=1;k<n;k++) for(i=1;i<n;i++) for(j=1;j<n;j++) { if(fmat[i][k] > fmat[k][j]) max = fmat[i][k]; else max = fmat[k][j]; if( mat[i][j] + fmat[i][j] > mat[i][k] + mat[k][j] + max ) { mat[i][j] = mat[i][k] + mat[k][j] ; fmat[i][j] = max; } } } int main() { long long n,m,q,i,j,k,u,v,x,N,s,cas=1,t=0; while(scanf("%lld%lld%lld",&n,&m,&q)==3 && (n||m||q)) { if(t) printf("\n"); t ++ ; N=n+1; ini(N); for(i=1;i<N;i++) scanf("%lld",&fc[i]); for(i=0;i<m;i++) { scanf("%lld%lld%lld",&u,&v,&s); mat[v][u] = mat[u][v] = s; } f(N); floyed(N); floyed(N); printf("Case #%lld\n",cas++); for(i=0;i<q;i++) { scanf("%lld%lld",&u,&v); x = fmat[u][v]+mat[u][v]; if(x<INF) printf("%lld\n",x); else printf("-1\n"); } } }
[ "naimelias56@gmail.com" ]
naimelias56@gmail.com
8bbe0a09f48485359e9932ff59db1498bba0b1f8
eac80d08b49de1245beca1630a6d0d0a995f2258
/uiposthread.h
98e14a493f16ec4faab08b756f009277f5714dbc
[]
no_license
secondtonone1/qtwebsocket
5a1e00ca84941279fcdc3806461d2eb535772a4d
dda591a4fa5028f83aaf51c4b53a5a476f185477
refs/heads/main
2023-01-29T19:23:33.176235
2020-12-15T12:53:40
2020-12-15T12:53:40
321,666,650
0
0
null
null
null
null
UTF-8
C++
false
false
757
h
#ifndef UI_POST_THREAD_H #define UI_POST_THREAD_H #include <QThread> #include <QtWidgets/QMainWindow> #include "postdata.h" #include <string> #include <iostream> #include <postqueue.h> using namespace std; //ui 投递消息给发送队列 class UIPostThread:public QThread{ Q_OBJECT public: UIPostThread(vector<PostData> vecPost){ m_vecPostData = vecPost; } void run() override{ for(auto it = m_vecPostData.begin(); it != m_vecPostData.end(); it ++){ cout << "key is: " << it->GetKey() << " cmd is: " << it->GetCmd() << endl; auto p1 = PostQueue<PostData>::getInstance(); p1->push(PostData(*it)); } } private: std::vector<PostData> m_vecPostData; }; #endif
[ "secondtonone1@163.com" ]
secondtonone1@163.com
9016ce3208e852165e87f3ff703b76cfda1b174b
19cad9cc067f117a096af8dbf233f6fff3115e4b
/oxygine/src/Input.cpp
6a36f094394c5075273c9d2dda116de32c83cef3
[ "MIT" ]
permissive
mattpbooth/oxygine-framework
b28339b77dd26c69029ee80b18ccd0b1895b0ab4
14a3026a67a0b8df0a3c094566aae89bf66c3ffd
refs/heads/master
2020-04-01T13:52:14.227020
2014-11-25T21:35:21
2014-11-25T21:35:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,509
cpp
#include "Input.h" #include "Stage.h" #include "core/log.h" #include <string.h> //#define LOGD(...) oxygine::log::message("input: "); oxygine::log::messageln(__VA_ARGS__) #define LOGD(...) ((void)0) namespace oxygine { Input Input::instance; const PointerState *TouchEvent::getPointer() const { return Input::instance.getTouchByIndex(index); } void Input::sendPointerButtonEvent(MouseButton button, float x, float y, float pressure, int type, PointerState *ps) { Vector2 p(x, y); TouchEvent me(type, true, p); me.index = ps->getIndex(); me.mouseButton = button; me.pressure = pressure; if (type == TouchEvent::TOUCH_DOWN) ps->_isPressed[button] = true; else if (type == TouchEvent::TOUCH_UP) ps->_isPressed[button] = false; ps->_position = p; LOGD("sendPointerButtonEvent %d - (%.2f, %.2f), %d", me.index, p.x, p.y, type); getStage()->handleEvent(&me); if (type == TouchEvent::TOUCH_UP) { _ids[ps->getIndex() - 1] = 0; } } void Input::sendPointerMotionEvent(float x, float y, float pressure, PointerState *ps) { TouchEvent me(TouchEvent::MOVE, true, Vector2(x, y)); me.index = ps->getIndex(); me.pressure = pressure; ps->_position = Vector2(x, y); LOGD("sendPointerMotionEvent %d - (%.2f, %.2f)", me.index, x, y); getStage()->handleEvent(&me); } void Input::sendPointerWheelEvent(int scroll, PointerState *ps) { TouchEvent me(scroll > 0 ? TouchEvent::WHEEL_UP : TouchEvent::WHEEL_DOWN, true); me.index = ps->getIndex(); ps->_position = Vector2(0, 0); getStage()->handleEvent(&me); } Input::Input() { addRef(); _pointerMouse.init(MAX_TOUCHES + 1); for (int i = 0; i < MAX_TOUCHES; ++i) _pointers[i].init(i + 1); memset(_ids, 0, sizeof(_ids)); } Input::~Input() { } void Input::cleanup() { } PointerState *Input::getTouchByIndex(int index) { if (index == MAX_TOUCHES + 1) return &_pointerMouse; index -= 1; OX_ASSERT(index >= 0 && index < MAX_TOUCHES); index = min(max(index, 0), MAX_TOUCHES); return &_pointers[index]; } #ifndef __S3E__ int Input::touchID2index(int id) { id += 1;//id could be = 0 ? for (int i = 0; i < MAX_TOUCHES; ++i) { int &d = _ids[i]; int index = i + 1; if (d == 0) { d = id; return index; } if (d == id) return index; } OX_ASSERT("can't find touch id"); return 0; } PointerState *Input::getTouchByID(int id) { return getTouchByIndex(touchID2index(id)); } #endif }
[ "frankinshtein85@gmail.com" ]
frankinshtein85@gmail.com
e8277430563c2c78a6c316abc5fb127d1ca1e2bb
ffb81d9b96927622af3f8f5ea79543ea96883b68
/parallel_execution_mpi.h
36f69c88921d17fc339ea295175e46b88f657d38
[]
no_license
laurapl/MPI_parallization
704494d579ff5118e16bb7fc9aefa1504f48d5e9
b3b17548c1d3fc5cadd514449d4fee3a2c224f31
refs/heads/master
2020-03-24T17:26:01.378993
2018-07-30T10:19:36
2018-07-30T10:19:36
142,859,105
0
1
null
null
null
null
UTF-8
C++
false
false
52,072
h
/* * Copyright 2018 Universidad Carlos III de Madrid * * 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. */ #ifndef GRPPI_NATIVE_PARALLEL_EXECUTION_NATIVE_H #define GRPPI_NATIVE_PARALLEL_EXECUTION_NATIVE_H #include "worker_pool.h" #include "../common/mpmc_queue.h" #include "../common/iterator.h" #include "../common/execution_traits.h" #include "../common/configuration.h" #include <thread> #include <atomic> #include <algorithm> #include <vector> #include <type_traits> #include <tuple> #include <experimental/optional> #include <sstream> #include <cstdlib> #include <cstring> namespace grppi { /** \brief Thread index table to provide portable natural thread indices. A thread table provides a simple way to offer thread indices (starting from 0). When a thread registers itself in the registry, its id is added to the vector of identifiers. When a thread deregisters itself from the registry its entry is modified to contain the empty thread id. To get an integer index, users may call `current_index`, which provides the order number of the calling thread in the registry. \note This class is thread safe by means of using a spin-lock. */ class thread_registry { public: thread_registry() = default; /** \brief Adds the current thread id in the registry. */ void register_thread() noexcept; /** \brief Removes current thread id from the registry. */ void deregister_thread() noexcept; /** \brief Integer index for current thread \return Integer value with the registration order of current thread. \pre Current thread is registered. */ int current_index() const noexcept; private: mutable std::atomic_flag lock_ = ATOMIC_FLAG_INIT; std::vector<std::thread::id> ids_{}; }; inline void thread_registry::register_thread() noexcept { using namespace std; while (lock_.test_and_set(memory_order_acquire)) {} auto this_id = this_thread::get_id(); ids_.push_back(this_id); lock_.clear(memory_order_release); } inline void thread_registry::deregister_thread() noexcept { using namespace std; while (lock_.test_and_set(memory_order_acquire)) {} auto this_id = this_thread::get_id(); auto current = find(begin(ids_), end(ids_), this_id); *current = {}; //Empty thread lock_.clear(memory_order_release); } inline int thread_registry::current_index() const noexcept { using namespace std; while (lock_.test_and_set(memory_order_acquire)) {} auto this_id = this_thread::get_id(); auto current = find(begin(ids_), end(ids_), this_id); auto index = distance(begin(ids_), current); lock_.clear(memory_order_release); return index; } /** \brief RAII class to manage registration/deregistration pairs. This class allows to manage automatic deregistration of threads through the common RAII pattern. The current thread is registered into the registry at construction and deregistered a destruction. */ class native_thread_manager { public: /** \brief Saves a reference to the registry and registers current thread */ native_thread_manager(thread_registry & registry) : registry_{registry} { registry_.register_thread(); } /** \brief Deregisters current thread from the registry. */ ~native_thread_manager() { registry_.deregister_thread(); } private: thread_registry & registry_; }; /** \brief Native parallel execution policy. This policy uses ISO C++ threads as implementation building block allowing usage in any ISO C++ compliant platform. */ class parallel_execution_native { public: /** \brief Default construct a native parallel execution policy. Creates a parallel execution native object. The concurrency degree is determined by the platform. \note The concurrency degree is fixed to 2 times the hardware concurrency degree. */ parallel_execution_native() noexcept {} parallel_execution_native(int concurrency_degree) noexcept : concurrency_degree_{concurrency_degree} {} /** \brief Constructs a native parallel execution policy. Creates a parallel execution native object selecting the concurrency degree and ordering mode. \param concurrency_degree Number of threads used for parallel algorithms. \param order Whether ordered executions is enabled or disabled. */ parallel_execution_native(int concurrency_degree, bool ordering) noexcept : concurrency_degree_{concurrency_degree}, ordering_{ordering} {} parallel_execution_native(const parallel_execution_native & ex) : parallel_execution_native{ex.concurrency_degree_, ex.ordering_} {} /** \brief Set number of grppi threads. */ void set_concurrency_degree(int degree) noexcept { concurrency_degree_ = degree; } /** \brief Get number of grppi threads. */ int concurrency_degree() const noexcept { return concurrency_degree_; } /** \brief Enable ordering. */ void enable_ordering() noexcept { ordering_=true; } /** \brief Disable ordering. */ void disable_ordering() noexcept { ordering_=false; } /** \brief Is execution ordered. */ bool is_ordered() const noexcept { return ordering_; } /** \brief Get a manager object for registration/deregistration in the thread index table for current thread. */ native_thread_manager thread_manager() const { return native_thread_manager{thread_registry_}; } /** \brief Get index of current thread in the thread table \pre The current thread is currently registered. */ [[deprecated("Thread ids are deprecated.\n" "If you have a specific use case file a bug")]] int get_thread_id() const noexcept { return thread_registry_.current_index(); } /** \brief Sets the attributes for the queues built through make_queue<T>() */ void set_queue_attributes(int size, queue_mode mode) noexcept { queue_size_ = size; queue_mode_ = mode; } /** \brief Makes a communication queue for elements of type T. Constructs a queue using the attributes that can be set via set_queue_attributes(). The value is returned via move semantics. \tparam T Element type for the queue. */ template <typename T> mpmc_queue<T> make_queue() const { return {queue_size_, queue_mode_}; } /** \brief Returns the reference of a communication queue for elements of type T if the queue has been created in an outer pattern. Returns the reference of the queue received as argument. \tparam T Element type for the queue. \tparam Transformers List of the next transformers. \param queue Reference of a queue of type T */ template <typename T, typename ... Transformers> mpmc_queue<T>& get_output_queue(mpmc_queue<T> & queue, Transformers && ...) const { return queue; } /** \brief Makes a communication queue for elements of type T if the queue has not been created in an outer pattern. Call to the make_queue function and the value is returned via move semantics. \tparam T Element type for the queue. \tparam Transformers List of the next transformers. */ template <typename T, typename ... Transformers> mpmc_queue<T> get_output_queue(Transformers && ...) const{ return std::move(make_queue<T>()); } /** \brief Applies a transformation to multiple sequences leaving the result in another sequence by chunks according to concurrency degree. \tparam InputIterators Iterator types for input sequences. \tparam OutputIterator Iterator type for the output sequence. \tparam Transformer Callable object type for the transformation. \param firsts Tuple of iterators to input sequences. \param first_out Iterator to the output sequence. \param sequence_size Size of the input sequences. \param transform_op Transformation callable object. \pre For every I iterators in the range `[get<I>(firsts), next(get<I>(firsts),sequence_size))` are valid. \pre Iterators in the range `[first_out, next(first_out,sequence_size)]` are valid. */ template <typename ... InputIterators, typename OutputIterator, typename Transformer> void map(std::tuple<InputIterators...> firsts, OutputIterator first_out, std::size_t sequence_size, Transformer transform_op) const; /** \brief Applies a reduction to a sequence of data items. \tparam InputIterator Iterator type for the input sequence. \tparam Identity Type for the identity value. \tparam Combiner Callable object type for the combination. \param first Iterator to the first element of the sequence. \param sequence_size Size of the input sequence. \param identity Identity value for the reduction. \param combine_op Combination callable object. \pre Iterators in the range `[first,last)` are valid. \return The reduction result */ template <typename InputIterator, typename Identity, typename Combiner> auto reduce(InputIterator first, std::size_t sequence_size, Identity && identity, Combiner && combine_op) const; /** \brief Applies a map/reduce operation to a sequence of data items. \tparam InputIterator Iterator type for the input sequence. \tparam Identity Type for the identity value. \tparam Transformer Callable object type for the transformation. \tparam Combiner Callable object type for the combination. \param first Iterator to the first element of the sequence. \param sequence_size Size of the input sequence. \param identity Identity value for the reduction. \param transform_op Transformation callable object. \param combine_op Combination callable object. \pre Iterators in the range `[first,last)` are valid. \return The map/reduce result. */ template <typename ... InputIterators, typename Identity, typename Transformer, typename Combiner> auto map_reduce(std::tuple<InputIterators...> firsts, std::size_t sequence_size, Identity && identity, Transformer && transform_op, Combiner && combine_op) const; /** \brief Applies a stencil to multiple sequences leaving the result in another sequence. \tparam InputIterators Iterator types for input sequences. \tparam OutputIterator Iterator type for the output sequence. \tparam StencilTransformer Callable object type for the stencil transformation. \tparam Neighbourhood Callable object for generating neighbourhoods. \param firsts Tuple of iterators to input sequences. \param first_out Iterator to the output sequence. \param sequence_size Size of the input sequences. \param transform_op Stencil transformation callable object. \param neighbour_op Neighbourhood callable object. \pre For every I iterators in the range `[get<I>(firsts), next(get<I>(firsts),sequence_size))` are valid. \pre Iterators in the range `[first_out, next(first_out,sequence_size)]` are valid. */ template <typename ... InputIterators, typename OutputIterator, typename StencilTransformer, typename Neighbourhood> void stencil(std::tuple<InputIterators...> firsts, OutputIterator first_out, std::size_t sequence_size, StencilTransformer && transform_op, Neighbourhood && neighbour_op) const; /** \brief Invoke \ref md_divide-conquer. \tparam Input Type used for the input problem. \tparam Divider Callable type for the divider operation. \tparam Solver Callable type for the solver operation. \tparam Combiner Callable type for the combiner operation. \param ex Sequential execution policy object. \param input Input problem to be solved. \param divider_op Divider operation. \param solver_op Solver operation. \param combine_op Combiner operation. */ template <typename Input, typename Divider, typename Solver, typename Combiner> [[deprecated("Use new interface with predicate argument")]] auto divide_conquer(Input && input, Divider && divide_op, Solver && solve_op, Combiner && combine_op) const; /** \brief Invoke \ref md_divide-conquer. \tparam Input Type used for the input problem. \tparam Divider Callable type for the divider operation. \tparam Predicate Callable type for the stop condition predicate. \tparam Solver Callable type for the solver operation. \tparam Combiner Callable type for the combiner operation. \param ex Sequential execution policy object. \param input Input problem to be solved. \param divider_op Divider operation. \param predicate_op Predicate operation. \param solver_op Solver operation. \param combine_op Combiner operation. */ template <typename Input, typename Divider, typename Predicate, typename Solver, typename Combiner> auto divide_conquer(Input && input, Divider && divide_op, Predicate && predicate_op, Solver && solve_op, Combiner && combine_op) const; /** \brief Invoke \ref md_pipeline. \tparam Generator Callable type for the generator operation. \tparam Transformers Callable types for the transformers in the pipeline. \param generate_op Generator operation. \param transform_ops Transformer operations. */ template <typename Generator, typename ... Transformers> void pipeline(Generator && generate_op, Transformers && ... transform_ops) const; /** \brief Invoke \ref md_pipeline coming from another context that uses mpmc_queues as communication channels. \tparam InputType Type of the input stream. \tparam Transformers Callable types for the transformers in the pipeline. \tparam InputType Type of the output stream. \param input_queue Input stream communicator. \param transform_ops Transformer operations. \param output_queue Input stream communicator. */ template <typename InputType, typename Transformer, typename OutputType> void pipeline(mpmc_queue<InputType> & input_queue, Transformer && transform_op, mpmc_queue<OutputType> &output_queue) const { do_pipeline(input_queue, std::forward<Transformer>(transform_op), output_queue); } private: template <typename Input, typename Divider, typename Solver, typename Combiner> auto divide_conquer(Input && input, Divider && divide_op, Solver && solve_op, Combiner && combine_op, std::atomic<int> & num_threads) const; template <typename Input, typename Divider,typename Predicate, typename Solver, typename Combiner> auto divide_conquer(Input && input, Divider && divide_op, Predicate && predicate_op, Solver && solve_op, Combiner && combine_op, std::atomic<int> & num_threads) const; template <typename Queue, typename Consumer, requires_no_pattern<Consumer> = 0> void do_pipeline(Queue & input_queue, Consumer && consume_op) const; template <typename Inqueue, typename Transformer, typename output_type, requires_no_pattern<Transformer> = 0> void do_pipeline(Inqueue & input_queue, Transformer && transform_op, mpmc_queue<output_type> & output_queue) const; template <typename T, typename ... Others> void do_pipeline(mpmc_queue<T> & in_q, mpmc_queue<T> & same_queue, Others &&... ops) const; template <typename T> void do_pipeline(mpmc_queue<T> &) const {} template <typename Queue, typename Transformer, typename ... OtherTransformers, requires_no_pattern<Transformer> = 0> void do_pipeline(Queue & input_queue, Transformer && transform_op, OtherTransformers && ... other_ops) const; template <typename Queue, typename FarmTransformer, template <typename> class Farm, requires_farm<Farm<FarmTransformer>> = 0> void do_pipeline(Queue & input_queue, Farm<FarmTransformer> & farm_obj) const { do_pipeline(input_queue, std::move(farm_obj)); } template <typename Queue, typename FarmTransformer, template <typename> class Farm, requires_farm<Farm<FarmTransformer>> = 0> void do_pipeline( Queue & input_queue, Farm<FarmTransformer> && farm_obj) const; template <typename Queue, typename Execution, typename Transformer, template <typename, typename> class Context, typename ... OtherTransformers, requires_context<Context<Execution,Transformer>> = 0> void do_pipeline(Queue & input_queue, Context<Execution,Transformer> && context_op, OtherTransformers &&... other_ops) const; template <typename Queue, typename Execution, typename Transformer, template <typename, typename> class Context, typename ... OtherTransformers, requires_context<Context<Execution,Transformer>> = 0> void do_pipeline(Queue & input_queue, Context<Execution,Transformer> & context_op, OtherTransformers &&... other_ops) const { do_pipeline(input_queue, std::move(context_op), std::forward<OtherTransformers>(other_ops)...); } template <typename Queue, typename FarmTransformer, template <typename> class Farm, typename ... OtherTransformers, requires_farm<Farm<FarmTransformer>> = 0> void do_pipeline(Queue & input_queue, Farm<FarmTransformer> & farm_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline(input_queue, std::move(farm_obj), std::forward<OtherTransformers>(other_transform_ops)...); } template <typename Queue, typename FarmTransformer, template <typename> class Farm, typename ... OtherTransformers, requires_farm<Farm<FarmTransformer>> = 0> void do_pipeline(Queue & input_queue, Farm<FarmTransformer> && farm_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename Predicate, template <typename> class Filter, typename ... OtherTransformers, requires_filter<Filter<Predicate>> =0> void do_pipeline(Queue & input_queue, Filter<Predicate> & filter_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline(input_queue, std::move(filter_obj), std::forward<OtherTransformers>(other_transform_ops)...); } template <typename Queue, typename Predicate, template <typename> class Filter, typename ... OtherTransformers, requires_filter<Filter<Predicate>> =0> void do_pipeline(Queue & input_queue, Filter<Predicate> && farm_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename Combiner, typename Identity, template <typename C, typename I> class Reduce, typename ... OtherTransformers, requires_reduce<Reduce<Combiner,Identity>> = 0> void do_pipeline(Queue && input_queue, Reduce<Combiner,Identity> & reduce_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline(input_queue, std::move(reduce_obj), std::forward<OtherTransformers>(other_transform_ops)...); } template <typename Queue, typename Combiner, typename Identity, template <typename C, typename I> class Reduce, typename ... OtherTransformers, requires_reduce<Reduce<Combiner,Identity>> = 0> void do_pipeline(Queue && input_queue, Reduce<Combiner,Identity> && reduce_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename Transformer, typename Predicate, template <typename T, typename P> class Iteration, typename ... OtherTransformers, requires_iteration<Iteration<Transformer,Predicate>> =0, requires_no_pattern<Transformer> =0> void do_pipeline(Queue & input_queue, Iteration<Transformer,Predicate> & iteration_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline(input_queue, std::move(iteration_obj), std::forward<OtherTransformers>(other_transform_ops)...); } template <typename Queue, typename Transformer, typename Predicate, template <typename T, typename P> class Iteration, typename ... OtherTransformers, requires_iteration<Iteration<Transformer,Predicate>> =0, requires_no_pattern<Transformer> =0> void do_pipeline(Queue & input_queue, Iteration<Transformer,Predicate> && iteration_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename Transformer, typename Predicate, template <typename T, typename P> class Iteration, typename ... OtherTransformers, requires_iteration<Iteration<Transformer,Predicate>> =0, requires_pipeline<Transformer> =0> void do_pipeline(Queue & input_queue, Iteration<Transformer,Predicate> && iteration_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, requires_pipeline<Pipeline<Transformers...>> = 0> void do_pipeline(Queue & input_queue, Pipeline<Transformers...> & pipeline_obj) const { do_pipeline(input_queue, std::move(pipeline_obj)); } template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, requires_pipeline<Pipeline<Transformers...>> = 0> void do_pipeline(Queue & input_queue, Pipeline<Transformers...> && pipeline_obj) const; template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, typename ... OtherTransformers, requires_pipeline<Pipeline<Transformers...>> = 0> void do_pipeline(Queue & input_queue, Pipeline<Transformers...> & pipeline_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline(input_queue, std::move(pipeline_obj), std::forward<OtherTransformers>(other_transform_ops)...); } template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, typename ... OtherTransformers, requires_pipeline<Pipeline<Transformers...>> = 0> void do_pipeline(Queue & input_queue, Pipeline<Transformers...> && pipeline_obj, OtherTransformers && ... other_transform_ops) const; template <typename Queue, typename ... Transformers, std::size_t ... I> void do_pipeline_nested( Queue & input_queue, std::tuple<Transformers...> && transform_ops, std::index_sequence<I...>) const; private: mutable thread_registry thread_registry_{}; configuration<> config_{}; int concurrency_degree_ = config_.concurrency_degree(); bool ordering_ = config_.ordering(); int queue_size_ = config_.queue_size(); queue_mode queue_mode_ = config_.mode(); }; /** \brief Metafunction that determines if type E is parallel_execution_native \tparam Execution policy type. */ template <typename E> constexpr bool is_parallel_execution_native() { return std::is_same<E, parallel_execution_native>::value; } /** \brief Determines if an execution policy is supported in the current compilation. \note Specialization for parallel_execution_native. */ template <> constexpr bool is_supported<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the map pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_map<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the reduce pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_reduce<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the map-reduce pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_map_reduce<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the stencil pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_stencil<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the divide/conquer pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_divide_conquer<parallel_execution_native>() { return true; } /** \brief Determines if an execution policy supports the pipeline pattern. \note Specialization for parallel_execution_native. */ template <> constexpr bool supports_pipeline<parallel_execution_native>() { return true; } template <typename ... InputIterators, typename OutputIterator, typename Transformer> void parallel_execution_native::map( std::tuple<InputIterators...> firsts, OutputIterator first_out, std::size_t sequence_size, Transformer transform_op) const { using namespace std; //Donde esta transform_op y fileinput //Apañar esto para argc y argv MPI_Init(&sequence_size); MPI_File fh, fhout; MPI_File_open(MPI_COMM_WORLD, 'Fileinput', MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); //Different chunck size must be specified per process. const int chunk_size = sequence_size / concurrency_degree_; //Take into account overhead in chunck distribution. Last processes could end up reading too much. int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_File_seek(fh, rank*chunk_size, MPI_SEEK_SET); auto aux; if (rank == 0) { //What should we do if the output file already exists? Where should be the file created? MPI_File_open(MPI_COMM_WORLD, 'Fileoutput', MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &fhout); } else { MPI_File_open(MPI_COMM_WORLD, 'Fileoutput', MPI_MODE_WRONLY, MPI_INFO_NULL, &fhout); } MPI_File_set_size(fhout, sequence_size*sizeof(auto)); MPI_File_seek(fhout, rank*chunk_size, MPI_SEEK_SET); for (int i = 0; i < chunk_size; i++) { //Input data type? MPI_File_read(fh, aux, 1, MPI_INT, MPI_STATUS_IGNORE); //Apply transform op aux = apply_deref_increment( std::forward<Transformer>('transform_op'), aux); //Write in the final buffer. MPI_File_write(fhout, aux, 1, MPI_Datatype datatype, MPI_STATUS_IGNORE); } MPI_File_close(&fh); MPI_File_close(&fhout); MPI_Finalize(); /*auto process_chunk = [&transform_op](auto fins, std::size_t size, auto fout) { const auto l = next(get<0>(fins), chunck_size); while (get<0>(fins)!=l) { *fout++ = apply_deref_increment( std::forward<Transformer>(transform_op), fins); } //}; /*{ worker_pool workers{concurrency_degree_}; for (int i=0; i!=concurrency_degree_-1; ++i) { const auto delta = chunk_size * i; const auto chunk_firsts = iterators_next(firsts,delta); const auto chunk_first_out = next(first_out, delta); workers.launch(*this, process_chunk, chunk_firsts, chunk_size, chunk_first_out); } const auto delta = chunk_size * (concurrency_degree_ - 1); const auto chunk_firsts = iterators_next(firsts,delta); const auto chunk_first_out = next(first_out, delta); process_chunk(chunk_firsts, sequence_size - delta, chunk_first_out); } // Pool synch*/ } template <typename InputIterator, typename Identity, typename Combiner> auto parallel_execution_native::reduce( InputIterator first, std::size_t sequence_size, Identity && identity, Combiner && combine_op) const { using result_type = std::decay_t<Identity>; std::vector<result_type> partial_results(concurrency_degree_); constexpr sequential_execution seq; auto process_chunk = [&](InputIterator f, std::size_t sz, std::size_t id) { partial_results[id] = seq.reduce(f,sz, std::forward<Identity>(identity), std::forward<Combiner>(combine_op)); }; const auto chunk_size = sequence_size / concurrency_degree_; { worker_pool workers{concurrency_degree_}; for (int i=0; i<concurrency_degree_-1; ++i) { const auto delta = chunk_size * i; const auto chunk_first = std::next(first,delta); workers.launch(*this, process_chunk, chunk_first, chunk_size, i); } const auto delta = chunk_size * (concurrency_degree_-1); const auto chunk_first = std::next(first, delta); const auto chunk_sz = sequence_size - delta; process_chunk(chunk_first, chunk_sz, concurrency_degree_-1); } // Pool synch return seq.reduce(std::next(partial_results.begin()), partial_results.size()-1, std::forward<result_type>(partial_results[0]), std::forward<Combiner>(combine_op)); } template <typename ... InputIterators, typename Identity, typename Transformer, typename Combiner> auto parallel_execution_native::map_reduce( std::tuple<InputIterators...> firsts, std::size_t sequence_size, Identity && identity, Transformer && transform_op, Combiner && combine_op) const { using result_type = std::decay_t<Identity>; std::vector<result_type> partial_results(concurrency_degree_); constexpr sequential_execution seq; auto process_chunk = [&](auto f, std::size_t sz, std::size_t id) { partial_results[id] = seq.map_reduce(f, sz, std::forward<Identity>(identity), std::forward<Transformer>(transform_op), std::forward<Combiner>(combine_op)); }; const auto chunk_size = sequence_size / concurrency_degree_; { worker_pool workers{concurrency_degree_}; for(int i=0;i<concurrency_degree_-1;++i){ const auto delta = chunk_size * i; const auto chunk_firsts = iterators_next(firsts,delta); workers.launch(*this, process_chunk, chunk_firsts, chunk_size, i); } const auto delta = chunk_size * (concurrency_degree_-1); const auto chunk_firsts = iterators_next(firsts, delta); process_chunk(chunk_firsts, sequence_size - delta, concurrency_degree_-1); } // Pool synch return seq.reduce(partial_results.begin(), partial_results.size(), std::forward<Identity>(identity), std::forward<Combiner>(combine_op)); } template <typename ... InputIterators, typename OutputIterator, typename StencilTransformer, typename Neighbourhood> void parallel_execution_native::stencil( std::tuple<InputIterators...> firsts, OutputIterator first_out, std::size_t sequence_size, StencilTransformer && transform_op, Neighbourhood && neighbour_op) const { constexpr sequential_execution seq; auto process_chunk = [&transform_op, &neighbour_op,seq](auto fins, std::size_t sz, auto fout) { seq.stencil(fins, fout, sz, std::forward<StencilTransformer>(transform_op), std::forward<Neighbourhood>(neighbour_op)); }; const auto chunk_size = sequence_size / concurrency_degree_; { worker_pool workers{concurrency_degree_}; for (int i=0; i!=concurrency_degree_-1; ++i) { const auto delta = chunk_size * i; const auto chunk_firsts = iterators_next(firsts,delta); const auto chunk_out = std::next(first_out,delta); workers.launch(*this, process_chunk, chunk_firsts, chunk_size, chunk_out); } const auto delta = chunk_size * (concurrency_degree_ - 1); const auto chunk_firsts = iterators_next(firsts,delta); const auto chunk_out = std::next(first_out,delta); process_chunk(chunk_firsts, sequence_size - delta, chunk_out); } // Pool synch } template <typename Input, typename Divider, typename Solver, typename Combiner> auto parallel_execution_native::divide_conquer( Input && problem, Divider && divide_op, Solver && solve_op, Combiner && combine_op) const { std::atomic<int> num_threads{concurrency_degree_-1}; return divide_conquer(std::forward<Input>(problem), std::forward<Divider>(divide_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); } template <typename Input, typename Divider,typename Predicate, typename Solver, typename Combiner> auto parallel_execution_native::divide_conquer( Input && problem, Divider && divide_op, Predicate && predicate_op, Solver && solve_op, Combiner && combine_op) const { std::atomic<int> num_threads{concurrency_degree_-1}; return divide_conquer(std::forward<Input>(problem), std::forward<Divider>(divide_op), std::forward<Predicate>(predicate_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); } template <typename Generator, typename ... Transformers> void parallel_execution_native::pipeline( Generator && generate_op, Transformers && ... transform_ops) const { using namespace std; using result_type = decay_t<typename result_of<Generator()>::type>; using output_type = pair<result_type,long>; auto output_queue = make_queue<output_type>(); thread generator_task([&,this]() { auto manager = thread_manager(); long order = 0; for (;;) { auto item{generate_op()}; output_queue.push(make_pair(item, order)); order++; if (!item) break; } }); do_pipeline(output_queue, forward<Transformers>(transform_ops)...); generator_task.join(); } // PRIVATE MEMBERS template <typename Input, typename Divider, typename Solver, typename Combiner> auto parallel_execution_native::divide_conquer( Input && input, Divider && divide_op, Solver && solve_op, Combiner && combine_op, std::atomic<int> & num_threads) const { constexpr sequential_execution seq; if (num_threads.load() <=0) { return seq.divide_conquer(std::forward<Input>(input), std::forward<Divider>(divide_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op)); } auto subproblems = divide_op(std::forward<Input>(input)); if (subproblems.size()<=1) { return solve_op(std::forward<Input>(input)); } using subresult_type = std::decay_t<typename std::result_of<Solver(Input)>::type>; std::vector<subresult_type> partials(subproblems.size()-1); auto process_subproblem = [&,this](auto it, std::size_t div) { partials[div] = this->divide_conquer(std::forward<Input>(*it), std::forward<Divider>(divide_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); }; int division = 0; worker_pool workers{num_threads.load()}; auto i = subproblems.begin() + 1; while (i!=subproblems.end() && num_threads.load()>0) { workers.launch(*this,process_subproblem, i++, division++); num_threads--; } while (i!=subproblems.end()) { partials[division] = seq.divide_conquer(std::forward<Input>(*i++), std::forward<Divider>(divide_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op)); } auto subresult = divide_conquer(std::forward<Input>(*subproblems.begin()), std::forward<Divider>(divide_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); workers.wait(); return seq.reduce(partials.begin(), partials.size(), std::forward<subresult_type>(subresult), std::forward<Combiner>(combine_op)); } template <typename Input, typename Divider,typename Predicate, typename Solver, typename Combiner> auto parallel_execution_native::divide_conquer( Input && input, Divider && divide_op, Predicate && predicate_op, Solver && solve_op, Combiner && combine_op, std::atomic<int> & num_threads) const { constexpr sequential_execution seq; if (num_threads.load() <=0) { return seq.divide_conquer(std::forward<Input>(input), std::forward<Divider>(divide_op), std::forward<Predicate>(predicate_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op)); } if (predicate_op(input)) { return solve_op(std::forward<Input>(input)); } auto subproblems = divide_op(std::forward<Input>(input)); using subresult_type = std::decay_t<typename std::result_of<Solver(Input)>::type>; std::vector<subresult_type> partials(subproblems.size()-1); auto process_subproblem = [&,this](auto it, std::size_t div) { partials[div] = this->divide_conquer(std::forward<Input>(*it), std::forward<Divider>(divide_op), std::forward<Predicate>(predicate_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); }; int division = 0; worker_pool workers{num_threads.load()}; auto i = subproblems.begin() + 1; while (i!=subproblems.end() && num_threads.load()>0) { workers.launch(*this,process_subproblem, i++, division++); num_threads--; } while (i!=subproblems.end()) { partials[division] = seq.divide_conquer(std::forward<Input>(*i++), std::forward<Divider>(divide_op), std::forward<Predicate>(predicate_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op)); } auto subresult = divide_conquer(std::forward<Input>(*subproblems.begin()), std::forward<Divider>(divide_op), std::forward<Predicate>(predicate_op), std::forward<Solver>(solve_op), std::forward<Combiner>(combine_op), num_threads); workers.wait(); return seq.reduce(partials.begin(), partials.size(), std::forward<subresult_type>(subresult), std::forward<Combiner>(combine_op)); } template <typename Queue, typename Consumer, requires_no_pattern<Consumer>> void parallel_execution_native::do_pipeline( Queue & input_queue, Consumer && consume_op) const { using namespace std; using input_type = typename Queue::value_type; auto manager = thread_manager(); if (!is_ordered()) { for (;;) { auto item = input_queue.pop(); if (!item.first) break; consume_op(*item.first); } return; } vector<input_type> elements; long current = 0; for (;;) { auto item = input_queue.pop(); if (!item.first) break; if(current == item.second){ consume_op(*item.first); current ++; } else { elements.push_back(item); } auto it = find_if(elements.begin(), elements.end(), [&](auto x) { return x.second== current; }); if(it != elements.end()){ consume_op(*it->first); elements.erase(it); current++; } } while (elements.size()>0) { auto it = find_if(elements.begin(), elements.end(), [&](auto x) { return x.second== current; }); if(it != elements.end()){ consume_op(*it->first); elements.erase(it); current++; } } } template <typename Inqueue, typename Transformer, typename output_type, requires_no_pattern<Transformer>> void parallel_execution_native::do_pipeline(Inqueue & input_queue, Transformer && transform_op, mpmc_queue<output_type> & output_queue) const { using namespace std; using namespace experimental; using output_item_value_type = typename output_type::first_type::value_type; for (;;) { auto item{input_queue.pop()}; if(!item.first) break; auto out = output_item_value_type{transform_op(*item.first)}; output_queue.push(make_pair(out,item.second)) ; } } template <typename Queue, typename Transformer, typename ... OtherTransformers, requires_no_pattern<Transformer>> void parallel_execution_native::do_pipeline( Queue & input_queue, Transformer && transform_op, OtherTransformers && ... other_transform_ops) const { using namespace std; using namespace experimental; using input_item_type = typename Queue::value_type; using input_item_value_type = typename input_item_type::first_type::value_type; using transform_result_type = decay_t<typename result_of<Transformer(input_item_value_type)>::type>; using output_item_value_type = optional<transform_result_type>; using output_item_type = pair<output_item_value_type,long>; decltype(auto) output_queue = get_output_queue<output_item_type>(other_transform_ops...); thread task([&,this]() { auto manager = thread_manager(); for (;;) { auto item{input_queue.pop()}; if (!item.first) break; auto out = output_item_value_type{transform_op(*item.first)}; output_queue.push(make_pair(out, item.second)); } output_queue.push(make_pair(output_item_value_type{},-1)); }); do_pipeline(output_queue, forward<OtherTransformers>(other_transform_ops)...); task.join(); } template <typename Queue, typename FarmTransformer, template <typename> class Farm, requires_farm<Farm<FarmTransformer>>> void parallel_execution_native::do_pipeline( Queue & input_queue, Farm<FarmTransformer> && farm_obj) const { using namespace std; auto farm_task = [&](int) { auto item{input_queue.pop()}; while (item.first) { farm_obj(*item.first); item = input_queue.pop(); } input_queue.push(item); }; auto ntasks = farm_obj.cardinality(); worker_pool workers{ntasks}; workers.launch_tasks(*this, farm_task, ntasks); workers.wait(); } template <typename Queue, typename Execution, typename Transformer, template <typename, typename> class Context, typename ... OtherTransformers, requires_context<Context<Execution,Transformer>>> void parallel_execution_native::do_pipeline(Queue & input_queue, Context<Execution,Transformer> && context_op, OtherTransformers &&... other_ops) const { using namespace std; using namespace experimental; using input_item_type = typename Queue::value_type; using input_item_value_type = typename input_item_type::first_type::value_type; using output_type = typename stage_return_type<input_item_value_type, Transformer>::type; using output_optional_type = experimental::optional<output_type>; using output_item_type = pair <output_optional_type, long> ; decltype(auto) output_queue = get_output_queue<output_item_type>(other_ops...); auto context_task = [&]() { context_op.execution_policy().pipeline(input_queue, context_op.transformer(), output_queue); output_queue.push( make_pair(output_optional_type{}, -1) ); }; worker_pool workers{1}; workers.launch_tasks(*this, context_task); do_pipeline(output_queue, forward<OtherTransformers>(other_ops)... ); workers.wait(); } template <typename Queue, typename FarmTransformer, template <typename> class Farm, typename ... OtherTransformers, requires_farm<Farm<FarmTransformer>>> void parallel_execution_native::do_pipeline( Queue & input_queue, Farm<FarmTransformer> && farm_obj, OtherTransformers && ... other_transform_ops) const { using namespace std; using namespace experimental; using input_item_type = typename Queue::value_type; using input_item_value_type = typename input_item_type::first_type::value_type; using output_type = typename stage_return_type<input_item_value_type, FarmTransformer>::type; using output_optional_type = experimental::optional<output_type>; using output_item_type = pair <output_optional_type, long> ; decltype(auto) output_queue = get_output_queue<output_item_type>(other_transform_ops...); atomic<int> done_threads{0}; auto farm_task = [&](int nt) { do_pipeline(input_queue, farm_obj.transformer(), output_queue); done_threads++; if (done_threads == nt) { output_queue.push(make_pair(output_optional_type{}, -1)); }else{ input_queue.push(input_item_type{}); } }; auto ntasks = farm_obj.cardinality(); worker_pool workers{ntasks}; workers.launch_tasks(*this, farm_task, ntasks); do_pipeline(output_queue, forward<OtherTransformers>(other_transform_ops)... ); workers.wait(); } template <typename Queue, typename Predicate, template <typename> class Filter, typename ... OtherTransformers, requires_filter<Filter<Predicate>>> void parallel_execution_native::do_pipeline( Queue & input_queue, Filter<Predicate> && filter_obj, OtherTransformers && ... other_transform_ops) const { using namespace std; using namespace experimental; using input_item_type = typename Queue::value_type; using input_value_type = typename input_item_type::first_type; auto filter_queue = make_queue<input_item_type>(); auto filter_task = [&,this]() { auto manager = thread_manager(); auto item{input_queue.pop()}; while (item.first) { if (filter_obj(*item.first)) { filter_queue.push(item); } else { filter_queue.push(make_pair(input_value_type{}, item.second)); } item = input_queue.pop(); } filter_queue.push(make_pair(input_value_type{}, -1)); }; thread filter_thread{filter_task}; decltype(auto) output_queue = get_output_queue<input_item_type>(other_transform_ops...); thread ordering_thread; if (is_ordered()) { auto ordering_task = [&]() { auto manager = thread_manager(); vector<input_item_type> elements; int current = 0; long order = 0; auto item{filter_queue.pop()}; for (;;) { if(!item.first && item.second == -1) break; if (item.second == current) { if (item.first) { output_queue.push(make_pair(item.first,order)); order++; } current++; } else { elements.push_back(item); } auto it = find_if(elements.begin(), elements.end(), [&](auto x) { return x.second== current; }); if(it != elements.end()){ if (it->first) { output_queue.push(make_pair(it->first,order)); order++; } elements.erase(it); current++; } item = filter_queue.pop(); } while (elements.size()>0) { auto it = find_if(elements.begin(), elements.end(), [&](auto x) { return x.second== current; }); if(it != elements.end()){ if (it->first) { output_queue.push(make_pair(it->first,order)); order++; } elements.erase(it); current++; } } output_queue.push(item); }; ordering_thread = thread{ordering_task}; do_pipeline(output_queue, forward<OtherTransformers>(other_transform_ops)...); filter_thread.join(); ordering_thread.join(); } else { do_pipeline(filter_queue, forward<OtherTransformers>(other_transform_ops)...); filter_thread.join(); } } template <typename Queue, typename Combiner, typename Identity, template <typename C, typename I> class Reduce, typename ... OtherTransformers, requires_reduce<Reduce<Combiner,Identity>>> void parallel_execution_native::do_pipeline( Queue && input_queue, Reduce<Combiner,Identity> && reduce_obj, OtherTransformers && ... other_transform_ops) const { using namespace std; using namespace experimental; using output_item_value_type = optional<decay_t<Identity>>; using output_item_type = pair<output_item_value_type,long>; decltype(auto) output_queue = get_output_queue<output_item_type>(other_transform_ops...); auto reduce_task = [&,this]() { auto manager = thread_manager(); auto item{input_queue.pop()}; int order = 0; while (item.first) { reduce_obj.add_item(std::forward<Identity>(*item.first)); item = input_queue.pop(); if (reduce_obj.reduction_needed()) { constexpr sequential_execution seq; auto red = reduce_obj.reduce_window(seq); output_queue.push(make_pair(red, order++)); } } output_queue.push(make_pair(output_item_value_type{}, -1)); }; thread reduce_thread{reduce_task}; do_pipeline(output_queue, forward<OtherTransformers>(other_transform_ops)...); reduce_thread.join(); } template <typename Queue, typename Transformer, typename Predicate, template <typename T, typename P> class Iteration, typename ... OtherTransformers, requires_iteration<Iteration<Transformer,Predicate>>, requires_no_pattern<Transformer>> void parallel_execution_native::do_pipeline( Queue & input_queue, Iteration<Transformer,Predicate> && iteration_obj, OtherTransformers && ... other_transform_ops) const { using namespace std; using namespace experimental; using input_item_type = typename decay_t<Queue>::value_type; decltype(auto) output_queue = get_output_queue<input_item_type>(other_transform_ops...); auto iteration_task = [&]() { for (;;) { auto item = input_queue.pop(); if (!item.first) break; auto value = iteration_obj.transform(*item.first); auto new_item = input_item_type{value,item.second}; if (iteration_obj.predicate(value)) { output_queue.push(new_item); } else { input_queue.push(new_item); } } while (!input_queue.empty()) { auto item = input_queue.pop(); auto value = iteration_obj.transform(*item.first); auto new_item = input_item_type{value,item.second}; if (iteration_obj.predicate(value)) { output_queue.push(new_item); } else { input_queue.push(new_item); } } output_queue.push(input_item_type{{},-1}); }; thread iteration_thread{iteration_task}; do_pipeline(output_queue, forward<OtherTransformers>(other_transform_ops)...); iteration_thread.join(); } template <typename Queue, typename Transformer, typename Predicate, template <typename T, typename P> class Iteration, typename ... OtherTransformers, requires_iteration<Iteration<Transformer,Predicate>>, requires_pipeline<Transformer>> void parallel_execution_native::do_pipeline( Queue &, Iteration<Transformer,Predicate> &&, OtherTransformers && ...) const { static_assert(!is_pipeline<Transformer>, "Not implemented"); } template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, requires_pipeline<Pipeline<Transformers...>>> void parallel_execution_native::do_pipeline( Queue & input_queue, Pipeline<Transformers...> && pipeline_obj) const { do_pipeline_nested( input_queue, pipeline_obj.transformers(), std::make_index_sequence<sizeof...(Transformers)>()); } template <typename Queue, typename ... Transformers, template <typename...> class Pipeline, typename ... OtherTransformers, requires_pipeline<Pipeline<Transformers...>>> void parallel_execution_native::do_pipeline( Queue & input_queue, Pipeline<Transformers...> && pipeline_obj, OtherTransformers && ... other_transform_ops) const { do_pipeline_nested( input_queue, std::tuple_cat(pipeline_obj.transformers(), std::forward_as_tuple(other_transform_ops...)), std::make_index_sequence<sizeof...(Transformers)+sizeof...(OtherTransformers)>()); } template <typename Queue, typename ... Transformers, std::size_t ... I> void parallel_execution_native::do_pipeline_nested( Queue & input_queue, std::tuple<Transformers...> && transform_ops, std::index_sequence<I...>) const { do_pipeline(input_queue, std::forward<Transformers>(std::get<I>(transform_ops))...); } template<typename T, typename... Others> void parallel_execution_native::do_pipeline(mpmc_queue<T> &, mpmc_queue<T> &, Others &&...) const { } } // end namespace grppi #endif
[ "100346174@alumnos.uc3m.es" ]
100346174@alumnos.uc3m.es
a6fa669ea8149f23b11ceff0321c49defe9e3267
4e74d69497df34a17e770cdd078acfb809c0551d
/looper/process.cc
0a10dff627cfd395c99841ab7e3bfe41e2ca51f8
[]
no_license
sgnoohc/HighPtHiggs
09b5263f6c82bd22018ba6b3c04c2f4aa1b65119
a1d97ee1d48e1c9a2c93924aad33da6f8c0befca
refs/heads/master
2020-03-25T19:50:31.153924
2018-11-20T07:30:44
2018-11-20T07:30:44
144,102,858
0
0
null
null
null
null
UTF-8
C++
false
false
12,109
cc
#include "hwwtree.h" #include "rooutil/rooutil.h" // ./process INPUTFILEPATH OUTPUTFILEPATH [NEVENTS] int main(int argc, char** argv) { // Argument checking if (argc < 3) { std::cout << "Usage:" << std::endl; std::cout << " $ ./process INPUTFILES OUTPUTFILE [NEVENTS]" << std::endl; std::cout << std::endl; std::cout << " INPUTFILES comma separated file list" << std::endl; std::cout << " OUTPUTFILE output file name" << std::endl; std::cout << " [NEVENTS=-1] # of events to run over" << std::endl; std::cout << std::endl; return 1; } // Creating output file where we will put the outputs of the processing TFile* ofile = new TFile(argv[2], "recreate"); // Create a TChain of the input files // The input files can be comma separated (e.g. "file1.root,file2.root") or with wildcard (n.b. be sure to escape) TChain* ch = RooUtil::FileUtil::createTChain("t", argv[1]); // Number of events to loop over int nEvents = argc > 3 ? atoi(argv[3]) : -1; // Create a Looper object to loop over input files RooUtil::Looper<hwwtree> looper(ch, &hww, nEvents); // Cutflow utility object that creates a tree structure of cuts RooUtil::Cutflow cutflow(ofile); cutflow.addCut("CutWeight" , [&]() { return hww.CutGenHT() > 0; } , [&]() { return hww.wgt(); } ); cutflow.addCutToLastActiveCut("CutBVeto" , [&]() { return hww.nbmed() == 0; } , UNITY ); cutflow.addCutToLastActiveCut("CutNLep" , [&]() { return hww.CutNLep() > 0; } , UNITY ); cutflow.addCutToLastActiveCut("CutNAK8" , [&]() { return hww.nak8jets() > 0; } , UNITY ); // Some nested loops to create various cut regions with shorter lines of code std::vector<TString> ISRbins = {"300", "300to400", "400", "400to450", "450"}; std::vector<TString> LeptonChannels = {"El", "Mu"}; std::vector<TString> Charges = {"Plus", "Minus"}; for (auto& ISRbin : ISRbins) { float fISRbin = ISRbin.Atof(); cutflow.getCut("CutNAK8"); cutflow.addCutToLastActiveCut("CutISR"+ISRbin, [=]() { return hww.recoisrmegajet_pt() > fISRbin; }, UNITY); for (auto& lepton : LeptonChannels) { cutflow.getCut("CutISR"+ISRbin); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+lepton, [=]() { return lepton.EqualTo("El") ? hww.CutEl() : hww.CutMu(); }, UNITY); for (auto& charge : Charges) { cutflow.getCut("CutISR"+ISRbin+lepton); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+lepton+charge, [=]() { return charge.EqualTo("Plus") ? lepton.EqualTo("El") ? hww.CutElPlus() : hww.CutMuPlus() : lepton.EqualTo("El") ? hww.CutElMinus() : hww.CutMuMinus() ;}, UNITY ); cutflow.getCut("CutISR"+ISRbin+lepton+charge); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+lepton+charge+"RecoClassA", [=]() { return (hww.wlepwhadptratiodiff()>0.); }, UNITY); cutflow.getCut("CutISR"+ISRbin+lepton+charge); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+lepton+charge+"RecoClassB", [=]() { return (hww.wlepwhadptratiodiff()<0.); }, UNITY); } } } for (auto& ISRbin : ISRbins) { // CutMuMinusRecoClassA cutflow.getCut("CutISR"+ISRbin+"MuMinusRecoClassA"); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassAStrawManCut1", [=]() { return (hww.lep_relIso03EA()>0.2) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassAStrawManCut2", [=]() { return (hww.lep_miniIsoEA()<0.02) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassAStrawMan" , [=]() { return (hww.recowhad_puppi_mass()>60)*(hww.recowhad_puppi_mass()<105) ; }, UNITY); // CutMuPlusRecoClassA cutflow.getCut("CutISR"+ISRbin+"MuPlusRecoClassA"); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassAStrawManCut1", [=]() { return (hww.lep_relIso03EA()>0.2) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassAStrawManCut2", [=]() { return (hww.lep_miniIsoEA()<0.02) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassAStrawManCut3", [=]() { return (hww.recohiggs_max()<200.) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassAStrawMan" , [=]() { return (hww.recowhad_puppi_mass()>60)*(hww.recowhad_puppi_mass()<105) ; }, UNITY); // CutMuMinusRecoClassB cutflow.getCut("CutISR"+ISRbin+"MuMinusRecoClassB"); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut1", [=]() { return (hww.recolepton_recowhad_dr()<0.75) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut2", [=]() { return (hww.recowhad_puppi_mass()<130) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut3", [=]() { return (hww.lep_customrelIso005EA()<1.12) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut4", [=]() { return (hww.recowhad_plep_puppi_mass()<154.) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut5", [=]() { return (hww.recohiggs_min()<200.) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawManCut6", [=]() { return ((hww.recoisrmegajet_pt() / (hww.recowhad_puppi_pt() + hww.met_pt()) - 1)<0.2) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuMinusRecoClassBStrawMan" , [=]() { return ((hww.recowhad_mlep_puppi_mass()>70)*(hww.recowhad_mlep_puppi_mass()<100)) ; }, UNITY); // CutMuPlusRecoClassB cutflow.getCut("CutISR"+ISRbin+"MuPlusRecoClassB"); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawManCut1", [=]() { return (hww.recolepton_recowhad_dr()<0.75) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawManCut2", [=]() { return (hww.recowhad_puppi_mass()<125) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawManCut3", [=]() { return (hww.lep_customrelIso010EA()<1.28) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawManCut4", [=]() { return (hww.recowhad_plep_puppi_mass()<141.) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawManCut5", [=]() { return (hww.recohiggs_min()<200.) ; }, UNITY); cutflow.addCutToLastActiveCut("CutISR"+ISRbin+"MuPlusRecoClassBStrawMan" , [=]() { return ((hww.recowhad_mlep_puppi_mass()>75)*(hww.recowhad_mlep_puppi_mass()<105)) ; }, UNITY); } // Book cutflows cutflow.bookCutflows(); // Histogram utility object that is used to define the histograms RooUtil::Histograms histograms; histograms.addHistogram("lep_relIso03EA" , 180 , 0 , 4 , [=](){ return hww.lep_relIso03EA() ;} ); histograms.addHistogram("lep_miniIsoEA" , 180 , 0 , 4 , [=](){ return hww.lep_miniIsoEA() ;} ); histograms.addHistogram("recowhad_puppi_mass" , 180 , 0 , 300 , [=](){ return hww.recowhad_puppi_mass() ;} ); histograms.addHistogram("recohiggs_min" , 180 , 0 , 500 , [=](){ return hww.recohiggs_min() ;} ); histograms.addHistogram("recohiggs_max" , 180 , 0 , 500 , [=](){ return hww.recohiggs_max() ;} ); histograms.addHistogram("recolepton_recowhad_dr" , 180 , 0 , 4 , [=](){ return hww.recolepton_recowhad_dr() ;} ); histograms.addHistogram("recoisrbalance" , 180 , -1.5 , 1.5 , [=](){ return hww.recoisrmegajet_pt() / (hww.recowhad_puppi_pt() + hww.met_pt()) - 1 ;} ); histograms.addHistogram("recowhad_mlep_puppi_mass" , 180 , 0 , 300 , [=](){ return hww.recowhad_mlep_puppi_mass() ;} ); histograms.addHistogram("recowhad_plep_puppi_mass" , 180 , 0 , 300 , [=](){ return hww.recowhad_plep_puppi_mass() ;} ); histograms.addHistogram("lep_customrelIso005EA" , 180 , 0 , 10 , [=](){ return hww.lep_customrelIso005EA() ;} ); histograms.addHistogram("lep_customrelIso010EA" , 180 , 0 , 10 , [=](){ return hww.lep_customrelIso010EA() ;} ); histograms.addHistogram("yield" , 8 , 0 , 8 , [=](){ int yield = -1; if (hww.CutElMinus()&& (hww.wlepwhadptratiodiff() > 0.)) yield = 0; if (hww.CutElPlus() && (hww.wlepwhadptratiodiff() > 0.)) yield = 1; if (hww.CutElMinus()&& (hww.wlepwhadptratiodiff() < 0.)) yield = 2; if (hww.CutElPlus() && (hww.wlepwhadptratiodiff() < 0.)) yield = 3; if (hww.CutMuMinus()&& (hww.wlepwhadptratiodiff() > 0.)) yield = 4; if (hww.CutMuPlus() && (hww.wlepwhadptratiodiff() > 0.)) yield = 5; if (hww.CutMuMinus()&& (hww.wlepwhadptratiodiff() < 0.)) yield = 6; if (hww.CutMuPlus() && (hww.wlepwhadptratiodiff() < 0.)) yield = 7; return yield; }); // Book Histograms for (auto& ISRbin : ISRbins) { cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"ElPlusRecoClassA"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"ElPlusRecoClassB"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"ElMinusRecoClassA"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"ElMinusRecoClassB"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"MuPlusRecoClassA"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"MuPlusRecoClassB"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"MuMinusRecoClassA"); cutflow.bookHistogramsForCutAndBelow(histograms, "CutISR"+ISRbin+"MuMinusRecoClassB"); } // Print cut structure cutflow.printCuts(); // Looping input file while (looper.nextEvent()) { cutflow.fill(); } // Writing output file cutflow.saveOutput(); delete ofile; }
[ "sgnoohc@gmail.com" ]
sgnoohc@gmail.com
febfb7891c61b0fd43895c6f67f8f56e3349fd6f
057d61d3f948d5d93e06b8ee70bdfa13745cfb4d
/ShapesSphere.h
d827c3e2e6a1234eff166e2d48eee07a816880fb
[]
no_license
adamabeshouse/celshading
e6957bbc6e868ea4442f5823af2c281f5a52c981
5e75f6254856c96033dd229d362636b6c9d790d9
refs/heads/master
2016-08-05T15:10:16.392566
2012-12-17T14:04:13
2012-12-17T14:04:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
#ifndef SHAPESSPHERE_H #define SHAPESSPHERE_H #include "Shape.h" class ShapesSphere : public Shape { public: ShapesSphere(); ~ShapesSphere(); void renderSelf(int param1, int param2);//overrides Shape; recalculates vertexes if necessary, and renders all of them void calculateVertexes(int param1, int param2);//overrides Shape; calculates vertexes float sphereX(float r, float theta, float phi);//transforms spherical coordinates into cartesian X float sphereY(float r, float theta, float phi);//transforms spherical coordinates into cartesian Y float sphereZ(float r, float theta, float phi);//transforms spherical coordinates into cartesian Z void vertexAndNorm(float x, float y, float z, int coord_ind);//adds a vertex and its corresponding norm to m_vertex }; #endif // SHAPESSPHERE_H
[ "adamabeshouse@gmail.com" ]
adamabeshouse@gmail.com
fceb10b992e24af5156097f7da959bc99a229259
67ed24f7e68014e3dbe8970ca759301f670dc885
/win10.19042/System32/browcli.dll.cpp
0355d7ad48c2ab93a0bb0e6f1e4e21f64615ef2a
[]
no_license
nil-ref/dll-exports
d010bd77a00048e52875d2a739ea6a0576c82839
42ccc11589b2eb91b1aa82261455df8ee88fa40c
refs/heads/main
2023-04-20T21:28:05.295797
2021-05-07T14:06:23
2021-05-07T14:06:23
401,055,938
1
0
null
2021-08-29T14:00:50
2021-08-29T14:00:49
null
UTF-8
C++
false
false
1,400
cpp
#pragma comment(linker, "/export:I_BrowserDebugCall=\"C:\\Windows\\System32\\browcli.I_BrowserDebugCall\"") #pragma comment(linker, "/export:I_BrowserDebugTrace=\"C:\\Windows\\System32\\browcli.I_BrowserDebugTrace\"") #pragma comment(linker, "/export:I_BrowserQueryEmulatedDomains=\"C:\\Windows\\System32\\browcli.I_BrowserQueryEmulatedDomains\"") #pragma comment(linker, "/export:I_BrowserQueryOtherDomains=\"C:\\Windows\\System32\\browcli.I_BrowserQueryOtherDomains\"") #pragma comment(linker, "/export:I_BrowserQueryStatistics=\"C:\\Windows\\System32\\browcli.I_BrowserQueryStatistics\"") #pragma comment(linker, "/export:I_BrowserResetNetlogonState=\"C:\\Windows\\System32\\browcli.I_BrowserResetNetlogonState\"") #pragma comment(linker, "/export:I_BrowserResetStatistics=\"C:\\Windows\\System32\\browcli.I_BrowserResetStatistics\"") #pragma comment(linker, "/export:I_BrowserServerEnum=\"C:\\Windows\\System32\\browcli.I_BrowserServerEnum\"") #pragma comment(linker, "/export:I_BrowserSetNetlogonState=\"C:\\Windows\\System32\\browcli.I_BrowserSetNetlogonState\"") #pragma comment(linker, "/export:NetBrowserStatisticsGet=\"C:\\Windows\\System32\\browcli.NetBrowserStatisticsGet\"") #pragma comment(linker, "/export:NetServerEnum=\"C:\\Windows\\System32\\browcli.NetServerEnum\"") #pragma comment(linker, "/export:NetServerEnumEx=\"C:\\Windows\\System32\\browcli.NetServerEnumEx\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
4d31c9d27686a0b2d67f6b77f84a62dab01d176d
a9a9742197e8b6e39f4e2435790b799c32970ed9
/pipeitem.h
5dec48eb7c90aea90bcff954ac0855a63dd07423
[ "Apache-2.0" ]
permissive
renzibei/Flow_Simulate
89b91ae3654c528b9f65cb1378ec073b0a4efabd
b6ae896549acf6ed9197214b28b90d8f1fef85e3
refs/heads/master
2020-03-27T19:44:16.306351
2018-09-03T17:30:14
2018-09-03T17:30:14
147,008,625
1
0
null
null
null
null
UTF-8
C++
false
false
638
h
#ifndef PIPEITEM_H #define PIPEITEM_H #include <QObject> #include <QGraphicsItem> class PipeItem : public QObject, public QGraphicsRectItem { Q_OBJECT public: explicit PipeItem(const QRectF &rect, int index, int width = 200,QGraphicsItem *parent = nullptr); explicit PipeItem(qreal x, qreal y, qreal width, qreal height, int index = -1, QGraphicsItem *parent = nullptr); int index; int width; ~PipeItem(); protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); // void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); protected slots: void modifyWidth(); }; #endif // PIPEITEM_H
[ "fan_qu@icloud.com" ]
fan_qu@icloud.com
0c60432b27dab8ac48df7d6f0356a0685600a068
f545b662c838dc2001bfbb31560f43539204605b
/CSCE1040 - Computer Science II/Homework/Homework 4/borrow.cpp
dc87f3cdbd2c717f02d29f2afdcdc77b3a8caa90
[]
no_license
JustinAWei/UNT-CSCE
ec651dcee591af66ec3ba8e1cf87001ba4477c67
d7185e3e8481e68f12329720e521bd6e1be48e9a
refs/heads/master
2018-08-30T14:53:46.601906
2018-06-03T17:50:49
2018-06-03T17:51:27
118,659,731
2
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
/* Name: Justin Wei Email: JustinWei@my.unt.edu Course: CSCE 1040 Instructor: Keathly Description: A class that handles set/get of the borrow structure */ #include <string> #include <iostream> #include "borrow.h" using namespace std; borrow::borrow() { next = prev = NULL; } void borrow::print() { cout << endl; cout << "trans_id: " << trans_id << endl; cout << "book_id: " << book_id << endl; cout << "patron_id: " << patron_id << endl; cout << "Due: " << ctime(&due) << endl; cout << endl; } void borrow::set_recheck(bool i) { recheck = i; } void borrow::set_trans_id(int i) { trans_id = i; } void borrow::set_book_id(int i) { book_id = i; } void borrow::set_patron_id(int i) { patron_id = i; } void borrow::set_due(time_t i) { due = i; } int borrow::get_trans_id() { return trans_id; } int borrow::get_book_id() { return book_id; } int borrow::get_patron_id() { return patron_id; } time_t borrow::get_due() { return due; } bool borrow::get_recheck() { return recheck; } void borrow::set_next(borrow * p) { next = p; } void borrow::set_prev(borrow * p) { prev = p; } borrow * borrow::get_next() { return next; } borrow * borrow::get_prev() { return prev; }
[ "wei.justin.a@gmail.com" ]
wei.justin.a@gmail.com
cf45c9654bdada0d74f372ff36b2484a6fd3ce2d
c940cd64d47146efc42c005f4b3be9ee57ce2fc8
/src/MFCDia/MFCDia.cpp
453d53f34dcadbcea4ca359de0fdebdc7570520a
[]
no_license
pavelliavonau/windia
602b44e16a5ecf72f79e9f2f01d5d734e47a35fe
5f400fd45da8a810d90cca78f9c166ca15aff775
refs/heads/master
2020-05-30T20:41:30.104032
2017-12-20T11:08:53
2017-12-20T11:08:53
5,484,218
1
0
null
null
null
null
UTF-8
C++
false
false
4,814
cpp
// MFCDia.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "MFCDia.h" #include "MainFrm.h" #include "MFCDiaDoc.h" #include "MFCDiaView.h" #include "DiaGridView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCDiaApp BEGIN_MESSAGE_MAP(CMFCDiaApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CMFCDiaApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) END_MESSAGE_MAP() // CMFCDiaApp construction CMFCDiaApp::CMFCDiaApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("MFCDia.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CMFCDiaApp object CMFCDiaApp theApp; // CMFCDiaApp initialization BOOL CMFCDiaApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CMFCDiaDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CMFCDiaView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); GXInit(); //pDocTemplate = new CSingleDocTemplate( // IDR_MAINFRAME, // RUNTIME_CLASS(CMFCDiaDoc), // RUNTIME_CLASS(CMainFrame), // main SDI frame window // RUNTIME_CLASS(DiaGridView)); //if (!pDocTemplate) // return FALSE; //AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } // CMFCDiaApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CMFCDiaApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CMFCDiaApp message handlers
[ "paval@open.by" ]
paval@open.by
82dec165a7f5fee7890a338a64a6bba77f0c7f07
b014db08b4b051a04f84d667c319dcad97c4fc42
/ITP1_2/2_A.cpp
d3117fd142b2b62278b40fad0722ebe85d8cde87
[]
no_license
s1260116/AOJ-ITP
896855f8716faa1a9d43010a5fbbdf523a5a5448
5cea570ed5384a549123f976f61c33afa8ce3bab
refs/heads/master
2020-03-13T13:06:13.862996
2018-07-26T08:53:10
2018-07-26T08:53:10
131,132,317
0
0
null
2018-04-26T09:27:00
2018-04-26T09:26:59
null
UTF-8
C++
false
false
237
cpp
#include <iostream> using namespace std; int main(){ int a, b; cin >> a >> b; if(a == b){ cout << "a == b" << endl; } else if(a > b){ cout << "a > b" << endl; } else{ cout << "a < b" << endl; } return 0; }
[ "s1260116@u-aizu.ac.jp" ]
s1260116@u-aizu.ac.jp
7cd6601a1dd4cb64e24fb26e97b3bbddf61e399e
c6d94bc435f9619e1dac9b3b143fe90232d8d3f4
/software/NECESSARY LIBRARIES/libraries/CC3000/host_spi.cpp
95da2544edf7c1b212281009b54e7be5f608e9d6
[ "MIT" ]
permissive
jmicrobe/odin
20fdfd47586be3ed2f833e20922212f28fc1b483
85af6f162e55142636c5bf7a38eb75d5f6b0a808
refs/heads/master
2023-03-26T19:16:54.050087
2018-12-26T19:59:51
2018-12-26T19:59:51
111,130,227
1
2
null
null
null
null
UTF-8
C++
false
false
19,373
cpp
#include <Arduino.h> #include "SPI.h" #include "tm_debug.h" #include "host_spi.h" #include "utility/wlan.h" #include "utility/nvmem.h" #include "utility/security.h" #include "utility/hci.h" #include "utility/os.h" #include "utility/netapp.h" #include "utility/evnt_handler.h" #define READ 3 #define WRITE 1 #define HI(value) (((value) & 0xFF00) >> 8) #define LO(value) ((value) & 0x00FF) // #define ASSERT_CS() (P1OUT &= ~BIT3) // #define DEASSERT_CS() (P1OUT |= BIT3) #define HEADERS_SIZE_EVNT (SPI_HEADER_SIZE + 5) #define SPI_HEADER_SIZE (5) #define eSPI_STATE_POWERUP (0) #define eSPI_STATE_INITIALIZED (1) #define eSPI_STATE_IDLE (2) #define eSPI_STATE_WRITE_IRQ (3) #define eSPI_STATE_WRITE_FIRST_PORTION (4) #define eSPI_STATE_WRITE_EOT (5) #define eSPI_STATE_READ_IRQ (6) #define eSPI_STATE_READ_FIRST_PORTION (7) #define eSPI_STATE_READ_EOT (8) #define CC3000_nIRQ (3) #define HOST_nCS (10) #define HOST_VBAT_SW_EN (5) #define DISABLE (0) #define ENABLE (1) #define DEBUG_MODE (1) #define NETAPP_IPCONFIG_MAC_OFFSET (20) #define ConnLED (2) #define ErrorLED (4) #define LED (4) unsigned char tSpiReadHeader[] = {READ, 0, 0, 0, 0}; int uart_have_cmd; //foor spi bus loop int loc = 0; char device_name[] = "CC3000"; const char aucCC3000_prefix[] = {'T', 'T', 'T'}; // const unsigned char smartconfigkey[] = {0x73,0x6d,0x61,0x72,0x74,0x63,0x6f,0x6e,0x66,0x69,0x67,0x41,0x45,0x53,0x31,0x36}; static int keyIndex = 0; unsigned char printOnce = 1; volatile unsigned long ulSmartConfigFinished, ulCC3000Connected,ulCC3000DHCP, OkToDoShutDown, ulCC3000DHCP_configured; unsigned char ucStopSmartConfig; typedef struct { gcSpiHandleRx SPIRxHandler; unsigned short usTxPacketLength; unsigned short usRxPacketLength; unsigned long ulSpiState; unsigned char *pTxPacket; unsigned char *pRxPacket; } tSpiInformation; sockaddr tSocketAddr; tSpiInformation sSpiInformation; void SpiWriteDataSynchronous(unsigned char *data, unsigned short size); void SpiWriteAsync(const unsigned char *data, unsigned short size); void SpiPauseSpi(void); void SpiResumeSpi(void); void SSIContReadOperation(void); void SpiReadHeader(void); // The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size) // for the purpose of detection of the overrun. The location of the memory where the magic number // resides shall never be written. In case it is written - the overrun occured and either recevie function // or send function will stuck forever. #define CC3000_BUFFER_MAGIC_NUMBER (0xDE) /////////////////////////////////////////////////////////////////////////////////////////////////////////// //#pragma is used for determine the memory location for a specific variable. /// /// //__no_init is used to prevent the buffer initialization in order to prevent hardware WDT expiration /// // before entering to 'main()'. /// //for every IDE, different syntax exists : 1. __CCS__ for CCS v5 /// // 2. __IAR_SYSTEMS_ITM__ for IAR Embedded Workbench /// // *CCS does not initialize variables - therefore, __no_init is not needed. /// /////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned char wlan_tx_buffer[CC3000_TX_BUFFER_SIZE]; unsigned char spi_buffer[CC3000_RX_BUFFER_SIZE]; void csn(int mode) { digitalWrite(HOST_nCS,mode); } //***************************************************************************** // //! This function get the reason for the GPIO interrupt and clear cooresponding //! interrupt flag //! //! \param none //! //! \return none //! //! \brief This function This function get the reason for the GPIO interrupt //! and clear cooresponding interrupt flag // //***************************************************************************** void SpiCleanGPIOISR(void) { TM_DEBUG("SpiCleanGPIOISR\n\r"); //add code } //***************************************************************************** // //! SpiClose //! //! \param none //! //! \return none //! //! \brief Cofigure the SSI // //***************************************************************************** void SpiClose(void) { TM_DEBUG("SpiClose\n\r"); if (sSpiInformation.pRxPacket) { sSpiInformation.pRxPacket = 0; } // // Disable Interrupt in GPIOA module... // tSLInformation.WlanInterruptDisable(); } void SpiInit(){ ulCC3000DHCP = 0; ulCC3000Connected = 0; ulSmartConfigFinished=0; pinMode(CC3000_nIRQ, INPUT); attachInterrupt(1, SPI_IRQ, FALLING); //Attaches Pin 2 to interrupt 1 pinMode(HOST_nCS, OUTPUT); pinMode(HOST_VBAT_SW_EN, OUTPUT); pinMode(ConnLED, OUTPUT); pinMode(ErrorLED, OUTPUT); //Initialize SPI SPI.begin(); csn(HIGH); //Set bit order to MSB first SPI.setBitOrder(MSBFIRST); //Set data mode to CPHA 0 and CPOL 0 SPI.setDataMode(SPI_MODE1); //Set clock divider. This will be different for each board //For Due, this sets to 4MHz. CC3000 can go up to 26MHz //SPI.setClockDivider(SS, SPI_CLOCK_DIV21); //For other boards, cant select SS pin. Only divide by 4 to get 4MHz SPI.setClockDivider(SPI_CLOCK_DIV4); } //***************************************************************************** // //! SpiClose //! //! \param none //! //! \return none //! //! \brief Cofigure the SSI // //***************************************************************************** void SpiOpen(gcSpiHandleRx pfRxHandler) { TM_DEBUG("SpiOpen\n\r"); sSpiInformation.ulSpiState = eSPI_STATE_POWERUP; sSpiInformation.SPIRxHandler = pfRxHandler; sSpiInformation.usTxPacketLength = 0; sSpiInformation.pTxPacket = NULL; sSpiInformation.pRxPacket = (unsigned char *)spi_buffer; sSpiInformation.usRxPacketLength = 0; spi_buffer[CC3000_RX_BUFFER_SIZE - 1] = CC3000_BUFFER_MAGIC_NUMBER; wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] = CC3000_BUFFER_MAGIC_NUMBER; // Enable interrupt on the GPIOA pin of WLAN IRQ tSLInformation.WlanInterruptEnable(); TM_DEBUG("Completed SpiOpen\n\r"); } //***************************************************************************** // //! This function: init_spi //! //! \param buffer //! //! \return none //! //! \brief initializes an SPI interface // //***************************************************************************** long SpiFirstWrite(unsigned char *ucBuf, unsigned short usLength) { // // workaround for first transaction // TM_DEBUG("SpiFirstWrite\n\r"); // digitalWrite(HOST_nCS, LOW); csn(LOW); delayMicroseconds(80); // SPI writes first 4 bytes of data SpiWriteDataSynchronous(ucBuf, 4); delayMicroseconds(80); SpiWriteDataSynchronous(ucBuf + 4, usLength - 4); // SpiWriteDataSynchronous(testData, usLength - 4); // From this point on - operate in a regular way sSpiInformation.ulSpiState = eSPI_STATE_IDLE; // digitalWrite(HOST_nCS, HIGH); csn(HIGH); return(0); } long SpiWrite(unsigned char *pUserBuffer, unsigned short usLength) { unsigned char ucPad = 0; // // Figure out the total length of the packet in order to figure out if there is padding or not // if(!(usLength & 0x0001)) { ucPad++; } pUserBuffer[0] = WRITE; pUserBuffer[1] = HI(usLength + ucPad); pUserBuffer[2] = LO(usLength + ucPad); pUserBuffer[3] = 0; pUserBuffer[4] = 0; usLength += (SPI_HEADER_SIZE + ucPad); // The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size) // for the purpose of detection of the overrun. If the magic number is overriten - buffer overrun // occurred - and we will stuck here forever! if (wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER) { while (1) ; } // Serial.println("Checking for state"); // print_spi_state(); if (sSpiInformation.ulSpiState == eSPI_STATE_POWERUP) { while (sSpiInformation.ulSpiState != eSPI_STATE_INITIALIZED){ } ; } if (sSpiInformation.ulSpiState == eSPI_STATE_INITIALIZED) { // // This is time for first TX/RX transactions over SPI: the IRQ is down - so need to send read buffer size command // SpiFirstWrite(pUserBuffer, usLength); } else { // We need to prevent here race that can occur in case 2 back to back // packets are sent to the device, so the state will move to IDLE and once //again to not IDLE due to IRQ tSLInformation.WlanInterruptDisable(); while (sSpiInformation.ulSpiState != eSPI_STATE_IDLE) { ; } sSpiInformation.ulSpiState = eSPI_STATE_WRITE_IRQ; sSpiInformation.pTxPacket = pUserBuffer; sSpiInformation.usTxPacketLength = usLength; // assert CS //digitalWrite(HOST_nCS, LOW); csn(LOW); // reenable IRQ tSLInformation.WlanInterruptEnable(); } // check for a missing interrupt between the CS assertion and enabling back the interrupts if (tSLInformation.ReadWlanInterruptPin() == 0) { // Serial.println("writing synchronous data"); SpiWriteDataSynchronous(sSpiInformation.pTxPacket, sSpiInformation.usTxPacketLength); sSpiInformation.ulSpiState = eSPI_STATE_IDLE; //deassert CS csn(HIGH); } // // Due to the fact that we are currently implementing a blocking situation // here we will wait till end of transaction // while (eSPI_STATE_IDLE != sSpiInformation.ulSpiState) ; //Serial.println("done with spi write"); return(0); } void SpiWriteDataSynchronous(unsigned char *data, unsigned short size) { tSLInformation.WlanInterruptDisable(); while (size) { SPI.transfer(*data); size--; data++; } tSLInformation.WlanInterruptEnable(); } void SpiReadDataSynchronous(unsigned char *data, unsigned short size) { unsigned int i = 0; for (i = 0; i < size; i ++) { data[i] = SPI.transfer(tSpiReadHeader[0]); } } void SpiReadHeader(void) { SpiReadDataSynchronous(sSpiInformation.pRxPacket, 10); } long SpiReadDataCont(void) { long data_to_recv; unsigned char *evnt_buff, type; // //determine what type of packet we have // evnt_buff = sSpiInformation.pRxPacket; data_to_recv = 0; STREAM_TO_UINT8((char *)(evnt_buff + SPI_HEADER_SIZE), HCI_PACKET_TYPE_OFFSET, type); switch(type) { case HCI_TYPE_DATA: { // // We need to read the rest of data.. // STREAM_TO_UINT16((char *)(evnt_buff + SPI_HEADER_SIZE), HCI_DATA_LENGTH_OFFSET, data_to_recv); if (!((HEADERS_SIZE_EVNT + data_to_recv) & 1)) { data_to_recv++; } if (data_to_recv) { SpiReadDataSynchronous(evnt_buff + 10, data_to_recv); } break; } case HCI_TYPE_EVNT: { // // Calculate the rest length of the data // STREAM_TO_UINT8((char *)(evnt_buff + SPI_HEADER_SIZE), HCI_EVENT_LENGTH_OFFSET, data_to_recv); data_to_recv -= 1; // // Add padding byte if needed // if ((HEADERS_SIZE_EVNT + data_to_recv) & 1) { data_to_recv++; } if (data_to_recv) { SpiReadDataSynchronous(evnt_buff + 10, data_to_recv); } sSpiInformation.ulSpiState = eSPI_STATE_READ_EOT; break; } } return (0); } void SpiPauseSpi(void) { detachInterrupt(0); //Detaches Pin 3 from interrupt 1 } void SpiResumeSpi(void) { attachInterrupt(0, SPI_IRQ, FALLING); //Attaches Pin 2 to interrupt 1 } void SpiTriggerRxProcessing(void) { // // // // Trigger Rx processing // // SpiPauseSpi(); csn(HIGH); //DEASSERT_CS(); //digitalWrite(HOST_nCS, HIGH); // The magic number that resides at the end of the TX/RX buffer (1 byte after // the allocated size) for the purpose of detection of the overrun. If the // magic number is overwritten - buffer overrun occurred - and we will stuck // here forever! if (sSpiInformation.pRxPacket[CC3000_RX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER) { while (1) { ; } } sSpiInformation.ulSpiState = eSPI_STATE_IDLE; sSpiInformation.SPIRxHandler(sSpiInformation.pRxPacket + SPI_HEADER_SIZE); } void StartSmartConfig(void) { ulSmartConfigFinished = 0; ulCC3000Connected = 0; ulCC3000DHCP = 0; OkToDoShutDown=0; // Reset all the previous configuration if (wlan_ioctl_set_connection_policy(0, 0, 0) != 0) { digitalWrite(ErrorLED, HIGH); return; } if (wlan_ioctl_del_profile(255) != 0) { digitalWrite(ErrorLED, HIGH); return; } //Wait until CC3000 is disconnected while (ulCC3000Connected == 1) { delayMicroseconds(100); } // Serial.println("waiting for disconnect"); // Trigger the Smart Config process // Start blinking LED6 during Smart Configuration process digitalWrite(ConnLED, HIGH); if (wlan_smart_config_set_prefix((char*)aucCC3000_prefix) != 0){ digitalWrite(ErrorLED, HIGH); return; } digitalWrite(ConnLED, LOW); // Start the SmartConfig start process if (wlan_smart_config_start(0) != 0){ digitalWrite(ErrorLED, HIGH); return; } if (DEBUG_MODE) { Serial.println("smart config start"); } digitalWrite(ConnLED, HIGH); // Wait for Smartconfig process complete while (ulSmartConfigFinished == 0) { delay(500); digitalWrite(ConnLED, LOW); delay(500); digitalWrite(ConnLED, HIGH); } if (DEBUG_MODE) { Serial.println("smart config finished"); } digitalWrite(ConnLED, LOW); // Configure to connect automatically to the AP retrieved in the // Smart config process. Enabled fast connect. if (wlan_ioctl_set_connection_policy(0, 0, 1) != 0){ digitalWrite(ErrorLED, HIGH); return; } // reset the CC3000 wlan_stop(); delayMicroseconds(500); wlan_start(0); // Mask out all non-required events wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|HCI_EVNT_WLAN_UNSOL_INIT|HCI_EVNT_WLAN_ASYNC_PING_REPORT); if (DEBUG_MODE) { Serial.print("Config done"); } } //***************************************************************************** // //! Returns state of IRQ pin //! // //***************************************************************************** long ReadWlanInterruptPin(void) { return(digitalRead(CC3000_nIRQ)); } void WlanInterruptEnable() { attachInterrupt(0, SPI_IRQ, FALLING); //Attaches Pin 2 to interrupt 1 } void WlanInterruptDisable() { detachInterrupt(0); //Detaches Pin 3 from interrupt 1 } void SPI_IRQ(void) { if (sSpiInformation.ulSpiState == eSPI_STATE_POWERUP) { //This means IRQ line was low call a callback of HCI Layer to inform on event sSpiInformation.ulSpiState = eSPI_STATE_INITIALIZED; } else if (sSpiInformation.ulSpiState == eSPI_STATE_IDLE) { sSpiInformation.ulSpiState = eSPI_STATE_READ_IRQ; //IRQ line goes down - we are start reception csn(LOW); // // Wait for TX/RX Compete which will come as DMA interrupt // SpiReadHeader(); sSpiInformation.ulSpiState = eSPI_STATE_READ_EOT; SSIContReadOperation(); } else if (sSpiInformation.ulSpiState == eSPI_STATE_WRITE_IRQ) { SpiWriteDataSynchronous(sSpiInformation.pTxPacket, sSpiInformation.usTxPacketLength); sSpiInformation.ulSpiState = eSPI_STATE_IDLE; csn(HIGH); } return; } void print_spi_state(void) { if (DEBUG_MODE) { switch (sSpiInformation.ulSpiState) { case eSPI_STATE_POWERUP: TM_DEBUG("POWERUP\n\r"); break; case eSPI_STATE_INITIALIZED: TM_DEBUG("INITIALIZED\n\r"); break; case eSPI_STATE_IDLE: TM_DEBUG("IDLE\n\r"); break; case eSPI_STATE_WRITE_IRQ: TM_DEBUG("WRITE_IRQ\n\r"); break; case eSPI_STATE_WRITE_FIRST_PORTION: TM_DEBUG("WRITE_FIRST_PORTION\n\r"); break; case eSPI_STATE_WRITE_EOT: TM_DEBUG("WRITE_EOT\n\r"); break; case eSPI_STATE_READ_IRQ: TM_DEBUG("READ_IRQ\n\r"); break; case eSPI_STATE_READ_FIRST_PORTION: TM_DEBUG("READ_FIRST_PORTION\n\r"); break; case eSPI_STATE_READ_EOT: TM_DEBUG("STATE_READ_EOT\n\r"); break; default: break; } } return; } void WriteWlanPin( unsigned char val ) { if (val) { digitalWrite(HOST_VBAT_SW_EN, HIGH); } else { digitalWrite(HOST_VBAT_SW_EN, LOW); } } //***************************************************************************** // // The function handles asynchronous events that come from CC3000 device //! // //***************************************************************************** void CC3000_UsynchCallback(long lEventType, char * data, unsigned char length) { if (lEventType == HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE) { ulSmartConfigFinished = 1; ucStopSmartConfig = 1; } if (lEventType == HCI_EVNT_WLAN_UNSOL_CONNECT) { ulCC3000Connected = 1; TM_DEBUG("connected\n\r"); } if (lEventType == HCI_EVNT_WLAN_UNSOL_DISCONNECT) { ulCC3000Connected = 0; ulCC3000DHCP = 0; ulCC3000DHCP_configured = 0; printOnce = 1; TM_DEBUG("disconnected\n\r"); digitalWrite(ConnLED, LOW); // digitalWrite(ErrorLED, HIGH); } if (lEventType == HCI_EVNT_WLAN_UNSOL_DHCP) { TM_DEBUG("dhcp\n\r"); // Notes: // 1) IP config parameters are received swapped // 2) IP config parameters are valid only if status is OK, i.e. ulCC3000DHCP becomes 1 // only if status is OK, the flag is set to 1 and the addresses are valid if ( *(data + NETAPP_IPCONFIG_MAC_OFFSET) == 0) { //sprintf( (char*)pucCC3000_Rx_Buffer,"IP:%d.%d.%d.%d\f\r", data[3],data[2], data[1], data[0] ); ulCC3000DHCP = 1; TM_DEBUG("DHCP Connected with IP: %hhu.%hhu.%hhu.%hhu\n\r", (unsigned char) data[3], (unsigned char) data[2], (unsigned char) data[1], (unsigned char) data[0]); digitalWrite(ConnLED, HIGH); } else { ulCC3000DHCP = 0; TM_DEBUG("DHCP failed\n\r"); digitalWrite(ConnLED, LOW); } } if (lEventType == HCI_EVENT_CC3000_CAN_SHUT_DOWN) { OkToDoShutDown = 1; } } // ***************************************************************************** // ! This function enter point for write flow // ! // ! \param SSIContReadOperation // ! // ! \return none // ! // ! \brief The function triggers a user provided callback for // ***************************************************************************** void SSIContReadOperation(void) { //Serial.println("SSIContReadOp"); // // The header was read - continue with the payload read // if (!SpiReadDataCont()) { // // All the data was read - finalize handling by switching to teh task // and calling from task Event Handler // SpiTriggerRxProcessing(); } }
[ "jess@jmicrobe.me" ]
jess@jmicrobe.me
61673d8c1b21910f61c908a29cac94652f9fd214
7be0cf5b98c891efc0972ff4e1a5a5430893162c
/AI/Wrappers/Cpp/src-generated/Economy.h
ac740603699d177b782b5e810f44dd3177a4aea6
[]
no_license
spring/spring-ai-includes
7358397df73d571fae36037e14bfd0bc4b39433e
24417cc1920814c6542ec43e6d7a2d79cb98a4ec
refs/heads/master
2021-01-17T17:25:35.096192
2016-10-09T04:26:38
2016-10-09T04:26:38
70,375,079
1
0
null
null
null
null
UTF-8
C++
false
false
2,172
h
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ /* Note: This file is machine generated, do not edit directly! */ #ifndef _CPPWRAPPER_ECONOMY_H #define _CPPWRAPPER_ECONOMY_H #include <climits> // for INT_MAX (required by unit-command wrapping functions) #include "IncludesHeaders.h" namespace springai { /** * Lets C++ Skirmish AIs call back to the Spring engine. * * @author AWK wrapper script * @version GENERATED */ class Economy { public: virtual ~Economy(){} public: virtual int GetSkirmishAIId() const = 0; public: virtual float GetCurrent(Resource* resource) = 0; public: virtual float GetIncome(Resource* resource) = 0; public: virtual float GetUsage(Resource* resource) = 0; public: virtual float GetStorage(Resource* resource) = 0; public: virtual float GetPull(Resource* resource) = 0; public: virtual float GetShare(Resource* resource) = 0; public: virtual float GetSent(Resource* resource) = 0; public: virtual float GetReceived(Resource* resource) = 0; public: virtual float GetExcess(Resource* resource) = 0; /** * Give \<amount\> units of resource \<resourceId\> to team \<receivingTeam\>. * - the amount is capped to the AI team's resource levels * - does not check for alliance with \<receivingTeam\> * - LuaRules might not allow resource transfers, AI's must verify the deduction */ public: virtual bool SendResource(Resource* resource, float amount, int receivingTeamId) = 0; /** * Give units specified by \<unitIds\> to team \<receivingTeam\>. * \<ret_sentUnits\> represents how many actually were transferred. * Make sure this always matches the size of \<unitIds\> you passed in. * If it does not, then some unitId's were filtered out. * - does not check for alliance with \<receivingTeam\> * - AI's should check each unit if it is still under control of their * team after the transaction via UnitTaken() and UnitGiven(), since * LuaRules might block part of it */ public: virtual int SendUnits(std::vector<springai::Unit*> unitIds_list, int receivingTeamId) = 0; }; // class Economy } // namespace springai #endif // _CPPWRAPPER_ECONOMY_H
[ "spring@abma.de" ]
spring@abma.de
bafdd4689fea3ceb29a9f00b28d11419f6d34317
9a11a7ac04bb4d646d4e0f0ad12fc41bd61cec09
/universe/olcPixelGameEngine.h
f006058b1ac69e75593bbd15c724c228fdbca194
[]
no_license
dynamic21/universe
150153b01ae4e98eabb9b61cb098811626805d98
1e776bb19f3f00effa84200ed9dac0bc2170b6ac
refs/heads/master
2023-04-08T23:42:13.849184
2021-04-10T22:12:08
2021-04-10T22:12:08
355,658,369
0
0
null
null
null
null
ISO-8859-2
C++
false
false
195,758
h
#pragma region license_and_help /* olcPixelGameEngine.h +-------------------------------------------------------------+ | OneLoneCoder Pixel Game Engine v2.15 | | "What do you need? Pixels... Lots of Pixels..." - javidx9 | +-------------------------------------------------------------+ What is this? ~~~~~~~~~~~~~ olc::PixelGameEngine is a single file, cross platform graphics and userinput framework used for games, visualisations, algorithm exploration and learning. It was developed by YouTuber "javidx9" as an assistive tool for many of his videos. The goal of this project is to provide high speed graphics with minimal project setup complexity, to encourage new programmers, younger people, and anyone else that wants to make fun things. However, olc::PixelGameEngine is not a toy! It is a powerful and fast utility capable of delivering high resolution, high speed, high quality applications which behave the same way regardless of the operating system or platform. This file provides the core utility set of the olc::PixelGameEngine, including window creation, keyboard/mouse input, main game thread, timing, pixel drawing routines, image/sprite loading and drawing routines, and a bunch of utility types to make rapid development of games/visualisations possible. License (OLC-3) ~~~~~~~~~~~~~~~ Copyright 2018 - 2021 OneLoneCoder.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions or derivations of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions or derivative works in binary form must reproduce the above copyright notice. This list of conditions and the following disclaimer must be reproduced in the documentation and/or other materials provided with the distribution. 3. 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. Links ~~~~~ YouTube: https://www.youtube.com/javidx9 https://www.youtube.com/javidx9extra Discord: https://discord.gg/WhwHUMV Twitter: https://www.twitter.com/javidx9 Twitch: https://www.twitch.tv/javidx9 GitHub: https://www.github.com/onelonecoder Homepage: https://www.onelonecoder.com Patreon: https://www.patreon.com/javidx9 Community: https://community.onelonecoder.com Compiling in Linux ~~~~~~~~~~~~~~~~~~ You will need a modern C++ compiler, so update yours! To compile use the command: g++ -o YourProgName YourSource.cpp -lX11 -lGL -lpthread -lpng -lstdc++fs -std=c++17 On some Linux configurations, the frame rate is locked to the refresh rate of the monitor. This engine tries to unlock it but may not be able to, in which case try launching your program like this: vblank_mode=0 ./YourProgName Compiling in Code::Blocks on Windows ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Well I wont judge you, but make sure your Code::Blocks installation is really up to date - you may even consider updating your C++ toolchain to use MinGW32-W64. Guide for installing recent GCC for Windows: https://www.msys2.org/ Guide for configuring code::blocks: https://solarianprogrammer.com/2019/11/05/install-gcc-windows/ https://solarianprogrammer.com/2019/11/16/install-codeblocks-gcc-windows-build-c-cpp-fortran-programs/ Add these libraries to "Linker Options": user32 gdi32 opengl32 gdiplus Shlwapi dwmapi stdc++fs Set these compiler options: -std=c++17 Compiling on Mac - EXPERIMENTAL! PROBABLY HAS BUGS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Yes yes, people use Macs for C++ programming! Who knew? Anyway, enough arguing, thanks to Mumflr the PGE is now supported on Mac. Now I know nothing about Mac, so if you need support, I suggest checking out the instructions here: https://github.com/MumflrFumperdink/olcPGEMac clang++ -arch x86_64 -std=c++17 -mmacosx-version-min=10.15 -Wall -framework OpenGL -framework GLUT -lpng YourSource.cpp -o YourProgName Compiling with Emscripten (New & Experimental) ~~~~~~~~~~~~~~~~~~~~~~~~~ Emscripten compiler will turn your awesome C++ PixelGameEngine project into WASM! This means you can run your application in teh browser, great for distributing and submission in to jams and things! It's a bit new at the moment. em++ -std=c++17 -O2 -s ALLOW_MEMORY_GROWTH=1 -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_LIBPNG=1 ./YourSource.cpp -o pge.html Using stb_image.h ~~~~~~~~~~~~~~~~~ The PGE will load png images by default (with help from libpng on non-windows systems). However, the excellent "stb_image.h" can be used instead, supporting a variety of image formats, and has no library dependence - something we like at OLC studios ;) To use stb_image.h, make sure it's in your code base, and simply: #define OLC_IMAGE_STB Before including the olcPixelGameEngine.h header file. stb_image.h works on many systems and can be downloaded here: https://github.com/nothings/stb/blob/master/stb_image.h Multiple cpp file projects? ~~~~~~~~~~~~~~~~~~~~~~~~~~~ As a single header solution, the OLC_PGE_APPLICATION definition is used to insert the engine implementation at a project location of your choosing. The simplest way to setup multifile projects is to create a file called "olcPixelGameEngine.cpp" which includes the following: #define OLC_PGE_APPLICATION #include "olcPixelGameEngine.h" That's all it should include. You can also include PGEX includes and defines in here too. With this in place, you dont need to #define OLC_PGE_APPLICATION anywhere, and can simply include this header file as an when you need to. Ports ~~~~~ olc::PixelGameEngine has been ported and tested with varying degrees of success to: WinXP, Win7, Win8, Win10, Various Linux, Raspberry Pi, Chromebook, Playstation Portable (PSP) and Nintendo Switch. If you are interested in the details of these ports, come and visit the Discord! Thanks ~~~~~~ I'd like to extend thanks to Ian McKay, Bispoo, Eremiell, slavka, gurkanctn, Phantim, IProgramInCPP, JackOJC, KrossX, Huhlig, Dragoneye, Appa, JustinRichardsMusic, SliceNDice, dandistine, Ralakus, Gorbit99, raoul, joshinils, benedani, Moros1138, Alexio, SaladinAkara & MagetzUb for advice, ideas and testing, and I'd like to extend my appreciation to the 230K YouTube followers, 80+ Patreons and 10K Discord server members who give me the motivation to keep going with all this :D Significant Contributors: @Moros1138, @SaladinAkara, @MaGetzUb, @slavka, @Dragoneye, @Gorbit99, @dandistine & @Mumflr Special thanks to those who bring gifts! GnarGnarHead.......Domina Gorbit99...........Bastion, Ori & The Blind Forest, Terraria, Spelunky 2 Marti Morta........Gris Danicron...........Terraria SaladinAkara.......Aseprite, Inside AlterEgo...........Final Fantasy XII - The Zodiac Age SlicEnDicE.........Noita, Inside Special thanks to my Patreons too - I wont name you on here, but I've certainly enjoyed my tea and flapjacks :D Author ~~~~~~ David Barr, aka javidx9, ŠOneLoneCoder 2018, 2019, 2020, 2021 */ #pragma endregion #pragma region version_history /* 2.01: Made renderer and platform static for multifile projects 2.02: Added Decal destructor, optimised Pixel constructor 2.03: Added FreeBSD flags, Added DrawStringDecal() 2.04: Windows Full-Screen bug fixed 2.05: +DrawPartialWarpedDecal() - draws a warped decal from a subset image +DrawPartialRotatedDecal() - draws a rotated decal from a subset image 2.06: +GetTextSize() - returns area occupied by multiline string +GetWindowSize() - returns actual window size +GetElapsedTime() - returns last calculated fElapsedTime +GetWindowMouse() - returns actual mouse location in window +DrawExplicitDecal() - bow-chikka-bow-bow +DrawPartialDecal(pos, size) - draws a partial decal to specified area +FillRectDecal() - draws a flat shaded rectangle as a decal +GradientFillRectDecal() - draws a rectangle, with unique colour corners +Modified DrawCircle() & FillCircle() - Thanks IanM-Matrix1 (#PR121) +Gone someway to appeasing pedants 2.07: +GetPixelSize() - returns user specified pixel size +GetScreenPixelSize() - returns actual size in monitor pixels +Pixel Cohesion Mode (flag in Construct()) - disallows arbitrary window scaling +Working VSYNC in Windows windowed application - now much smoother +Added string conversion for olc::vectors +Added comparator operators for olc::vectors +Added DestroyWindow() on windows platforms for serial PGE launches +Added GetMousePos() to stop TarriestPython whinging 2.08: Fix SetScreenSize() aspect ratio pre-calculation Fix DrawExplicitDecal() - stupid oversight with multiple decals Disabled olc::Sprite copy constructor +olc::Sprite Duplicate() - produces a new clone of the sprite +olc::Sprite Duplicate(pos, size) - produces a new sprite from the region defined +Unary operators for vectors +More pedant mollification - Thanks TheLandfill +ImageLoader modules - user selectable image handling core, gdi+, libpng, stb_image +Mac Support via GLUT - thanks Mumflr! 2.09: Fix olc::Renderable Image load error - Thanks MaGetzUb & Zij-IT for finding and moaning about it Fix file rejection in image loaders when using resource packs Tidied Compiler defines per platform - Thanks slavka +Pedant fixes, const correctness in parts +DecalModes - Normal, Additive, Multiplicative blend modes +Pixel Operators & Lerping +Filtered Decals - If you hate pixels, then erase this file +DrawStringProp(), GetTextSizeProp(), DrawStringPropDecal() - Draws non-monospaced font 2.10: Fix PixelLerp() - oops my bad, lerped the wrong way :P Fix "Shader" support for strings - thanks Megarev for crying about it Fix GetTextSizeProp() - Height was just plain wrong... +vec2d operator overloads (element wise *=, /=) +vec2d comparison operators... :| yup... hmmmm... +vec2d ceil(), floor(), min(), max() functions - surprising how often I do it manually +DrawExplicitDecal(... uint32_t elements) - complete control over convex polygons and lines +DrawPolygonDecal() - to keep Bispoo happy, required significant rewrite of EVERYTHING, but hey ho +Complete rewrite of decal renderer +OpenGL 3.3 Renderer (also supports Raspberry Pi) +PGEX Break-In Hooks - with a push from Dandistine +Wireframe Decal Mode - For debug overlays 2.11: Made PGEX hooks optional - (provide true to super constructor) 2.12: Fix for MinGW compiler non-compliance :( - why is its sdk structure different?? why??? 2.13: +GetFontSprite() - allows access to font data 2.14: Fix WIN32 Definition reshuffle Fix DrawPartialDecal() - messed up dimension during renderer experiment, didnt remove junk code, thanks Alexio Fix? Strange error regarding GDI+ Image Loader not knowing about COM, SDK change? 2.15: Big Reformat +WASM Platform (via Emscripten) - Big Thanks to OLC Community - See Platform for details +Sample Mode for Decals +Made olc_ConfigureSystem() accessible +Added OLC_----_CUSTOM_EX for externalised platforms, renderers and image loaders =Refactored olc::Sprite pixel data store -Deprecating LoadFromPGESprFile() -Deprecating SaveToPGESprFile() Fix Pixel -= operator (thanks Au Lit) !! Apple Platforms will not see these updates immediately - Sorry, I dont have a mac to test... !! !! Volunteers willing to help appreciated, though PRs are manually integrated with credit !! */ #pragma endregion #pragma region hello_world_example // O------------------------------------------------------------------------------O // | Example "Hello World" Program (main.cpp) | // O------------------------------------------------------------------------------O /* #define OLC_PGE_APPLICATION #include "olcPixelGameEngine.h" // Override base class with your custom functionality class Example : public olc::PixelGameEngine { public: Example() { // Name your application sAppName = "Example"; } public: bool OnUserCreate() override { // Called once at the start, so create things here return true; } bool OnUserUpdate(double fElapsedTime) override { // Called once per frame, draws random coloured pixels for (int x = 0; x < ScreenWidth(); x++) for (int y = 0; y < ScreenHeight(); y++) Draw(x, y, olc::Pixel(rand() % 256, rand() % 256, rand() % 256)); return true; } }; int main() { Example demo; if (demo.Construct(256, 240, 4, 4)) demo.Start(); return 0; } */ #pragma endregion #ifndef OLC_PGE_DEF #define OLC_PGE_DEF #pragma region std_includes // O------------------------------------------------------------------------------O // | STANDARD INCLUDES | // O------------------------------------------------------------------------------O #include <cmath> #include <cstdint> #include <string> #include <iostream> #include <streambuf> #include <sstream> #include <chrono> #include <vector> #include <list> #include <thread> #include <atomic> #include <fstream> #include <map> #include <functional> #include <algorithm> #include <array> #include <cstring> #pragma endregion #define PGE_VER 215 // O------------------------------------------------------------------------------O // | COMPILER CONFIGURATION ODDITIES | // O------------------------------------------------------------------------------O #pragma region compiler_config #define USE_EXPERIMENTAL_FS #if defined(_WIN32) #if _MSC_VER >= 1920 && _MSVC_LANG >= 201703L #undef USE_EXPERIMENTAL_FS #endif #endif #if defined(__linux__) || defined(__MINGW32__) || defined(__EMSCRIPTEN__) || defined(__FreeBSD__) || defined(__APPLE__) #if __cplusplus >= 201703L #undef USE_EXPERIMENTAL_FS #endif #endif #if defined(USE_EXPERIMENTAL_FS) || defined(FORCE_EXPERIMENTAL_FS) // C++14 #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> namespace _gfs = std::experimental::filesystem::v1; #else // C++17 #include <filesystem> namespace _gfs = std::filesystem; #endif #if defined(UNICODE) || defined(_UNICODE) #define olcT(s) L##s #else #define olcT(s) s #endif #define UNUSED(x) (void)(x) // O------------------------------------------------------------------------------O // | PLATFORM SELECTION CODE, Thanks slavka! | // O------------------------------------------------------------------------------O // Platform #if !defined(OLC_PLATFORM_WINAPI) && !defined(OLC_PLATFORM_X11) && !defined(OLC_PLATFORM_GLUT) && !defined(OLC_PLATFORM_EMSCRIPTEN) #if !defined(OLC_PLATFORM_CUSTOM_EX) #if defined(_WIN32) #define OLC_PLATFORM_WINAPI #endif #if defined(__linux__) || defined(__FreeBSD__) #define OLC_PLATFORM_X11 #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #define OLC_PLATFORM_GLUT #endif #if defined(__EMSCRIPTEN__) #define OLC_PLATFORM_EMSCRIPTEN #endif #endif #endif // Start Situation #if defined(OLC_PLATFORM_GLUT) || defined(OLC_PLATFORM_EMSCRIPTEN) #define PGE_USE_CUSTOM_START #endif // Renderer #if !defined(OLC_GFX_OPENGL10) && !defined(OLC_GFX_OPENGL33) && !defined(OLC_GFX_DIRECTX10) #if !defined(OLC_GFX_CUSTOM_EX) #if defined(OLC_PLATFORM_EMSCRIPTEN) #define OLC_GFX_OPENGL33 #else #define OLC_GFX_OPENGL10 #endif #endif #endif // Image loader #if !defined(OLC_IMAGE_STB) && !defined(OLC_IMAGE_GDI) && !defined(OLC_IMAGE_LIBPNG) #if !defined(OLC_IMAGE_CUSTOM_EX) #if defined(_WIN32) #define OLC_IMAGE_GDI #endif #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) #define OLC_IMAGE_LIBPNG #endif #endif #endif // O------------------------------------------------------------------------------O // | PLATFORM-SPECIFIC DEPENDENCIES | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_WINAPI) #define _WINSOCKAPI_ // Thanks Cornchipss #if !defined(VC_EXTRALEAN) #define VC_EXTRALEAN #endif #if !defined(NOMINMAX) #define NOMINMAX #endif // In Code::Blocks #if !defined(_WIN32_WINNT) #ifdef HAVE_MSMF #define _WIN32_WINNT 0x0600 // Windows Vista #else #define _WIN32_WINNT 0x0500 // Windows 2000 #endif #endif #include <windows.h> #undef _WINSOCKAPI_ #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <X11/X.h> #include <X11/Xlib.h> } #endif #if defined(OLC_PLATFORM_GLUT) #if defined(__linux__) #include <GL/glut.h> #include <GL/freeglut_ext.h> #endif #if defined(__APPLE__) #include <GLUT/glut.h> #endif #endif #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine INTERFACE DECLARATION | // O------------------------------------------------------------------------------O #pragma region pge_declaration namespace olc { class PixelGameEngine; class Sprite; // Pixel Game Engine Advanced Configuration constexpr uint8_t nMouseButtons = 5; constexpr uint8_t nDefaultAlpha = 0xFF; constexpr uint32_t nDefaultPixel = (nDefaultAlpha << 24); enum rcode { FAIL = 0, OK = 1, NO_FILE = -1 }; // O------------------------------------------------------------------------------O // | olc::Pixel - Represents a 32-Bit RGBA colour | // O------------------------------------------------------------------------------O struct Pixel { union { uint32_t n = nDefaultPixel; struct { uint8_t r; uint8_t g; uint8_t b; uint8_t a; }; }; enum Mode { NORMAL, MASK, ALPHA, CUSTOM }; Pixel(); Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = nDefaultAlpha); Pixel(uint32_t p); Pixel& operator = (const Pixel& v) = default; bool operator ==(const Pixel& p) const; bool operator !=(const Pixel& p) const; Pixel operator * (const float i) const; Pixel operator / (const float i) const; Pixel& operator *=(const float i); Pixel& operator /=(const float i); Pixel operator + (const Pixel& p) const; Pixel operator - (const Pixel& p) const; Pixel& operator +=(const Pixel& p); Pixel& operator -=(const Pixel& p); Pixel inv() const; }; Pixel PixelF(float red, float green, float blue, float alpha = 1.0f); Pixel PixelLerp(const olc::Pixel& p1, const olc::Pixel& p2, float t); // O------------------------------------------------------------------------------O // | USEFUL CONSTANTS | // O------------------------------------------------------------------------------O static const Pixel GREY(192, 192, 192), DARK_GREY(128, 128, 128), VERY_DARK_GREY(64, 64, 64), RED(255, 0, 0), DARK_RED(128, 0, 0), VERY_DARK_RED(64, 0, 0), YELLOW(255, 255, 0), DARK_YELLOW(128, 128, 0), VERY_DARK_YELLOW(64, 64, 0), GREEN(0, 255, 0), DARK_GREEN(0, 128, 0), VERY_DARK_GREEN(0, 64, 0), CYAN(0, 255, 255), DARK_CYAN(0, 128, 128), VERY_DARK_CYAN(0, 64, 64), BLUE(0, 0, 255), DARK_BLUE(0, 0, 128), VERY_DARK_BLUE(0, 0, 64), MAGENTA(255, 0, 255), DARK_MAGENTA(128, 0, 128), VERY_DARK_MAGENTA(64, 0, 64), WHITE(255, 255, 255), BLACK(0, 0, 0), BLANK(0, 0, 0, 0); // Thanks to scripticuk and others for updating the key maps // NOTE: The GLUT platform will need updating, open to contributions ;) enum Key { NONE, 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, K0, K1, K2, K3, K4, K5, K6, K7, K8, K9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, UP, DOWN, LEFT, RIGHT, SPACE, TAB, SHIFT, CTRL, INS, DEL, HOME, END, PGUP, PGDN, BACK, ESCAPE, RETURN, ENTER, PAUSE, SCROLL, NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9, NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL, PERIOD, EQUALS, COMMA, MINUS, OEM_1, OEM_2, OEM_3, OEM_4, OEM_5, OEM_6, OEM_7, OEM_8, CAPS_LOCK, ENUM_END }; // O------------------------------------------------------------------------------O // | olc::HWButton - Represents the state of a hardware button (mouse/key/joy) | // O------------------------------------------------------------------------------O struct HWButton { bool bPressed = false; // Set once during the frame the event occurs bool bReleased = false; // Set once during the frame the event occurs bool bHeld = false; // Set true for all frames between pressed and released events }; // O------------------------------------------------------------------------------O // | olc::vX2d - A generic 2D vector type | // O------------------------------------------------------------------------------O #if !defined(OLC_IGNORE_VEC2D) template <class T> struct v2d_generic { T x = 0; T y = 0; v2d_generic() : x(0), y(0) {} v2d_generic(T _x, T _y) : x(_x), y(_y) {} v2d_generic(const v2d_generic& v) : x(v.x), y(v.y) {} v2d_generic& operator=(const v2d_generic& v) = default; T mag() const { return T(std::sqrt(x * x + y * y)); } T mag2() const { return x * x + y * y; } v2d_generic norm() const { T r = 1 / mag(); return v2d_generic(x * r, y * r); } v2d_generic perp() const { return v2d_generic(-y, x); } v2d_generic floor() const { return v2d_generic(std::floor(x), std::floor(y)); } v2d_generic ceil() const { return v2d_generic(std::ceil(x), std::ceil(y)); } v2d_generic max(const v2d_generic& v) const { return v2d_generic(std::max(x, v.x), std::max(y, v.y)); } v2d_generic min(const v2d_generic& v) const { return v2d_generic(std::min(x, v.x), std::min(y, v.y)); } T dot(const v2d_generic& rhs) const { return this->x * rhs.x + this->y * rhs.y; } T cross(const v2d_generic& rhs) const { return this->x * rhs.y - this->y * rhs.x; } v2d_generic operator + (const v2d_generic& rhs) const { return v2d_generic(this->x + rhs.x, this->y + rhs.y); } v2d_generic operator - (const v2d_generic& rhs) const { return v2d_generic(this->x - rhs.x, this->y - rhs.y); } v2d_generic operator * (const T& rhs) const { return v2d_generic(this->x * rhs, this->y * rhs); } v2d_generic operator * (const v2d_generic& rhs) const { return v2d_generic(this->x * rhs.x, this->y * rhs.y); } v2d_generic operator / (const T& rhs) const { return v2d_generic(this->x / rhs, this->y / rhs); } v2d_generic operator / (const v2d_generic& rhs) const { return v2d_generic(this->x / rhs.x, this->y / rhs.y); } v2d_generic& operator += (const v2d_generic& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; } v2d_generic& operator -= (const v2d_generic& rhs) { this->x -= rhs.x; this->y -= rhs.y; return *this; } v2d_generic& operator *= (const T& rhs) { this->x *= rhs; this->y *= rhs; return *this; } v2d_generic& operator /= (const T& rhs) { this->x /= rhs; this->y /= rhs; return *this; } v2d_generic& operator *= (const v2d_generic& rhs) { this->x *= rhs.x; this->y *= rhs.y; return *this; } v2d_generic& operator /= (const v2d_generic& rhs) { this->x /= rhs.x; this->y /= rhs.y; return *this; } v2d_generic operator + () const { return { +x, +y }; } v2d_generic operator - () const { return { -x, -y }; } bool operator == (const v2d_generic& rhs) const { return (this->x == rhs.x && this->y == rhs.y); } bool operator != (const v2d_generic& rhs) const { return (this->x != rhs.x || this->y != rhs.y); } const std::string str() const { return std::string("(") + std::to_string(this->x) + "," + std::to_string(this->y) + ")"; } friend std::ostream& operator << (std::ostream& os, const v2d_generic& rhs) { os << rhs.str(); return os; } operator v2d_generic<int32_t>() const { return { static_cast<int32_t>(this->x), static_cast<int32_t>(this->y) }; } operator v2d_generic<float>() const { return { static_cast<float>(this->x), static_cast<float>(this->y) }; } operator v2d_generic<double>() const { return { static_cast<double>(this->x), static_cast<double>(this->y) }; } }; // Note: joshinils has some good suggestions here, but they are complicated to implement at this moment, // however they will appear in a future version of PGE template<class T> inline v2d_generic<T> operator * (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (float)rhs.x), (T)(lhs * (float)rhs.y)); } template<class T> inline v2d_generic<T> operator * (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (double)rhs.x), (T)(lhs * (double)rhs.y)); } template<class T> inline v2d_generic<T> operator * (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (int)rhs.x), (T)(lhs * (int)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (float)rhs.x), (T)(lhs / (float)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (double)rhs.x), (T)(lhs / (double)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (int)rhs.x), (T)(lhs / (int)rhs.y)); } // To stop dandistine crying... template<class T, class U> inline bool operator < (const v2d_generic<T>& lhs, const v2d_generic<U>& rhs) { return lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x); } template<class T, class U> inline bool operator > (const v2d_generic<T>& lhs, const v2d_generic<U>& rhs) { return lhs.y > rhs.y || (lhs.y == rhs.y && lhs.x > rhs.x); } typedef v2d_generic<int32_t> vi2d; typedef v2d_generic<uint32_t> vu2d; typedef v2d_generic<float> vf2d; typedef v2d_generic<double> vd2d; #endif // O------------------------------------------------------------------------------O // | olc::ResourcePack - A virtual scrambled filesystem to pack your assets into | // O------------------------------------------------------------------------------O struct ResourceBuffer : public std::streambuf { ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size); std::vector<char> vMemory; }; class ResourcePack : public std::streambuf { public: ResourcePack(); ~ResourcePack(); bool AddFile(const std::string& sFile); bool LoadPack(const std::string& sFile, const std::string& sKey); bool SavePack(const std::string& sFile, const std::string& sKey); ResourceBuffer GetFileBuffer(const std::string& sFile); bool Loaded(); private: struct sResourceFile { uint32_t nSize; uint32_t nOffset; }; std::map<std::string, sResourceFile> mapFiles; std::ifstream baseFile; std::vector<char> scramble(const std::vector<char>& data, const std::string& key); std::string makeposix(const std::string& path); }; class ImageLoader { public: ImageLoader() = default; virtual ~ImageLoader() = default; virtual olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) = 0; virtual olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) = 0; }; // O------------------------------------------------------------------------------O // | olc::Sprite - An image represented by a 2D array of olc::Pixel | // O------------------------------------------------------------------------------O class Sprite { public: Sprite(); Sprite(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); Sprite(int32_t w, int32_t h); Sprite(const olc::Sprite&) = delete; ~Sprite(); public: olc::rcode LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); olc::rcode LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); olc::rcode SaveToPGESprFile(const std::string& sImageFile); public: int32_t width = 0; int32_t height = 0; enum Mode { NORMAL, PERIODIC }; enum Flip { NONE = 0, HORIZ = 1, VERT = 2 }; public: void SetSampleMode(olc::Sprite::Mode mode = olc::Sprite::Mode::NORMAL); Pixel GetPixel(int32_t x, int32_t y) const; bool SetPixel(int32_t x, int32_t y, Pixel p); Pixel GetPixel(const olc::vi2d& a) const; bool SetPixel(const olc::vi2d& a, Pixel p); Pixel Sample(float x, float y) const; Pixel SampleBL(float u, float v) const; Pixel* GetData(); olc::Sprite* Duplicate(); olc::Sprite* Duplicate(const olc::vi2d& vPos, const olc::vi2d& vSize); std::vector<olc::Pixel> pColData; Mode modeSample = Mode::NORMAL; static std::unique_ptr<olc::ImageLoader> loader; }; // O------------------------------------------------------------------------------O // | olc::Decal - A GPU resident storage of an olc::Sprite | // O------------------------------------------------------------------------------O class Decal { public: Decal(olc::Sprite* spr, bool filter = false, bool clamp = true); Decal(const uint32_t nExistingTextureResource, olc::Sprite* spr); virtual ~Decal(); void Update(); void UpdateSprite(); public: // But dont touch int32_t id = -1; olc::Sprite* sprite = nullptr; olc::vf2d vUVScale = { 1.0f, 1.0f }; }; enum class DecalMode { NORMAL, ADDITIVE, MULTIPLICATIVE, STENCIL, ILLUMINATE, WIREFRAME, }; // O------------------------------------------------------------------------------O // | olc::Renderable - Convenience class to keep a sprite and decal together | // O------------------------------------------------------------------------------O class Renderable { public: Renderable() = default; olc::rcode Load(const std::string& sFile, ResourcePack* pack = nullptr, bool filter = false, bool clamp = true); void Create(uint32_t width, uint32_t height, bool filter = false, bool clamp = true); olc::Decal* Decal() const; olc::Sprite* Sprite() const; private: std::unique_ptr<olc::Sprite> pSprite = nullptr; std::unique_ptr<olc::Decal> pDecal = nullptr; }; // O------------------------------------------------------------------------------O // | Auxilliary components internal to engine | // O------------------------------------------------------------------------------O struct DecalInstance { olc::Decal* decal = nullptr; std::vector<olc::vf2d> pos; std::vector<olc::vf2d> uv; std::vector<float> w; std::vector<olc::Pixel> tint; olc::DecalMode mode = olc::DecalMode::NORMAL; uint32_t points = 0; }; struct LayerDesc { olc::vf2d vOffset = { 0, 0 }; olc::vf2d vScale = { 1, 1 }; bool bShow = false; bool bUpdate = false; olc::Sprite* pDrawTarget = nullptr; uint32_t nResID = 0; std::vector<DecalInstance> vecDecalInstance; olc::Pixel tint = olc::WHITE; std::function<void()> funcHook = nullptr; }; class Renderer { public: virtual ~Renderer() = default; virtual void PrepareDevice() = 0; virtual olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) = 0; virtual olc::rcode DestroyDevice() = 0; virtual void DisplayFrame() = 0; virtual void PrepareDrawing() = 0; virtual void SetDecalMode(const olc::DecalMode& mode) = 0; virtual void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) = 0; virtual void DrawDecal(const olc::DecalInstance& decal) = 0; virtual uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered = false, const bool clamp = true) = 0; virtual void UpdateTexture(uint32_t id, olc::Sprite* spr) = 0; virtual void ReadTexture(uint32_t id, olc::Sprite* spr) = 0; virtual uint32_t DeleteTexture(const uint32_t id) = 0; virtual void ApplyTexture(uint32_t id) = 0; virtual void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) = 0; virtual void ClearBuffer(olc::Pixel p, bool bDepth) = 0; static olc::PixelGameEngine* ptrPGE; }; class Platform { public: virtual ~Platform() = default; virtual olc::rcode ApplicationStartUp() = 0; virtual olc::rcode ApplicationCleanUp() = 0; virtual olc::rcode ThreadStartUp() = 0; virtual olc::rcode ThreadCleanUp() = 0; virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) = 0; virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) = 0; virtual olc::rcode SetWindowTitle(const std::string& s) = 0; virtual olc::rcode StartSystemEventLoop() = 0; virtual olc::rcode HandleSystemEvent() = 0; static olc::PixelGameEngine* ptrPGE; }; class PGEX; // The Static Twins (plus one) static std::unique_ptr<Renderer> renderer; static std::unique_ptr<Platform> platform; static std::map<size_t, uint8_t> mapKeys; // O------------------------------------------------------------------------------O // | olc::PixelGameEngine - The main BASE class for your application | // O------------------------------------------------------------------------------O class PixelGameEngine { public: PixelGameEngine(); virtual ~PixelGameEngine(); public: olc::rcode Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h, bool full_screen = false, bool vsync = false, bool cohesion = false); olc::rcode Start(); public: // User Override Interfaces // Called once on application startup, use to load your resources virtual bool OnUserCreate(); // Called every frame, and provides you with a time per frame value virtual bool OnUserUpdate(double fElapsedTime); // Called once on application termination, so you can be one clean coder virtual bool OnUserDestroy(); public: // Hardware Interfaces // Returns true if window is currently in focus bool IsFocused() const; // Get the state of a specific keyboard button HWButton GetKey(Key k) const; // Get the state of a specific mouse button HWButton GetMouse(uint32_t b) const; // Get Mouse X coordinate in "pixel" space int32_t GetMouseX() const; // Get Mouse Y coordinate in "pixel" space int32_t GetMouseY() const; // Get Mouse Wheel Delta int32_t GetMouseWheel() const; // Get the mouse in window space const olc::vi2d& GetWindowMouse() const; // Gets the mouse as a vector to keep Tarriest happy const olc::vi2d& GetMousePos() const; public: // Utility // Returns the width of the screen in "pixels" int32_t ScreenWidth() const; // Returns the height of the screen in "pixels" int32_t ScreenHeight() const; // Returns the width of the currently selected drawing target in "pixels" int32_t GetDrawTargetWidth() const; // Returns the height of the currently selected drawing target in "pixels" int32_t GetDrawTargetHeight() const; // Returns the currently active draw target olc::Sprite* GetDrawTarget() const; // Resize the primary screen sprite void SetScreenSize(int w, int h); // Specify which Sprite should be the target of drawing functions, use nullptr // to specify the primary screen void SetDrawTarget(Sprite* target); // Gets the current Frames Per Second uint32_t GetFPS() const; // Gets last update of elapsed time float GetElapsedTime() const; // Gets Actual Window size const olc::vi2d& GetWindowSize() const; // Gets pixel scale const olc::vi2d& GetPixelSize() const; // Gets actual pixel scale const olc::vi2d& GetScreenPixelSize() const; public: // CONFIGURATION ROUTINES // Layer targeting functions void SetDrawTarget(uint8_t layer); void EnableLayer(uint8_t layer, bool b); void SetLayerOffset(uint8_t layer, const olc::vf2d& offset); void SetLayerOffset(uint8_t layer, float x, float y); void SetLayerScale(uint8_t layer, const olc::vf2d& scale); void SetLayerScale(uint8_t layer, float x, float y); void SetLayerTint(uint8_t layer, const olc::Pixel& tint); void SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f); std::vector<LayerDesc>& GetLayers(); uint32_t CreateLayer(); // Change the pixel mode for different optimisations // olc::Pixel::NORMAL = No transparency // olc::Pixel::MASK = Transparent if alpha is < 255 // olc::Pixel::ALPHA = Full transparency void SetPixelMode(Pixel::Mode m); Pixel::Mode GetPixelMode(); // Use a custom blend function void SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel& pSource, const olc::Pixel& pDest)> pixelMode); // Change the blend factor from between 0.0f to 1.0f; void SetPixelBlend(float fBlend); public: // DRAWING ROUTINES // Draws a single Pixel virtual bool Draw(int32_t x, int32_t y, Pixel p = olc::WHITE); bool Draw(const olc::vi2d& pos, Pixel p = olc::WHITE); // Draws a line from (x1,y1) to (x2,y2) void DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF); void DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF); // Draws a circle located at (x,y) with radius void DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF); void DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF); // Fills a circle located at (x,y) with radius void FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE); void FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE); // Draws a rectangle at (x,y) to (x+w,y+h) void DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE); void DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE); // Fills a rectangle at (x,y) to (x+w,y+h) void FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE); void FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE); // Draws a triangle between points (x1,y1), (x2,y2) and (x3,y3) void DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE); void DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE); // Flat fills a triangle between points (x1,y1), (x2,y2) and (x3,y3) void FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE); void FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE); // Draws an entire sprite at location (x,y) void DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); void DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); // Draws an area of a sprite at location (x,y), where the // selected area is (ox,oy) to (ox+w,oy+h) void DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); void DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); // Draws a single line of text - traditional monospaced void DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); void DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); olc::vi2d GetTextSize(const std::string& s); // Draws a single line of text - non-monospaced void DrawStringProp(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); void DrawStringProp(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); olc::vi2d GetTextSizeProp(const std::string& s); // Decal Quad functions void SetDecalMode(const olc::DecalMode& mode); // Draws a whole decal, with optional scale and tinting void DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); // Draws a region of a decal, with optional scale and tinting void DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); void DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); // Draws fully user controlled 4 vertices, pos(pixels), uv(pixels), colours void DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col, uint32_t elements = 4); // Draws a decal with 4 arbitrary points, warping the texture to look "correct" void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint = olc::WHITE); void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint = olc::WHITE); void DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint = olc::WHITE); // As above, but you can specify a region of a decal source sprite void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); void DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); // Draws a decal rotated to specified angle, wit point of rotation offset void DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center = { 0.0f, 0.0f }, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); void DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f, 1.0f }, const olc::Pixel& tint = olc::WHITE); // Draws a multiline string as a decal, with tiniting and scaling void DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col = olc::WHITE, const olc::vf2d& scale = { 1.0f, 1.0f }); void DrawStringPropDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col = olc::WHITE, const olc::vf2d& scale = { 1.0f, 1.0f }); // Draws a single shaded filled rectangle as a decal void FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col = olc::WHITE); // Draws a corner shaded rectangle as a decal void GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR); // Draws an arbitrary convex textured polygon using GPU void DrawPolygonDecal(olc::Decal* decal, const std::vector<olc::vf2d>& pos, const std::vector<olc::vf2d>& uv, const olc::Pixel tint = olc::WHITE); // Clears entire draw target to Pixel void Clear(Pixel p); // Clears the rendering back buffer void ClearBuffer(Pixel p, bool bDepth = true); // Returns the font image olc::Sprite* GetFontSprite(); public: // Branding std::string sAppName; private: // Inner mysterious workings Sprite* pDrawTarget = nullptr; Pixel::Mode nPixelMode = Pixel::NORMAL; float fBlendFactor = 1.0f; olc::vi2d vScreenSize = { 256, 240 }; olc::vf2d vInvScreenSize = { 1.0f / 256.0f, 1.0f / 240.0f }; olc::vi2d vPixelSize = { 4, 4 }; olc::vi2d vScreenPixelSize = { 4, 4 }; olc::vi2d vMousePos = { 0, 0 }; int32_t nMouseWheelDelta = 0; olc::vi2d vMousePosCache = { 0, 0 }; olc::vi2d vMouseWindowPos = { 0, 0 }; int32_t nMouseWheelDeltaCache = 0; olc::vi2d vWindowSize = { 0, 0 }; olc::vi2d vViewPos = { 0, 0 }; olc::vi2d vViewSize = { 0,0 }; bool bFullScreen = false; olc::vf2d vPixel = { 1.0f, 1.0f }; bool bHasInputFocus = false; bool bHasMouseFocus = false; bool bEnableVSYNC = false; float fFrameTimer = 1.0f; float fLastElapsed = 0.0f; int nFrameCount = 0; Sprite* fontSprite = nullptr; Decal* fontDecal = nullptr; Sprite* pDefaultDrawTarget = nullptr; std::vector<LayerDesc> vLayers; uint8_t nTargetLayer = 0; uint32_t nLastFPS = 0; bool bPixelCohesion = false; DecalMode nDecalMode = DecalMode::NORMAL; std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> funcPixelMode; std::chrono::time_point<std::chrono::system_clock> m_tp1, m_tp2; std::vector<olc::vi2d> vFontSpacing; // State of keyboard bool pKeyNewState[256] = { 0 }; bool pKeyOldState[256] = { 0 }; HWButton pKeyboardState[256] = { 0 }; // State of mouse bool pMouseNewState[nMouseButtons] = { 0 }; bool pMouseOldState[nMouseButtons] = { 0 }; HWButton pMouseState[nMouseButtons] = { 0 }; // The main engine thread void EngineThread(); // If anything sets this flag to false, the engine // "should" shut down gracefully static std::atomic<bool> bAtomActive; public: // "Break In" Functions void olc_UpdateMouse(int32_t x, int32_t y); void olc_UpdateMouseWheel(int32_t delta); void olc_UpdateWindowSize(int32_t x, int32_t y); void olc_UpdateViewport(); void olc_ConstructFontSheet(); void olc_CoreUpdate(); void olc_PrepareEngine(); void olc_UpdateMouseState(int32_t button, bool state); void olc_UpdateKeyState(int32_t key, bool state); void olc_UpdateMouseFocus(bool state); void olc_UpdateKeyFocus(bool state); void olc_Terminate(); void olc_Reanimate(); bool olc_IsRunning(); // At the very end of this file, chooses which // components to compile virtual void olc_ConfigureSystem(); // NOTE: Items Here are to be deprecated, I have left them in for now // in case you are using them, but they will be removed. // olc::vf2d vSubPixelOffset = { 0.0f, 0.0f }; public: // PGEX Stuff friend class PGEX; void pgex_Register(olc::PGEX* pgex); private: std::vector<olc::PGEX*> vExtensions; }; // O------------------------------------------------------------------------------O // | PGE EXTENSION BASE CLASS - Permits access to PGE functions from extension | // O------------------------------------------------------------------------------O class PGEX { friend class olc::PixelGameEngine; public: PGEX(bool bHook = false); protected: virtual void OnBeforeUserCreate(); virtual void OnAfterUserCreate(); virtual void OnBeforeUserUpdate(double& fElapsedTime); virtual void OnAfterUserUpdate(double fElapsedTime); protected: static PixelGameEngine* pge; }; } #pragma endregion #endif // OLC_PGE_DEF // O------------------------------------------------------------------------------O // | START OF OLC_PGE_APPLICATION | // O------------------------------------------------------------------------------O #ifdef OLC_PGE_APPLICATION #undef OLC_PGE_APPLICATION // O------------------------------------------------------------------------------O // | olcPixelGameEngine INTERFACE IMPLEMENTATION (CORE) | // | Note: The core implementation is platform independent | // O------------------------------------------------------------------------------O #pragma region pge_implementation namespace olc { // O------------------------------------------------------------------------------O // | olc::Pixel IMPLEMENTATION | // O------------------------------------------------------------------------------O Pixel::Pixel() { r = 0; g = 0; b = 0; a = nDefaultAlpha; } Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { n = red | (green << 8) | (blue << 16) | (alpha << 24); } // Thanks jarekpelczar Pixel::Pixel(uint32_t p) { n = p; } bool Pixel::operator==(const Pixel& p) const { return n == p.n; } bool Pixel::operator!=(const Pixel& p) const { return n != p.n; } Pixel Pixel::operator * (const float i) const { float fR = std::min(255.0f, std::max(0.0f, float(r) * i)); float fG = std::min(255.0f, std::max(0.0f, float(g) * i)); float fB = std::min(255.0f, std::max(0.0f, float(b) * i)); return Pixel(uint8_t(fR), uint8_t(fG), uint8_t(fB), a); } Pixel Pixel::operator / (const float i) const { float fR = std::min(255.0f, std::max(0.0f, float(r) / i)); float fG = std::min(255.0f, std::max(0.0f, float(g) / i)); float fB = std::min(255.0f, std::max(0.0f, float(b) / i)); return Pixel(uint8_t(fR), uint8_t(fG), uint8_t(fB), a); } Pixel& Pixel::operator *=(const float i) { this->r = uint8_t(std::min(255.0f, std::max(0.0f, float(r) * i))); this->g = uint8_t(std::min(255.0f, std::max(0.0f, float(g) * i))); this->b = uint8_t(std::min(255.0f, std::max(0.0f, float(b) * i))); return *this; } Pixel& Pixel::operator /=(const float i) { this->r = uint8_t(std::min(255.0f, std::max(0.0f, float(r) / i))); this->g = uint8_t(std::min(255.0f, std::max(0.0f, float(g) / i))); this->b = uint8_t(std::min(255.0f, std::max(0.0f, float(b) / i))); return *this; } Pixel Pixel::operator + (const Pixel& p) const { uint8_t nR = uint8_t(std::min(255, std::max(0, int(r) + int(p.r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, int(g) + int(p.g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, int(b) + int(p.b)))); return Pixel(nR, nG, nB, a); } Pixel Pixel::operator - (const Pixel& p) const { uint8_t nR = uint8_t(std::min(255, std::max(0, int(r) - int(p.r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, int(g) - int(p.g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, int(b) - int(p.b)))); return Pixel(nR, nG, nB, a); } Pixel& Pixel::operator += (const Pixel& p) { this->r = uint8_t(std::min(255, std::max(0, int(r) + int(p.r)))); this->g = uint8_t(std::min(255, std::max(0, int(g) + int(p.g)))); this->b = uint8_t(std::min(255, std::max(0, int(b) + int(p.b)))); return *this; } Pixel& Pixel::operator -= (const Pixel& p) // Thanks Au Lit { this->r = uint8_t(std::min(255, std::max(0, int(r) - int(p.r)))); this->g = uint8_t(std::min(255, std::max(0, int(g) - int(p.g)))); this->b = uint8_t(std::min(255, std::max(0, int(b) - int(p.b)))); return *this; } Pixel Pixel::inv() const { uint8_t nR = uint8_t(std::min(255, std::max(0, 255 - int(r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, 255 - int(g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, 255 - int(b)))); return Pixel(nR, nG, nB, a); } Pixel PixelF(float red, float green, float blue, float alpha) { return Pixel(uint8_t(red * 255.0f), uint8_t(green * 255.0f), uint8_t(blue * 255.0f), uint8_t(alpha * 255.0f)); } Pixel PixelLerp(const olc::Pixel& p1, const olc::Pixel& p2, float t) { return (p2 * t) + p1 * (1.0f - t); } // O------------------------------------------------------------------------------O // | olc::Sprite IMPLEMENTATION | // O------------------------------------------------------------------------------O Sprite::Sprite() { width = 0; height = 0; } Sprite::Sprite(const std::string& sImageFile, olc::ResourcePack* pack) { LoadFromFile(sImageFile, pack); } Sprite::Sprite(int32_t w, int32_t h) { width = w; height = h; pColData.resize(width * height); pColData.resize(width * height, nDefaultPixel); } Sprite::~Sprite() { pColData.clear(); } // To Be Deprecated //olc::rcode Sprite::LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack) //{ // if (pColData) delete[] pColData; // auto ReadData = [&](std::istream& is) // { // is.read((char*)&width, sizeof(int32_t)); // is.read((char*)&height, sizeof(int32_t)); // pColData = new Pixel[width * height]; // is.read((char*)pColData, (size_t)width * (size_t)height * sizeof(uint32_t)); // }; // // These are essentially Memory Surfaces represented by olc::Sprite // // which load very fast, but are completely uncompressed // if (pack == nullptr) // { // std::ifstream ifs; // ifs.open(sImageFile, std::ifstream::binary); // if (ifs.is_open()) // { // ReadData(ifs); // return olc::OK; // } // else // return olc::FAIL; // } // else // { // ResourceBuffer rb = pack->GetFileBuffer(sImageFile); // std::istream is(&rb); // ReadData(is); // return olc::OK; // } // return olc::FAIL; //} //olc::rcode Sprite::SaveToPGESprFile(const std::string& sImageFile) //{ // if (pColData == nullptr) return olc::FAIL; // std::ofstream ofs; // ofs.open(sImageFile, std::ifstream::binary); // if (ofs.is_open()) // { // ofs.write((char*)&width, sizeof(int32_t)); // ofs.write((char*)&height, sizeof(int32_t)); // ofs.write((char*)pColData, std::streamsize(width) * std::streamsize(height) * sizeof(uint32_t)); // ofs.close(); // return olc::OK; // } // return olc::FAIL; //} void Sprite::SetSampleMode(olc::Sprite::Mode mode) { modeSample = mode; } Pixel Sprite::GetPixel(const olc::vi2d& a) const { return GetPixel(a.x, a.y); } bool Sprite::SetPixel(const olc::vi2d& a, Pixel p) { return SetPixel(a.x, a.y, p); } Pixel Sprite::GetPixel(int32_t x, int32_t y) const { if (modeSample == olc::Sprite::Mode::NORMAL) { if (x >= 0 && x < width && y >= 0 && y < height) return pColData[y * width + x]; else return Pixel(0, 0, 0, 0); } else { return pColData[abs(y % height) * width + abs(x % width)]; } } bool Sprite::SetPixel(int32_t x, int32_t y, Pixel p) { if (x >= 0 && x < width && y >= 0 && y < height) { pColData[y * width + x] = p; return true; } else return false; } Pixel Sprite::Sample(float x, float y) const { int32_t sx = std::min((int32_t)((x * (float)width)), width - 1); int32_t sy = std::min((int32_t)((y * (float)height)), height - 1); return GetPixel(sx, sy); } Pixel Sprite::SampleBL(float u, float v) const { u = u * width - 0.5f; v = v * height - 0.5f; int x = (int)floor(u); // cast to int rounds toward zero, not downward int y = (int)floor(v); // Thanks @joshinils float u_ratio = u - x; float v_ratio = v - y; float u_opposite = 1 - u_ratio; float v_opposite = 1 - v_ratio; olc::Pixel p1 = GetPixel(std::max(x, 0), std::max(y, 0)); olc::Pixel p2 = GetPixel(std::min(x + 1, (int)width - 1), std::max(y, 0)); olc::Pixel p3 = GetPixel(std::max(x, 0), std::min(y + 1, (int)height - 1)); olc::Pixel p4 = GetPixel(std::min(x + 1, (int)width - 1), std::min(y + 1, (int)height - 1)); return olc::Pixel( (uint8_t)((p1.r * u_opposite + p2.r * u_ratio) * v_opposite + (p3.r * u_opposite + p4.r * u_ratio) * v_ratio), (uint8_t)((p1.g * u_opposite + p2.g * u_ratio) * v_opposite + (p3.g * u_opposite + p4.g * u_ratio) * v_ratio), (uint8_t)((p1.b * u_opposite + p2.b * u_ratio) * v_opposite + (p3.b * u_opposite + p4.b * u_ratio) * v_ratio)); } Pixel* Sprite::GetData() { return pColData.data(); } olc::rcode Sprite::LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack) { UNUSED(pack); return loader->LoadImageResource(this, sImageFile, pack); } olc::Sprite* Sprite::Duplicate() { olc::Sprite* spr = new olc::Sprite(width, height); std::memcpy(spr->GetData(), GetData(), width * height * sizeof(olc::Pixel)); spr->modeSample = modeSample; return spr; } olc::Sprite* Sprite::Duplicate(const olc::vi2d& vPos, const olc::vi2d& vSize) { olc::Sprite* spr = new olc::Sprite(vSize.x, vSize.y); for (int y = 0; y < vSize.y; y++) for (int x = 0; x < vSize.x; x++) spr->SetPixel(x, y, GetPixel(vPos.x + x, vPos.y + y)); return spr; } // O------------------------------------------------------------------------------O // | olc::Decal IMPLEMENTATION | // O------------------------------------------------------------------------------O Decal::Decal(olc::Sprite* spr, bool filter, bool clamp) { id = -1; if (spr == nullptr) return; sprite = spr; id = renderer->CreateTexture(sprite->width, sprite->height, filter, clamp); Update(); } Decal::Decal(const uint32_t nExistingTextureResource, olc::Sprite* spr) { if (spr == nullptr) return; id = nExistingTextureResource; } void Decal::Update() { if (sprite == nullptr) return; vUVScale = { 1.0f / float(sprite->width), 1.0f / float(sprite->height) }; renderer->ApplyTexture(id); renderer->UpdateTexture(id, sprite); } void Decal::UpdateSprite() { if (sprite == nullptr) return; renderer->ApplyTexture(id); renderer->ReadTexture(id, sprite); } Decal::~Decal() { if (id != -1) { renderer->DeleteTexture(id); id = -1; } } void Renderable::Create(uint32_t width, uint32_t height, bool filter, bool clamp) { pSprite = std::make_unique<olc::Sprite>(width, height); pDecal = std::make_unique<olc::Decal>(pSprite.get(), filter, clamp); } olc::rcode Renderable::Load(const std::string& sFile, ResourcePack* pack, bool filter, bool clamp) { pSprite = std::make_unique<olc::Sprite>(); if (pSprite->LoadFromFile(sFile, pack) == olc::rcode::OK) { pDecal = std::make_unique<olc::Decal>(pSprite.get(), filter, clamp); return olc::rcode::OK; } else { pSprite.release(); pSprite = nullptr; return olc::rcode::NO_FILE; } } olc::Decal* Renderable::Decal() const { return pDecal.get(); } olc::Sprite* Renderable::Sprite() const { return pSprite.get(); } // O------------------------------------------------------------------------------O // | olc::ResourcePack IMPLEMENTATION | // O------------------------------------------------------------------------------O //============================================================= // Resource Packs - Allows you to store files in one large // scrambled file - Thanks MaGetzUb for debugging a null char in std::stringstream bug ResourceBuffer::ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size) { vMemory.resize(size); ifs.seekg(offset); ifs.read(vMemory.data(), vMemory.size()); setg(vMemory.data(), vMemory.data(), vMemory.data() + size); } ResourcePack::ResourcePack() { } ResourcePack::~ResourcePack() { baseFile.close(); } bool ResourcePack::AddFile(const std::string& sFile) { const std::string file = makeposix(sFile); if (_gfs::exists(file)) { sResourceFile e; e.nSize = (uint32_t)_gfs::file_size(file); e.nOffset = 0; // Unknown at this stage mapFiles[file] = e; return true; } return false; } bool ResourcePack::LoadPack(const std::string& sFile, const std::string& sKey) { // Open the resource file baseFile.open(sFile, std::ifstream::binary); if (!baseFile.is_open()) return false; // 1) Read Scrambled index uint32_t nIndexSize = 0; baseFile.read((char*)&nIndexSize, sizeof(uint32_t)); std::vector<char> buffer(nIndexSize); for (uint32_t j = 0; j < nIndexSize; j++) buffer[j] = baseFile.get(); std::vector<char> decoded = scramble(buffer, sKey); size_t pos = 0; auto read = [&decoded, &pos](char* dst, size_t size) { memcpy((void*)dst, (const void*)(decoded.data() + pos), size); pos += size; }; auto get = [&read]() -> int { char c; read(&c, 1); return c; }; // 2) Read Map uint32_t nMapEntries = 0; read((char*)&nMapEntries, sizeof(uint32_t)); for (uint32_t i = 0; i < nMapEntries; i++) { uint32_t nFilePathSize = 0; read((char*)&nFilePathSize, sizeof(uint32_t)); std::string sFileName(nFilePathSize, ' '); for (uint32_t j = 0; j < nFilePathSize; j++) sFileName[j] = get(); sResourceFile e; read((char*)&e.nSize, sizeof(uint32_t)); read((char*)&e.nOffset, sizeof(uint32_t)); mapFiles[sFileName] = e; } // Don't close base file! we will provide a stream // pointer when the file is requested return true; } bool ResourcePack::SavePack(const std::string& sFile, const std::string& sKey) { // Create/Overwrite the resource file std::ofstream ofs(sFile, std::ofstream::binary); if (!ofs.is_open()) return false; // Iterate through map uint32_t nIndexSize = 0; // Unknown for now ofs.write((char*)&nIndexSize, sizeof(uint32_t)); uint32_t nMapSize = uint32_t(mapFiles.size()); ofs.write((char*)&nMapSize, sizeof(uint32_t)); for (auto& e : mapFiles) { // Write the path of the file size_t nPathSize = e.first.size(); ofs.write((char*)&nPathSize, sizeof(uint32_t)); ofs.write(e.first.c_str(), nPathSize); // Write the file entry properties ofs.write((char*)&e.second.nSize, sizeof(uint32_t)); ofs.write((char*)&e.second.nOffset, sizeof(uint32_t)); } // 2) Write the individual Data std::streampos offset = ofs.tellp(); nIndexSize = (uint32_t)offset; for (auto& e : mapFiles) { // Store beginning of file offset within resource pack file e.second.nOffset = (uint32_t)offset; // Load the file to be added std::vector<uint8_t> vBuffer(e.second.nSize); std::ifstream i(e.first, std::ifstream::binary); i.read((char*)vBuffer.data(), e.second.nSize); i.close(); // Write the loaded file into resource pack file ofs.write((char*)vBuffer.data(), e.second.nSize); offset += e.second.nSize; } // 3) Scramble Index std::vector<char> stream; auto write = [&stream](const char* data, size_t size) { size_t sizeNow = stream.size(); stream.resize(sizeNow + size); memcpy(stream.data() + sizeNow, data, size); }; // Iterate through map write((char*)&nMapSize, sizeof(uint32_t)); for (auto& e : mapFiles) { // Write the path of the file size_t nPathSize = e.first.size(); write((char*)&nPathSize, sizeof(uint32_t)); write(e.first.c_str(), nPathSize); // Write the file entry properties write((char*)&e.second.nSize, sizeof(uint32_t)); write((char*)&e.second.nOffset, sizeof(uint32_t)); } std::vector<char> sIndexString = scramble(stream, sKey); uint32_t nIndexStringLen = uint32_t(sIndexString.size()); // 4) Rewrite Map (it has been updated with offsets now) // at start of file ofs.seekp(0, std::ios::beg); ofs.write((char*)&nIndexStringLen, sizeof(uint32_t)); ofs.write(sIndexString.data(), nIndexStringLen); ofs.close(); return true; } ResourceBuffer ResourcePack::GetFileBuffer(const std::string& sFile) { return ResourceBuffer(baseFile, mapFiles[sFile].nOffset, mapFiles[sFile].nSize); } bool ResourcePack::Loaded() { return baseFile.is_open(); } std::vector<char> ResourcePack::scramble(const std::vector<char>& data, const std::string& key) { if (key.empty()) return data; std::vector<char> o; size_t c = 0; for (auto s : data) o.push_back(s ^ key[(c++) % key.size()]); return o; }; std::string ResourcePack::makeposix(const std::string& path) { std::string o; for (auto s : path) o += std::string(1, s == '\\' ? '/' : s); return o; }; // O------------------------------------------------------------------------------O // | olc::PixelGameEngine IMPLEMENTATION | // O------------------------------------------------------------------------------O PixelGameEngine::PixelGameEngine() { sAppName = "Undefined"; olc::PGEX::pge = this; // Bring in relevant Platform & Rendering systems depending // on compiler parameters olc_ConfigureSystem(); } PixelGameEngine::~PixelGameEngine() {} olc::rcode PixelGameEngine::Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h, bool full_screen, bool vsync, bool cohesion) { bPixelCohesion = cohesion; vScreenSize = { screen_w, screen_h }; vInvScreenSize = { 1.0f / float(screen_w), 1.0f / float(screen_h) }; vPixelSize = { pixel_w, pixel_h }; vWindowSize = vScreenSize * vPixelSize; bFullScreen = full_screen; bEnableVSYNC = vsync; vPixel = 2.0f / vScreenSize; if (vPixelSize.x <= 0 || vPixelSize.y <= 0 || vScreenSize.x <= 0 || vScreenSize.y <= 0) return olc::FAIL; return olc::OK; } void PixelGameEngine::SetScreenSize(int w, int h) { vScreenSize = { w, h }; vInvScreenSize = { 1.0f / float(w), 1.0f / float(h) }; for (auto& layer : vLayers) { delete layer.pDrawTarget; // Erase existing layer sprites layer.pDrawTarget = new Sprite(vScreenSize.x, vScreenSize.y); layer.bUpdate = true; } SetDrawTarget(nullptr); renderer->ClearBuffer(olc::BLACK, true); renderer->DisplayFrame(); renderer->ClearBuffer(olc::BLACK, true); renderer->UpdateViewport(vViewPos, vViewSize); } #if !defined(PGE_USE_CUSTOM_START) olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); // Start the thread bAtomActive = true; std::thread t = std::thread(&PixelGameEngine::EngineThread, this); // Some implementations may form an event loop here platform->StartSystemEventLoop(); // Wait for thread to be exited t.join(); if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } #endif void PixelGameEngine::SetDrawTarget(Sprite* target) { if (target) { pDrawTarget = target; } else { nTargetLayer = 0; pDrawTarget = vLayers[0].pDrawTarget; } } void PixelGameEngine::SetDrawTarget(uint8_t layer) { if (layer < vLayers.size()) { pDrawTarget = vLayers[layer].pDrawTarget; vLayers[layer].bUpdate = true; nTargetLayer = layer; } } void PixelGameEngine::EnableLayer(uint8_t layer, bool b) { if (layer < vLayers.size()) vLayers[layer].bShow = b; } void PixelGameEngine::SetLayerOffset(uint8_t layer, const olc::vf2d& offset) { SetLayerOffset(layer, offset.x, offset.y); } void PixelGameEngine::SetLayerOffset(uint8_t layer, float x, float y) { if (layer < vLayers.size()) vLayers[layer].vOffset = { x, y }; } void PixelGameEngine::SetLayerScale(uint8_t layer, const olc::vf2d& scale) { SetLayerScale(layer, scale.x, scale.y); } void PixelGameEngine::SetLayerScale(uint8_t layer, float x, float y) { if (layer < vLayers.size()) vLayers[layer].vScale = { x, y }; } void PixelGameEngine::SetLayerTint(uint8_t layer, const olc::Pixel& tint) { if (layer < vLayers.size()) vLayers[layer].tint = tint; } void PixelGameEngine::SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f) { if (layer < vLayers.size()) vLayers[layer].funcHook = f; } std::vector<LayerDesc>& PixelGameEngine::GetLayers() { return vLayers; } uint32_t PixelGameEngine::CreateLayer() { LayerDesc ld; ld.pDrawTarget = new olc::Sprite(vScreenSize.x, vScreenSize.y); ld.nResID = renderer->CreateTexture(vScreenSize.x, vScreenSize.y); renderer->UpdateTexture(ld.nResID, ld.pDrawTarget); vLayers.push_back(ld); return uint32_t(vLayers.size()) - 1; } Sprite* PixelGameEngine::GetDrawTarget() const { return pDrawTarget; } int32_t PixelGameEngine::GetDrawTargetWidth() const { if (pDrawTarget) return pDrawTarget->width; else return 0; } int32_t PixelGameEngine::GetDrawTargetHeight() const { if (pDrawTarget) return pDrawTarget->height; else return 0; } uint32_t PixelGameEngine::GetFPS() const { return nLastFPS; } bool PixelGameEngine::IsFocused() const { return bHasInputFocus; } HWButton PixelGameEngine::GetKey(Key k) const { return pKeyboardState[k]; } HWButton PixelGameEngine::GetMouse(uint32_t b) const { return pMouseState[b]; } int32_t PixelGameEngine::GetMouseX() const { return vMousePos.x; } int32_t PixelGameEngine::GetMouseY() const { return vMousePos.y; } const olc::vi2d& PixelGameEngine::GetMousePos() const { return vMousePos; } int32_t PixelGameEngine::GetMouseWheel() const { return nMouseWheelDelta; } int32_t PixelGameEngine::ScreenWidth() const { return vScreenSize.x; } int32_t PixelGameEngine::ScreenHeight() const { return vScreenSize.y; } float PixelGameEngine::GetElapsedTime() const { return fLastElapsed; } const olc::vi2d& PixelGameEngine::GetWindowSize() const { return vWindowSize; } const olc::vi2d& PixelGameEngine::GetPixelSize() const { return vPixelSize; } const olc::vi2d& PixelGameEngine::GetScreenPixelSize() const { return vScreenPixelSize; } const olc::vi2d& PixelGameEngine::GetWindowMouse() const { return vMouseWindowPos; } bool PixelGameEngine::Draw(const olc::vi2d& pos, Pixel p) { return Draw(pos.x, pos.y, p); } // This is it, the critical function that plots a pixel bool PixelGameEngine::Draw(int32_t x, int32_t y, Pixel p) { if (!pDrawTarget) return false; if (nPixelMode == Pixel::NORMAL) { return pDrawTarget->SetPixel(x, y, p); } if (nPixelMode == Pixel::MASK) { if (p.a == 255) return pDrawTarget->SetPixel(x, y, p); } if (nPixelMode == Pixel::ALPHA) { Pixel d = pDrawTarget->GetPixel(x, y); float a = (float)(p.a / 255.0f) * fBlendFactor; float c = 1.0f - a; float r = a * (float)p.r + c * (float)d.r; float g = a * (float)p.g + c * (float)d.g; float b = a * (float)p.b + c * (float)d.b; return pDrawTarget->SetPixel(x, y, Pixel((uint8_t)r, (uint8_t)g, (uint8_t)b/*, (uint8_t)(p.a * fBlendFactor)*/)); } if (nPixelMode == Pixel::CUSTOM) { return pDrawTarget->SetPixel(x, y, funcPixelMode(x, y, p, pDrawTarget->GetPixel(x, y))); } return false; } void PixelGameEngine::DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p, uint32_t pattern) { DrawLine(pos1.x, pos1.y, pos2.x, pos2.y, p, pattern); } void PixelGameEngine::DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p, uint32_t pattern) { int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; auto rol = [&](void) { pattern = (pattern << 1) | (pattern >> 31); return pattern & 1; }; // straight lines idea by gurkanctn if (dx == 0) // Line is vertical { if (y2 < y1) std::swap(y1, y2); for (y = y1; y <= y2; y++) if (rol()) Draw(x1, y, p); return; } if (dy == 0) // Line is horizontal { if (x2 < x1) std::swap(x1, x2); for (x = x1; x <= x2; x++) if (rol()) Draw(x, y1, p); return; } // Line is Funk-aye dx1 = abs(dx); dy1 = abs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } if (rol()) Draw(x, y, p); for (i = 0; x < xe; i++) { x = x + 1; if (px < 0) px = px + 2 * dy1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) y = y + 1; else y = y - 1; px = px + 2 * (dy1 - dx1); } if (rol()) Draw(x, y, p); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } if (rol()) Draw(x, y, p); for (i = 0; y < ye; i++) { y = y + 1; if (py <= 0) py = py + 2 * dx1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) x = x + 1; else x = x - 1; py = py + 2 * (dx1 - dy1); } if (rol()) Draw(x, y, p); } } } void PixelGameEngine::DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p, uint8_t mask) { DrawCircle(pos.x, pos.y, radius, p, mask); } void PixelGameEngine::DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p, uint8_t mask) { // Thanks to IanM-Matrix1 #PR121 if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius) return; if (radius > 0) { int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; while (y0 >= x0) // only formulate 1/8 of circle { // Draw even octants if (mask & 0x01) Draw(x + x0, y - y0, p);// Q6 - upper right right if (mask & 0x04) Draw(x + y0, y + x0, p);// Q4 - lower lower right if (mask & 0x10) Draw(x - x0, y + y0, p);// Q2 - lower left left if (mask & 0x40) Draw(x - y0, y - x0, p);// Q0 - upper upper left if (x0 != 0 && x0 != y0) { if (mask & 0x02) Draw(x + y0, y - x0, p);// Q7 - upper upper right if (mask & 0x08) Draw(x + x0, y + y0, p);// Q5 - lower right right if (mask & 0x20) Draw(x - y0, y + x0, p);// Q3 - lower lower left if (mask & 0x80) Draw(x - x0, y - y0, p);// Q1 - upper left left } if (d < 0) d += 4 * x0++ + 6; else d += 4 * (x0++ - y0--) + 10; } } else Draw(x, y, p); } void PixelGameEngine::FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p) { FillCircle(pos.x, pos.y, radius, p); } void PixelGameEngine::FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p) { // Thanks to IanM-Matrix1 #PR121 if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius) return; if (radius > 0) { int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; auto drawline = [&](int sx, int ex, int y) { for (int x = sx; x <= ex; x++) Draw(x, y, p); }; while (y0 >= x0) { drawline(x - y0, x + y0, y - x0); if (x0 > 0) drawline(x - y0, x + y0, y + x0); if (d < 0) d += 4 * x0++ + 6; else { if (x0 != y0) { drawline(x - x0, x + x0, y - y0); drawline(x - x0, x + x0, y + y0); } d += 4 * (x0++ - y0--) + 10; } } } else Draw(x, y, p); } void PixelGameEngine::DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p) { DrawRect(pos.x, pos.y, size.x, size.y, p); } void PixelGameEngine::DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { DrawLine(x, y, x + w, y, p); DrawLine(x + w, y, x + w, y + h, p); DrawLine(x + w, y + h, x, y + h, p); DrawLine(x, y + h, x, y, p); } void PixelGameEngine::Clear(Pixel p) { int pixels = GetDrawTargetWidth() * GetDrawTargetHeight(); Pixel* m = GetDrawTarget()->GetData(); for (int i = 0; i < pixels; i++) m[i] = p; } void PixelGameEngine::ClearBuffer(Pixel p, bool bDepth) { renderer->ClearBuffer(p, bDepth); } olc::Sprite* PixelGameEngine::GetFontSprite() { return fontSprite; } void PixelGameEngine::FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p) { FillRect(pos.x, pos.y, size.x, size.y, p); } void PixelGameEngine::FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { int32_t x2 = x + w; int32_t y2 = y + h; if (x < 0) x = 0; if (x >= (int32_t)GetDrawTargetWidth()) x = (int32_t)GetDrawTargetWidth(); if (y < 0) y = 0; if (y >= (int32_t)GetDrawTargetHeight()) y = (int32_t)GetDrawTargetHeight(); if (x2 < 0) x2 = 0; if (x2 >= (int32_t)GetDrawTargetWidth()) x2 = (int32_t)GetDrawTargetWidth(); if (y2 < 0) y2 = 0; if (y2 >= (int32_t)GetDrawTargetHeight()) y2 = (int32_t)GetDrawTargetHeight(); for (int i = x; i < x2; i++) for (int j = y; j < y2; j++) Draw(i, j, p); } void PixelGameEngine::DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p) { DrawTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p); } void PixelGameEngine::DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { DrawLine(x1, y1, x2, y2, p); DrawLine(x2, y2, x3, y3, p); DrawLine(x3, y3, x1, y1, p); } void PixelGameEngine::FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p) { FillTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p); } // https://www.avrfreaks.net/sites/default/files/triangles.c void PixelGameEngine::FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); }; int t1x, t2x, y, minx, maxx, t1xp, t2xp; bool changed1 = false; bool changed2 = false; int signx1, signx2, dx1, dy1, dx2, dy2; int e1, e2; // Sort vertices if (y1 > y2) { std::swap(y1, y2); std::swap(x1, x2); } if (y1 > y3) { std::swap(y1, y3); std::swap(x1, x3); } if (y2 > y3) { std::swap(y2, y3); std::swap(x2, x3); } t1x = t2x = x1; y = y1; // Starting points dx1 = (int)(x2 - x1); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y2 - y1); dx2 = (int)(x3 - x1); if (dx2 < 0) { dx2 = -dx2; signx2 = -1; } else signx2 = 1; dy2 = (int)(y3 - y1); if (dy1 > dx1) { std::swap(dx1, dy1); changed1 = true; } if (dy2 > dx2) { std::swap(dy2, dx2); changed2 = true; } e2 = (int)(dx2 >> 1); // Flat top, just process the second half if (y1 == y2) goto next; e1 = (int)(dx1 >> 1); for (int i = 0; i < dx1;) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { i++; e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) t1xp = signx1;//t1x += signx1; else goto next1; } if (changed1) break; else t1x += signx1; } // Move line next1: // process second line until y value is about to change while (1) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2;//t2x += signx2; else goto next2; } if (changed2) break; else t2x += signx2; } next2: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); // Draw line from min to max points found on the y // Now increase y if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y == y2) break; } next: // Second half dx1 = (int)(x3 - x2); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y3 - y2); t1x = x2; if (dy1 > dx1) { // swap values std::swap(dy1, dx1); changed1 = true; } else changed1 = false; e1 = (int)(dx1 >> 1); for (int i = 0; i <= dx1; i++) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) { t1xp = signx1; break; }//t1x += signx1; else goto next3; } if (changed1) break; else t1x += signx1; if (i < dx1) i++; } next3: // process second line until y value is about to change while (t2x != x3) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2; else goto next4; } if (changed2) break; else t2x += signx2; } next4: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y > y3) return; } } void PixelGameEngine::DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale, uint8_t flip) { DrawSprite(pos.x, pos.y, sprite, scale, flip); } void PixelGameEngine::DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale, uint8_t flip) { if (sprite == nullptr) return; int32_t fxs = 0, fxm = 1, fx = 0; int32_t fys = 0, fym = 1, fy = 0; if (flip & olc::Sprite::Flip::HORIZ) { fxs = sprite->width - 1; fxm = -1; } if (flip & olc::Sprite::Flip::VERT) { fys = sprite->height - 1; fym = -1; } if (scale > 1) { fx = fxs; for (int32_t i = 0; i < sprite->width; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < sprite->height; j++, fy += fym) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx, fy)); } } else { fx = fxs; for (int32_t i = 0; i < sprite->width; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < sprite->height; j++, fy += fym) Draw(x + i, y + j, sprite->GetPixel(fx, fy)); } } } void PixelGameEngine::DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale, uint8_t flip) { DrawPartialSprite(pos.x, pos.y, sprite, sourcepos.x, sourcepos.y, size.x, size.y, scale, flip); } void PixelGameEngine::DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale, uint8_t flip) { if (sprite == nullptr) return; int32_t fxs = 0, fxm = 1, fx = 0; int32_t fys = 0, fym = 1, fy = 0; if (flip & olc::Sprite::Flip::HORIZ) { fxs = w - 1; fxm = -1; } if (flip & olc::Sprite::Flip::VERT) { fys = h - 1; fym = -1; } if (scale > 1) { fx = fxs; for (int32_t i = 0; i < w; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < h; j++, fy += fym) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx + ox, fy + oy)); } } else { fx = fxs; for (int32_t i = 0; i < w; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < h; j++, fy += fym) Draw(x + i, y + j, sprite->GetPixel(fx + ox, fy + oy)); } } } void PixelGameEngine::SetDecalMode(const olc::DecalMode& mode) { nDecalMode = mode; } void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * source_size.x * vInvScreenSize.x) * scale.x, vScreenSpacePos.y - (2.0f * source_size.y * vInvScreenSize.y) * scale.y }; DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.w = { 1,1,1,1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * size.x * vInvScreenSize.x), vScreenSpacePos.y - (2.0f * size.y * vInvScreenSize.y) }; DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; olc::vf2d uvtl = (source_pos)*decal->vUVScale; olc::vf2d uvbr = uvtl + ((source_size)*decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.w = { 1,1,1,1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * (float(decal->sprite->width) * vInvScreenSize.x)) * scale.x, vScreenSpacePos.y - (2.0f * (float(decal->sprite->height) * vInvScreenSize.y)) * scale.y }; DecalInstance di; di.decal = decal; di.points = 4; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; di.w = { 1, 1, 1, 1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col, uint32_t elements) { DecalInstance di; di.decal = decal; di.pos.resize(elements); di.uv.resize(elements); di.w.resize(elements); di.tint.resize(elements); di.points = elements; for (uint32_t i = 0; i < elements; i++) { di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; di.uv[i] = uv[i]; di.tint[i] = col[i]; di.w[i] = 1.0f; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPolygonDecal(olc::Decal* decal, const std::vector<olc::vf2d>& pos, const std::vector<olc::vf2d>& uv, const olc::Pixel tint) { DecalInstance di; di.decal = decal; di.points = uint32_t(pos.size()); di.pos.resize(di.points); di.uv.resize(di.points); di.w.resize(di.points); di.tint.resize(di.points); for (uint32_t i = 0; i < di.points; i++) { di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; di.uv[i] = uv[i]; di.tint[i] = tint; di.w[i] = 1.0f; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col) { std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } }; std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} }; std::array<olc::Pixel, 4> cols = { {col, col, col, col} }; DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data(), 4); } void PixelGameEngine::GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR) { std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } }; std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} }; std::array<olc::Pixel, 4> cols = { {colTL, colBL, colBR, colTR} }; DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data(), 4); } void PixelGameEngine::DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& scale, const olc::Pixel& tint) { DecalInstance di; di.decal = decal; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; di.w = { 1, 1, 1, 1 }; di.tint = { tint, tint, tint, tint }; di.points = 4; di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale; di.pos[1] = (olc::vf2d(0.0f, float(decal->sprite->height)) - center) * scale; di.pos[2] = (olc::vf2d(float(decal->sprite->width), float(decal->sprite->height)) - center) * scale; di.pos[3] = (olc::vf2d(float(decal->sprite->width), 0.0f) - center) * scale; float c = cos(fAngle), s = sin(fAngle); for (int i = 0; i < 4; i++) { di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c); di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f); di.pos[i].y *= -1.0f; di.w[i] = 1; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint) { DecalInstance di; di.decal = decal; di.points = 4; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale; di.pos[1] = (olc::vf2d(0.0f, source_size.y) - center) * scale; di.pos[2] = (olc::vf2d(source_size.x, source_size.y) - center) * scale; di.pos[3] = (olc::vf2d(source_size.x, 0.0f) - center) * scale; float c = cos(fAngle), s = sin(fAngle); for (int i = 0; i < 4; i++) { di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c); di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f); di.pos[i].y *= -1.0f; } olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; olc::vf2d center; float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y)); if (rd != 0) { olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; rd = 1.0f / rd; float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd; float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd; if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]); float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag(); for (int i = 0; i < 4; i++) { float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3]; di.uv[i] *= q; di.w[i] *= q; di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint) { // Thanks Nathan Reed, a brilliant article explaining whats going on here // http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/ DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; olc::vf2d center; float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y)); if (rd != 0) { rd = 1.0f / rd; float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd; float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd; if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]); float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag(); for (int i = 0; i < 4; i++) { float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3]; di.uv[i] *= q; di.w[i] *= q; di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint) { DrawWarpedDecal(decal, pos.data(), tint); } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint) { DrawWarpedDecal(decal, &pos[0], tint); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DrawPartialWarpedDecal(decal, pos.data(), source_pos, source_size, tint); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DrawPartialWarpedDecal(decal, &pos[0], source_pos, source_size, tint); } void PixelGameEngine::DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col, const olc::vf2d& scale) { olc::vf2d spos = { 0.0f, 0.0f }; for (auto c : sText) { if (c == '\n') { spos.x = 0; spos.y += 8.0f * scale.y; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; DrawPartialDecal(pos + spos, fontDecal, { float(ox) * 8.0f, float(oy) * 8.0f }, { 8.0f, 8.0f }, scale, col); spos.x += 8.0f * scale.x; } } } void PixelGameEngine::DrawStringPropDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col, const olc::vf2d& scale) { olc::vf2d spos = { 0.0f, 0.0f }; for (auto c : sText) { if (c == '\n') { spos.x = 0; spos.y += 8.0f * scale.y; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; DrawPartialDecal(pos + spos, fontDecal, { float(ox) * 8.0f + float(vFontSpacing[c - 32].x), float(oy) * 8.0f }, { float(vFontSpacing[c - 32].y), 8.0f }, scale, col); spos.x += float(vFontSpacing[c - 32].y) * scale.x; } } } olc::vi2d PixelGameEngine::GetTextSize(const std::string& s) { olc::vi2d size = { 0,1 }; olc::vi2d pos = { 0,1 }; for (auto c : s) { if (c == '\n') { pos.y++; pos.x = 0; } else pos.x++; size.x = std::max(size.x, pos.x); size.y = std::max(size.y, pos.y); } return size * 8; } void PixelGameEngine::DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col, uint32_t scale) { DrawString(pos.x, pos.y, sText, col, scale); } void PixelGameEngine::DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col, uint32_t scale) { int32_t sx = 0; int32_t sy = 0; Pixel::Mode m = nPixelMode; // Thanks @tucna, spotted bug with col.ALPHA :P if (m != Pixel::CUSTOM) // Thanks @Megarev, required for "shaders" { if (col.a != 255) SetPixelMode(Pixel::ALPHA); else SetPixelMode(Pixel::MASK); } for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col); } else { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) Draw(x + sx + i, y + sy + j, col); } sx += 8 * scale; } } SetPixelMode(m); } olc::vi2d PixelGameEngine::GetTextSizeProp(const std::string& s) { olc::vi2d size = { 0,1 }; olc::vi2d pos = { 0,1 }; for (auto c : s) { if (c == '\n') { pos.y += 1; pos.x = 0; } else pos.x += vFontSpacing[c - 32].y; size.x = std::max(size.x, pos.x); size.y = std::max(size.y, pos.y); } size.y *= 8; return size; } void PixelGameEngine::DrawStringProp(const olc::vi2d& pos, const std::string& sText, Pixel col, uint32_t scale) { DrawStringProp(pos.x, pos.y, sText, col, scale); } void PixelGameEngine::DrawStringProp(int32_t x, int32_t y, const std::string& sText, Pixel col, uint32_t scale) { int32_t sx = 0; int32_t sy = 0; Pixel::Mode m = nPixelMode; if (m != Pixel::CUSTOM) { if (col.a != 255) SetPixelMode(Pixel::ALPHA); else SetPixelMode(Pixel::MASK); } for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (int32_t i = 0; i < vFontSpacing[c - 32].y; i++) for (int32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8 + vFontSpacing[c - 32].x, j + oy * 8).r > 0) for (int32_t is = 0; is < int(scale); is++) for (int32_t js = 0; js < int(scale); js++) Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col); } else { for (int32_t i = 0; i < vFontSpacing[c - 32].y; i++) for (int32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8 + vFontSpacing[c - 32].x, j + oy * 8).r > 0) Draw(x + sx + i, y + sy + j, col); } sx += vFontSpacing[c - 32].y * scale; } } SetPixelMode(m); } void PixelGameEngine::SetPixelMode(Pixel::Mode m) { nPixelMode = m; } Pixel::Mode PixelGameEngine::GetPixelMode() { return nPixelMode; } void PixelGameEngine::SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> pixelMode) { funcPixelMode = pixelMode; nPixelMode = Pixel::Mode::CUSTOM; } void PixelGameEngine::SetPixelBlend(float fBlend) { fBlendFactor = fBlend; if (fBlendFactor < 0.0f) fBlendFactor = 0.0f; if (fBlendFactor > 1.0f) fBlendFactor = 1.0f; } // User must override these functions as required. I have not made // them abstract because I do need a default behaviour to occur if // they are not overwritten bool PixelGameEngine::OnUserCreate() { return false; } bool PixelGameEngine::OnUserUpdate(double fElapsedTime) { UNUSED(fElapsedTime); return false; } bool PixelGameEngine::OnUserDestroy() { return true; } void PixelGameEngine::olc_UpdateViewport() { int32_t ww = vScreenSize.x * vPixelSize.x; int32_t wh = vScreenSize.y * vPixelSize.y; float wasp = (float)ww / (float)wh; if (bPixelCohesion) { vScreenPixelSize = (vWindowSize / vScreenSize); vViewSize = (vWindowSize / vScreenSize) * vScreenSize; } else { vViewSize.x = (int32_t)vWindowSize.x; vViewSize.y = (int32_t)((float)vViewSize.x / wasp); if (vViewSize.y > vWindowSize.y) { vViewSize.y = vWindowSize.y; vViewSize.x = (int32_t)((float)vViewSize.y * wasp); } } vViewPos = (vWindowSize - vViewSize) / 2; } void PixelGameEngine::olc_UpdateWindowSize(int32_t x, int32_t y) { vWindowSize = { x, y }; olc_UpdateViewport(); } void PixelGameEngine::olc_UpdateMouseWheel(int32_t delta) { nMouseWheelDeltaCache += delta; } void PixelGameEngine::olc_UpdateMouse(int32_t x, int32_t y) { // Mouse coords come in screen space // But leave in pixel space bHasMouseFocus = true; vMouseWindowPos = { x, y }; // Full Screen mode may have a weird viewport we must clamp to x -= vViewPos.x; y -= vViewPos.y; vMousePosCache.x = (int32_t)(((float)x / (float)(vWindowSize.x - (vViewPos.x * 2)) * (float)vScreenSize.x)); vMousePosCache.y = (int32_t)(((float)y / (float)(vWindowSize.y - (vViewPos.y * 2)) * (float)vScreenSize.y)); if (vMousePosCache.x >= (int32_t)vScreenSize.x) vMousePosCache.x = vScreenSize.x - 1; if (vMousePosCache.y >= (int32_t)vScreenSize.y) vMousePosCache.y = vScreenSize.y - 1; if (vMousePosCache.x < 0) vMousePosCache.x = 0; if (vMousePosCache.y < 0) vMousePosCache.y = 0; } void PixelGameEngine::olc_UpdateMouseState(int32_t button, bool state) { pMouseNewState[button] = state; } void PixelGameEngine::olc_UpdateKeyState(int32_t key, bool state) { pKeyNewState[key] = state; } void PixelGameEngine::olc_UpdateMouseFocus(bool state) { bHasMouseFocus = state; } void PixelGameEngine::olc_UpdateKeyFocus(bool state) { bHasInputFocus = state; } void PixelGameEngine::olc_Reanimate() { bAtomActive = true; } bool PixelGameEngine::olc_IsRunning() { return bAtomActive; } void PixelGameEngine::olc_Terminate() { bAtomActive = false; } void PixelGameEngine::EngineThread() { // Allow platform to do stuff here if needed, since its now in the // context of this thread if (platform->ThreadStartUp() == olc::FAIL) return; // Do engine context specific initialisation olc_PrepareEngine(); // Create user resources as part of this thread for (auto& ext : vExtensions) ext->OnBeforeUserCreate(); if (!OnUserCreate()) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserCreate(); while (bAtomActive) { // Run as fast as possible while (bAtomActive) { olc_CoreUpdate(); } // Allow the user to free resources if they have overrided the destroy function if (!OnUserDestroy()) { // User denied destroy for some reason, so continue running bAtomActive = true; } } platform->ThreadCleanUp(); } void PixelGameEngine::olc_PrepareEngine() { // Start OpenGL, the context is owned by the game thread if (platform->CreateGraphics(bFullScreen, bEnableVSYNC, vViewPos, vViewSize) == olc::FAIL) return; // Construct default font sheet olc_ConstructFontSheet(); // Create Primary Layer "0" CreateLayer(); vLayers[0].bUpdate = true; vLayers[0].bShow = true; SetDrawTarget(nullptr); m_tp1 = std::chrono::system_clock::now(); m_tp2 = std::chrono::system_clock::now(); } void PixelGameEngine::olc_CoreUpdate() { // Handle Timing m_tp2 = std::chrono::system_clock::now(); std::chrono::duration<float> elapsedTime = m_tp2 - m_tp1; m_tp1 = m_tp2; // Our time per frame coefficient double fElapsedTime = elapsedTime.count(); fLastElapsed = fElapsedTime; // Some platforms will need to check for events platform->HandleSystemEvent(); // Compare hardware input states from previous frame auto ScanHardware = [&](HWButton* pKeys, bool* pStateOld, bool* pStateNew, uint32_t nKeyCount) { for (uint32_t i = 0; i < nKeyCount; i++) { pKeys[i].bPressed = false; pKeys[i].bReleased = false; if (pStateNew[i] != pStateOld[i]) { if (pStateNew[i]) { pKeys[i].bPressed = !pKeys[i].bHeld; pKeys[i].bHeld = true; } else { pKeys[i].bReleased = true; pKeys[i].bHeld = false; } } pStateOld[i] = pStateNew[i]; } }; ScanHardware(pKeyboardState, pKeyOldState, pKeyNewState, 256); ScanHardware(pMouseState, pMouseOldState, pMouseNewState, nMouseButtons); // Cache mouse coordinates so they remain consistent during frame vMousePos = vMousePosCache; nMouseWheelDelta = nMouseWheelDeltaCache; nMouseWheelDeltaCache = 0; // renderer->ClearBuffer(olc::BLACK, true); // Handle Frame Update for (auto& ext : vExtensions) ext->OnBeforeUserUpdate(fElapsedTime); if (!OnUserUpdate(fElapsedTime)) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserUpdate(fElapsedTime); // Display Frame renderer->UpdateViewport(vViewPos, vViewSize); renderer->ClearBuffer(olc::BLACK, true); // Layer 0 must always exist vLayers[0].bUpdate = true; vLayers[0].bShow = true; SetDecalMode(DecalMode::NORMAL); renderer->PrepareDrawing(); for (auto layer = vLayers.rbegin(); layer != vLayers.rend(); ++layer) { if (layer->bShow) { if (layer->funcHook == nullptr) { renderer->ApplyTexture(layer->nResID); if (layer->bUpdate) { renderer->UpdateTexture(layer->nResID, layer->pDrawTarget); layer->bUpdate = false; } renderer->DrawLayerQuad(layer->vOffset, layer->vScale, layer->tint); // Display Decals in order for this layer for (auto& decal : layer->vecDecalInstance) renderer->DrawDecal(decal); layer->vecDecalInstance.clear(); } else { // Mwa ha ha.... Have Fun!!! layer->funcHook(); } } } // Present Graphics to screen renderer->DisplayFrame(); // Update Title Bar fFrameTimer += fElapsedTime; nFrameCount++; if (fFrameTimer >= 1.0f) { nLastFPS = nFrameCount; fFrameTimer -= 1.0f; std::string sTitle = "OneLoneCoder.com - Pixel Game Engine - " + sAppName + " - FPS: " + std::to_string(nFrameCount); platform->SetWindowTitle(sTitle); nFrameCount = 0; } } void PixelGameEngine::olc_ConstructFontSheet() { std::string data; data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000"; data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400"; data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000"; data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000"; data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000"; data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000"; data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000"; data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000"; data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000"; data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000"; data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000"; data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000"; data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000"; data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0"; data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000"; data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020"; fontSprite = new olc::Sprite(128, 48); int px = 0, py = 0; for (size_t b = 0; b < 1024; b += 4) { uint32_t sym1 = (uint32_t)data[b + 0] - 48; uint32_t sym2 = (uint32_t)data[b + 1] - 48; uint32_t sym3 = (uint32_t)data[b + 2] - 48; uint32_t sym4 = (uint32_t)data[b + 3] - 48; uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4; for (int i = 0; i < 24; i++) { int k = r & (1 << i) ? 255 : 0; fontSprite->SetPixel(px, py, olc::Pixel(k, k, k, k)); if (++py == 48) { px++; py = 0; } } } fontDecal = new olc::Decal(fontSprite); constexpr std::array<uint8_t, 96> vSpacing = { { 0x03,0x25,0x16,0x08,0x07,0x08,0x08,0x04,0x15,0x15,0x08,0x07,0x15,0x07,0x24,0x08, 0x08,0x17,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x24,0x15,0x06,0x07,0x16,0x17, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x17,0x08,0x08,0x17,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x17,0x08,0x08,0x08,0x08,0x17,0x08,0x15,0x08,0x15,0x08,0x08, 0x24,0x18,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x33,0x17,0x17,0x33,0x18,0x17,0x17, 0x17,0x17,0x17,0x17,0x07,0x17,0x17,0x18,0x18,0x17,0x17,0x07,0x33,0x07,0x08,0x00, } }; for (auto c : vSpacing) vFontSpacing.push_back({ c >> 4, c & 15 }); } void PixelGameEngine::pgex_Register(olc::PGEX* pgex) { if (std::find(vExtensions.begin(), vExtensions.end(), pgex) == vExtensions.end()) vExtensions.push_back(pgex); } PGEX::PGEX(bool bHook) { if (bHook) pge->pgex_Register(this); } void PGEX::OnBeforeUserCreate() {} void PGEX::OnAfterUserCreate() {} void PGEX::OnBeforeUserUpdate(double& fElapsedTime) {} void PGEX::OnAfterUserUpdate(double fElapsedTime) {} // Need a couple of statics as these are singleton instances // read from multiple locations std::atomic<bool> PixelGameEngine::bAtomActive{ false }; olc::PixelGameEngine* olc::PGEX::pge = nullptr; olc::PixelGameEngine* olc::Platform::ptrPGE = nullptr; olc::PixelGameEngine* olc::Renderer::ptrPGE = nullptr; std::unique_ptr<ImageLoader> olc::Sprite::loader = nullptr; }; #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Renderers - the draw-y bits | // O------------------------------------------------------------------------------O #pragma region renderer_ogl10 // O------------------------------------------------------------------------------O // | START RENDERER: OpenGL 1.0 (the original, the best...) | // O------------------------------------------------------------------------------O #if defined(OLC_GFX_OPENGL10) #if defined(OLC_PLATFORM_WINAPI) #include <dwmapi.h> #include <GL/gl.h> #if !defined(__MINGW32__) #pragma comment(lib, "Dwmapi.lib") #endif typedef BOOL(WINAPI wglSwapInterval_t) (int interval); static wglSwapInterval_t* wglSwapInterval = nullptr; typedef HDC glDeviceContext_t; typedef HGLRC glRenderContext_t; #endif #if defined(__linux__) || defined(__FreeBSD__) #include <GL/gl.h> #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <GL/glx.h> } typedef int(glSwapInterval_t)(X11::Display* dpy, X11::GLXDrawable drawable, int interval); static glSwapInterval_t* glSwapIntervalEXT; typedef X11::GLXContext glDeviceContext_t; typedef X11::GLXContext glRenderContext_t; #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #include <OpenGL/OpenGL.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #endif namespace olc { class Renderer_OGL10 : public olc::Renderer { private: #if defined(OLC_PLATFORM_GLUT) bool mFullScreen = false; #else glDeviceContext_t glDeviceContext = 0; glRenderContext_t glRenderContext = 0; #endif bool bSync = false; olc::DecalMode nDecalMode = olc::DecalMode(-1); // Thanks Gusgo & Bispoo #if defined(OLC_PLATFORM_X11) X11::Display* olc_Display = nullptr; X11::Window* olc_Window = nullptr; X11::XVisualInfo* olc_VisualInfo = nullptr; #endif public: void PrepareDevice() override { #if defined(OLC_PLATFORM_GLUT) //glutInit has to be called with main() arguments, make fake ones int argc = 0; char* argv[1] = { (char*)"" }; glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); // Creates the window and the OpenGL context for it glutCreateWindow("OneLoneCoder.com - Pixel Game Engine"); glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif } olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) override { #if defined(OLC_PLATFORM_WINAPI) // Create Device Context glDeviceContext = GetDC((HWND)(params[0])); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = 0; if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return olc::FAIL; SetPixelFormat(glDeviceContext, pf, &pfd); if (!(glRenderContext = wglCreateContext(glDeviceContext))) return olc::FAIL; wglMakeCurrent(glDeviceContext, glRenderContext); // Remove Frame cap wglSwapInterval = (wglSwapInterval_t*)wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapInterval && !bVSYNC) wglSwapInterval(0); bSync = bVSYNC; #endif #if defined(OLC_PLATFORM_X11) using namespace X11; // Linux has tighter coupling between OpenGL and X11, so we store // various "platform" handles in the renderer olc_Display = (X11::Display*)(params[0]); olc_Window = (X11::Window*)(params[1]); olc_VisualInfo = (X11::XVisualInfo*)(params[2]); glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE); glXMakeCurrent(olc_Display, *olc_Window, glDeviceContext); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, *olc_Window, &gwa); glViewport(0, 0, gwa.width, gwa.height); glSwapIntervalEXT = nullptr; glSwapIntervalEXT = (glSwapInterval_t*)glXGetProcAddress((unsigned char*)"glXSwapIntervalEXT"); if (glSwapIntervalEXT == nullptr && !bVSYNC) { printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n"); printf(" Don't worry though, things will still work, it's just the\n"); printf(" frame rate will be capped to your monitors refresh rate - javidx9\n"); } if (glSwapIntervalEXT != nullptr && !bVSYNC) glSwapIntervalEXT(olc_Display, *olc_Window, 0); #endif #if defined(OLC_PLATFORM_GLUT) mFullScreen = bFullScreen; if (!bVSYNC) { #if defined(__APPLE__) GLint sync = 0; CGLContextObj ctx = CGLGetCurrentContext(); if (ctx) CGLSetParameter(ctx, kCGLCPSwapInterval, &sync); #endif } #else glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif return olc::rcode::OK; } olc::rcode DestroyDevice() override { #if defined(OLC_PLATFORM_WINAPI) wglDeleteContext(glRenderContext); #endif #if defined(OLC_PLATFORM_X11) glXMakeCurrent(olc_Display, None, NULL); glXDestroyContext(olc_Display, glDeviceContext); #endif #if defined(OLC_PLATFORM_GLUT) glutDestroyWindow(glutGetWindow()); #endif return olc::rcode::OK; } void DisplayFrame() override { #if defined(OLC_PLATFORM_WINAPI) SwapBuffers(glDeviceContext); if (bSync) DwmFlush(); // Woooohooooooo!!!! SMOOOOOOOTH! #endif #if defined(OLC_PLATFORM_X11) X11::glXSwapBuffers(olc_Display, *olc_Window); #endif #if defined(OLC_PLATFORM_GLUT) glutSwapBuffers(); #endif } void PrepareDrawing() override { glEnable(GL_BLEND); nDecalMode = DecalMode::NORMAL; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void SetDecalMode(const olc::DecalMode& mode) { if (mode != nDecalMode) { switch (mode) { case olc::DecalMode::NORMAL: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case olc::DecalMode::MULTIPLICATIVE: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::STENCIL: glBlendFunc(GL_ZERO, GL_SRC_ALPHA); break; case olc::DecalMode::ILLUMINATE: glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA); break; case olc::DecalMode::WIREFRAME: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } nDecalMode = mode; } } void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) override { glBegin(GL_QUADS); glColor4ub(tint.r, tint.g, tint.b, tint.a); glTexCoord2f(0.0f * scale.x + offset.x, 1.0f * scale.y + offset.y); glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(0.0f * scale.x + offset.x, 0.0f * scale.y + offset.y); glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(1.0f * scale.x + offset.x, 0.0f * scale.y + offset.y); glVertex3f(1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(1.0f * scale.x + offset.x, 1.0f * scale.y + offset.y); glVertex3f(1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f); glEnd(); } void DrawDecal(const olc::DecalInstance& decal) override { SetDecalMode(decal.mode); if (decal.decal == nullptr) glBindTexture(GL_TEXTURE_2D, 0); else glBindTexture(GL_TEXTURE_2D, decal.decal->id); if (nDecalMode == DecalMode::WIREFRAME) glBegin(GL_LINE_LOOP); else glBegin(GL_TRIANGLE_FAN); for (uint32_t n = 0; n < decal.points; n++) { glColor4ub(decal.tint[n].r, decal.tint[n].g, decal.tint[n].b, decal.tint[n].a); glTexCoord4f(decal.uv[n].x, decal.uv[n].y, 0.0f, decal.w[n]); glVertex2f(decal.pos[n].x, decal.pos[n].y); } glEnd(); } uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered, const bool clamp) override { UNUSED(width); UNUSED(height); uint32_t id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if (filtered) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); return id; } uint32_t DeleteTexture(const uint32_t id) override { glDeleteTextures(1, &id); return id; } void UpdateTexture(uint32_t id, olc::Sprite* spr) override { UNUSED(id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, spr->width, spr->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ReadTexture(uint32_t id, olc::Sprite* spr) override { glReadPixels(0, 0, spr->width, spr->height, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ApplyTexture(uint32_t id) override { glBindTexture(GL_TEXTURE_2D, id); } void ClearBuffer(olc::Pixel p, bool bDepth) override { glClearColor(float(p.r) / 255.0f, float(p.g) / 255.0f, float(p.b) / 255.0f, float(p.a) / 255.0f); glClear(GL_COLOR_BUFFER_BIT); if (bDepth) glClear(GL_DEPTH_BUFFER_BIT); } void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) override { #if defined(OLC_PLATFORM_GLUT) if (!mFullScreen) glutReshapeWindow(size.x, size.y); #else glViewport(pos.x, pos.y, size.x, size.y); #endif } }; } #endif // O------------------------------------------------------------------------------O // | END RENDERER: OpenGL 1.0 (the original, the best...) | // O------------------------------------------------------------------------------O #pragma endregion #pragma region renderer_ogl33 // O------------------------------------------------------------------------------O // | START RENDERER: OpenGL 3.3 (3.0 es) (sh-sh-sh-shaders....) | // O------------------------------------------------------------------------------O #if defined(OLC_GFX_OPENGL33) #if defined(OLC_PLATFORM_WINAPI) #include <dwmapi.h> #include <gl/GL.h> #if !defined(__MINGW32__) #pragma comment(lib, "Dwmapi.lib") #endif typedef void __stdcall locSwapInterval_t(GLsizei n); typedef HDC glDeviceContext_t; typedef HGLRC glRenderContext_t; #define CALLSTYLE __stdcall #define OGL_LOAD(t, n) (t*)wglGetProcAddress(#n) #endif #if defined(__linux__) || defined(__FreeBSD__) #include <GL/gl.h> #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <GL/glx.h> } typedef int(locSwapInterval_t)(X11::Display* dpy, X11::GLXDrawable drawable, int interval); typedef X11::GLXContext glDeviceContext_t; typedef X11::GLXContext glRenderContext_t; #define CALLSTYLE #define OGL_LOAD(t, n) (t*)glXGetProcAddress((unsigned char*)#n); #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #include <OpenGL/OpenGL.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) #include <EGL/egl.h> #include <GLES2/gl2.h> #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2ext.h> #include <emscripten/emscripten.h> #define CALLSTYLE typedef EGLBoolean(locSwapInterval_t)(EGLDisplay display, EGLint interval); #define GL_CLAMP GL_CLAMP_TO_EDGE #define OGL_LOAD(t, n) n; #endif namespace olc { typedef char GLchar; typedef ptrdiff_t GLsizeiptr; typedef GLuint CALLSTYLE locCreateShader_t(GLenum type); typedef GLuint CALLSTYLE locCreateProgram_t(void); typedef void CALLSTYLE locDeleteShader_t(GLuint shader); #if defined(OLC_PLATFORM_EMSCRIPTEN) typedef void CALLSTYLE locShaderSource_t(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length); #else typedef void CALLSTYLE locShaderSource_t(GLuint shader, GLsizei count, const GLchar** string, const GLint* length); #endif typedef void CALLSTYLE locCompileShader_t(GLuint shader); typedef void CALLSTYLE locLinkProgram_t(GLuint program); typedef void CALLSTYLE locDeleteProgram_t(GLuint program); typedef void CALLSTYLE locAttachShader_t(GLuint program, GLuint shader); typedef void CALLSTYLE locBindBuffer_t(GLenum target, GLuint buffer); typedef void CALLSTYLE locBufferData_t(GLenum target, GLsizeiptr size, const void* data, GLenum usage); typedef void CALLSTYLE locGenBuffers_t(GLsizei n, GLuint* buffers); typedef void CALLSTYLE locVertexAttribPointer_t(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer); typedef void CALLSTYLE locEnableVertexAttribArray_t(GLuint index); typedef void CALLSTYLE locUseProgram_t(GLuint program); typedef void CALLSTYLE locBindVertexArray_t(GLuint array); typedef void CALLSTYLE locGenVertexArrays_t(GLsizei n, GLuint* arrays); typedef void CALLSTYLE locGetShaderInfoLog_t(GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog); constexpr size_t OLC_MAX_VERTS = 128; class Renderer_OGL33 : public olc::Renderer { private: #if defined(OLC_PLATFORM_EMSCRIPTEN) EGLDisplay olc_Display; EGLConfig olc_Config; EGLContext olc_Context; EGLSurface olc_Surface; #endif #if defined(OLC_PLATFORM_GLUT) bool mFullScreen = false; #else #if !defined(OLC_PLATFORM_EMSCRIPTEN) glDeviceContext_t glDeviceContext = 0; glRenderContext_t glRenderContext = 0; #endif #endif bool bSync = false; olc::DecalMode nDecalMode = olc::DecalMode(-1); // Thanks Gusgo & Bispoo #if defined(OLC_PLATFORM_X11) X11::Display* olc_Display = nullptr; X11::Window* olc_Window = nullptr; X11::XVisualInfo* olc_VisualInfo = nullptr; #endif private: locCreateShader_t* locCreateShader = nullptr; locShaderSource_t* locShaderSource = nullptr; locCompileShader_t* locCompileShader = nullptr; locDeleteShader_t* locDeleteShader = nullptr; locCreateProgram_t* locCreateProgram = nullptr; locDeleteProgram_t* locDeleteProgram = nullptr; locLinkProgram_t* locLinkProgram = nullptr; locAttachShader_t* locAttachShader = nullptr; locBindBuffer_t* locBindBuffer = nullptr; locBufferData_t* locBufferData = nullptr; locGenBuffers_t* locGenBuffers = nullptr; locVertexAttribPointer_t* locVertexAttribPointer = nullptr; locEnableVertexAttribArray_t* locEnableVertexAttribArray = nullptr; locUseProgram_t* locUseProgram = nullptr; locBindVertexArray_t* locBindVertexArray = nullptr; locGenVertexArrays_t* locGenVertexArrays = nullptr; locSwapInterval_t* locSwapInterval = nullptr; locGetShaderInfoLog_t* locGetShaderInfoLog = nullptr; uint32_t m_nFS = 0; uint32_t m_nVS = 0; uint32_t m_nQuadShader = 0; uint32_t m_vbQuad = 0; uint32_t m_vaQuad = 0; struct locVertex { float pos[3]; olc::vf2d tex; olc::Pixel col; }; locVertex pVertexMem[OLC_MAX_VERTS]; olc::Renderable rendBlankQuad; public: void PrepareDevice() override { #if defined(OLC_PLATFORM_GLUT) //glutInit has to be called with main() arguments, make fake ones int argc = 0; char* argv[1] = { (char*)"" }; glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); // Creates the window and the OpenGL context for it glutCreateWindow("OneLoneCoder.com - Pixel Game Engine"); glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif } olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) override { // Create OpenGL Context #if defined(OLC_PLATFORM_WINAPI) // Create Device Context glDeviceContext = GetDC((HWND)(params[0])); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = 0; if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return olc::FAIL; SetPixelFormat(glDeviceContext, pf, &pfd); if (!(glRenderContext = wglCreateContext(glDeviceContext))) return olc::FAIL; wglMakeCurrent(glDeviceContext, glRenderContext); // Set Vertical Sync locSwapInterval = OGL_LOAD(locSwapInterval_t, "wglSwapIntervalEXT"); if (locSwapInterval && !bVSYNC) locSwapInterval(0); bSync = bVSYNC; #endif #if defined(OLC_PLATFORM_X11) using namespace X11; // Linux has tighter coupling between OpenGL and X11, so we store // various "platform" handles in the renderer olc_Display = (X11::Display*)(params[0]); olc_Window = (X11::Window*)(params[1]); olc_VisualInfo = (X11::XVisualInfo*)(params[2]); glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE); glXMakeCurrent(olc_Display, *olc_Window, glDeviceContext); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, *olc_Window, &gwa); glViewport(0, 0, gwa.width, gwa.height); locSwapInterval = OGL_LOAD(locSwapInterval_t, "glXSwapIntervalEXT"); if (locSwapInterval == nullptr && !bVSYNC) { printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n"); printf(" Don't worry though, things will still work, it's just the\n"); printf(" frame rate will be capped to your monitors refresh rate - javidx9\n"); } if (locSwapInterval != nullptr && !bVSYNC) locSwapInterval(olc_Display, *olc_Window, 0); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) EGLint const attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLint const context_config[] = { EGL_CONTEXT_CLIENT_VERSION , 2, EGL_NONE }; EGLint num_config; olc_Display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(olc_Display, nullptr, nullptr); eglChooseConfig(olc_Display, attribute_list, &olc_Config, 1, &num_config); /* create an EGL rendering context */ olc_Context = eglCreateContext(olc_Display, olc_Config, EGL_NO_CONTEXT, context_config); olc_Surface = eglCreateWindowSurface(olc_Display, olc_Config, NULL, nullptr); eglMakeCurrent(olc_Display, olc_Surface, olc_Surface, olc_Context); //eglSwapInterval is currently a NOP, plement anyways in case it becomes supported locSwapInterval = &eglSwapInterval; locSwapInterval(olc_Display, bVSYNC ? 1 : 0); #endif #if defined(OLC_PLATFORM_GLUT) mFullScreen = bFullScreen; if (!bVSYNC) { #if defined(__APPLE__) GLint sync = 0; CGLContextObj ctx = CGLGetCurrentContext(); if (ctx) CGLSetParameter(ctx, kCGLCPSwapInterval, &sync); #endif } #else #if !defined(OLC_PLATFORM_EMSCRIPTEN) glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif #endif // Load External OpenGL Functions locCreateShader = OGL_LOAD(locCreateShader_t, glCreateShader); locCompileShader = OGL_LOAD(locCompileShader_t, glCompileShader); locShaderSource = OGL_LOAD(locShaderSource_t, glShaderSource); locDeleteShader = OGL_LOAD(locDeleteShader_t, glDeleteShader); locCreateProgram = OGL_LOAD(locCreateProgram_t, glCreateProgram); locDeleteProgram = OGL_LOAD(locDeleteProgram_t, glDeleteProgram); locLinkProgram = OGL_LOAD(locLinkProgram_t, glLinkProgram); locAttachShader = OGL_LOAD(locAttachShader_t, glAttachShader); locBindBuffer = OGL_LOAD(locBindBuffer_t, glBindBuffer); locBufferData = OGL_LOAD(locBufferData_t, glBufferData); locGenBuffers = OGL_LOAD(locGenBuffers_t, glGenBuffers); locVertexAttribPointer = OGL_LOAD(locVertexAttribPointer_t, glVertexAttribPointer); locEnableVertexAttribArray = OGL_LOAD(locEnableVertexAttribArray_t, glEnableVertexAttribArray); locUseProgram = OGL_LOAD(locUseProgram_t, glUseProgram); locGetShaderInfoLog = OGL_LOAD(locGetShaderInfoLog_t, glGetShaderInfoLog); #if !defined(OLC_PLATFORM_EMSCRIPTEN) locBindVertexArray = OGL_LOAD(locBindVertexArray_t, glBindVertexArray); locGenVertexArrays = OGL_LOAD(locGenVertexArrays_t, glGenVertexArrays); #else locBindVertexArray = glBindVertexArrayOES; locGenVertexArrays = glGenVertexArraysOES; #endif // Load & Compile Quad Shader - assumes no errors m_nFS = locCreateShader(0x8B30); const GLchar* strFS = #if defined(__arm__) || defined(OLC_PLATFORM_EMSCRIPTEN) "#version 300 es\n" "precision mediump float;" #else "#version 330 core\n" #endif "out vec4 pixel;\n""in vec2 oTex;\n" "in vec4 oCol;\n""uniform sampler2D sprTex;\n""void main(){pixel = texture(sprTex, oTex) * oCol;}"; locShaderSource(m_nFS, 1, &strFS, NULL); locCompileShader(m_nFS); m_nVS = locCreateShader(0x8B31); const GLchar* strVS = #if defined(__arm__) || defined(OLC_PLATFORM_EMSCRIPTEN) "#version 300 es\n" "precision mediump float;" #else "#version 330 core\n" #endif "layout(location = 0) in vec3 aPos;\n""layout(location = 1) in vec2 aTex;\n" "layout(location = 2) in vec4 aCol;\n""out vec2 oTex;\n""out vec4 oCol;\n" "void main(){ float p = 1.0 / aPos.z; gl_Position = p * vec4(aPos.x, aPos.y, 0.0, 1.0); oTex = p * aTex; oCol = aCol;}"; locShaderSource(m_nVS, 1, &strVS, NULL); locCompileShader(m_nVS); m_nQuadShader = locCreateProgram(); locAttachShader(m_nQuadShader, m_nFS); locAttachShader(m_nQuadShader, m_nVS); locLinkProgram(m_nQuadShader); // Create Quad locGenBuffers(1, &m_vbQuad); locGenVertexArrays(1, &m_vaQuad); locBindVertexArray(m_vaQuad); locBindBuffer(0x8892, m_vbQuad); locVertex verts[OLC_MAX_VERTS]; locBufferData(0x8892, sizeof(locVertex) * OLC_MAX_VERTS, verts, 0x88E0); locVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(locVertex), 0); locEnableVertexAttribArray(0); locVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(locVertex), (void*)(3 * sizeof(float))); locEnableVertexAttribArray(1); locVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(locVertex), (void*)(5 * sizeof(float))); locEnableVertexAttribArray(2); locBindBuffer(0x8892, 0); locBindVertexArray(0); // Create blank texture for spriteless decals rendBlankQuad.Create(1, 1); rendBlankQuad.Sprite()->GetData()[0] = olc::WHITE; rendBlankQuad.Decal()->Update(); return olc::rcode::OK; } olc::rcode DestroyDevice() override { #if defined(OLC_PLATFORM_WINAPI) wglDeleteContext(glRenderContext); #endif #if defined(OLC_PLATFORM_X11) glXMakeCurrent(olc_Display, None, NULL); glXDestroyContext(olc_Display, glDeviceContext); #endif #if defined(OLC_PLATFORM_GLUT) glutDestroyWindow(glutGetWindow()); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) eglMakeCurrent(olc_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(olc_Display, olc_Context); eglDestroySurface(olc_Display, olc_Surface); eglTerminate(olc_Display); olc_Display = EGL_NO_DISPLAY; olc_Surface = EGL_NO_SURFACE; olc_Context = EGL_NO_CONTEXT; #endif return olc::rcode::OK; } void DisplayFrame() override { #if defined(OLC_PLATFORM_WINAPI) SwapBuffers(glDeviceContext); if (bSync) DwmFlush(); // Woooohooooooo!!!! SMOOOOOOOTH! #endif #if defined(OLC_PLATFORM_X11) X11::glXSwapBuffers(olc_Display, *olc_Window); #endif #if defined(OLC_PLATFORM_GLUT) glutSwapBuffers(); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) eglSwapBuffers(olc_Display, olc_Surface); #endif } void PrepareDrawing() override { glEnable(GL_BLEND); nDecalMode = DecalMode::NORMAL; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); locUseProgram(m_nQuadShader); locBindVertexArray(m_vaQuad); #if defined(OLC_PLATFORM_EMSCRIPTEN) locVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(locVertex), 0); locEnableVertexAttribArray(0); locVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(locVertex), (void*)(3 * sizeof(float))); locEnableVertexAttribArray(1); locVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(locVertex), (void*)(5 * sizeof(float))); locEnableVertexAttribArray(2); #endif } void SetDecalMode(const olc::DecalMode& mode) override { if (mode != nDecalMode) { switch (mode) { case olc::DecalMode::NORMAL: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case olc::DecalMode::MULTIPLICATIVE: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::STENCIL: glBlendFunc(GL_ZERO, GL_SRC_ALPHA); break; case olc::DecalMode::ILLUMINATE: glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA); break; case olc::DecalMode::WIREFRAME: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } nDecalMode = mode; } } void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) override { locBindBuffer(0x8892, m_vbQuad); locVertex verts[4] = { {{-1.0f, -1.0f, 1.0}, {0.0f * scale.x + offset.x, 1.0f * scale.y + offset.y}, tint}, {{+1.0f, -1.0f, 1.0}, {1.0f * scale.x + offset.x, 1.0f * scale.y + offset.y}, tint}, {{-1.0f, +1.0f, 1.0}, {0.0f * scale.x + offset.x, 0.0f * scale.y + offset.y}, tint}, {{+1.0f, +1.0f, 1.0}, {1.0f * scale.x + offset.x, 0.0f * scale.y + offset.y}, tint}, }; locBufferData(0x8892, sizeof(locVertex) * 4, verts, 0x88E0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void DrawDecal(const olc::DecalInstance& decal) override { SetDecalMode(decal.mode); if (decal.decal == nullptr) glBindTexture(GL_TEXTURE_2D, rendBlankQuad.Decal()->id); else glBindTexture(GL_TEXTURE_2D, decal.decal->id); locBindBuffer(0x8892, m_vbQuad); for (uint32_t i = 0; i < decal.points; i++) pVertexMem[i] = { { decal.pos[i].x, decal.pos[i].y, decal.w[i] }, { decal.uv[i].x, decal.uv[i].y }, decal.tint[i] }; locBufferData(0x8892, sizeof(locVertex) * decal.points, pVertexMem, 0x88E0); if (nDecalMode == DecalMode::WIREFRAME) glDrawArrays(GL_LINE_LOOP, 0, decal.points); else glDrawArrays(GL_TRIANGLE_FAN, 0, decal.points); } uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered, const bool clamp) override { UNUSED(width); UNUSED(height); uint32_t id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if (filtered) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } #if !defined(OLC_PLATFORM_EMSCRIPTEN) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #endif return id; } uint32_t DeleteTexture(const uint32_t id) override { glDeleteTextures(1, &id); return id; } void UpdateTexture(uint32_t id, olc::Sprite* spr) override { UNUSED(id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, spr->width, spr->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ReadTexture(uint32_t id, olc::Sprite* spr) override { glReadPixels(0, 0, spr->width, spr->height, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ApplyTexture(uint32_t id) override { glBindTexture(GL_TEXTURE_2D, id); } void ClearBuffer(olc::Pixel p, bool bDepth) override { glClearColor(float(p.r) / 255.0f, float(p.g) / 255.0f, float(p.b) / 255.0f, float(p.a) / 255.0f); glClear(GL_COLOR_BUFFER_BIT); if (bDepth) glClear(GL_DEPTH_BUFFER_BIT); } void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) override { #if defined(OLC_PLATFORM_GLUT) if (!mFullScreen) glutReshapeWindow(size.x, size.y); #else glViewport(pos.x, pos.y, size.x, size.y); #endif } }; } #endif // O------------------------------------------------------------------------------O // | END RENDERER: OpenGL 3.3 (3.0 es) (sh-sh-sh-shaders....) | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Image loaders | // O------------------------------------------------------------------------------O #pragma region image_gdi // O------------------------------------------------------------------------------O // | START IMAGE LOADER: GDI+, Windows Only, always exists, a little slow | // O------------------------------------------------------------------------------O #if defined(OLC_IMAGE_GDI) #define min(a, b) ((a < b) ? a : b) #define max(a, b) ((a > b) ? a : b) #include <objidl.h> #include <gdiplus.h> #if defined(__MINGW32__) // Thanks Gusgo & Dandistine, but c'mon mingw!! wtf?! #include <gdiplus/gdiplusinit.h> #else #include <gdiplusinit.h> #endif #include <shlwapi.h> #undef min #undef max #if !defined(__MINGW32__) #pragma comment(lib, "gdiplus.lib") #pragma comment(lib, "Shlwapi.lib") #endif namespace olc { // Thanks @MaGetzUb for this, which allows sprites to be defined // at construction, by initialising the GDI subsystem static class GDIPlusStartup { public: GDIPlusStartup() { Gdiplus::GdiplusStartupInput startupInput; GdiplusStartup(&token, &startupInput, NULL); } ULONG_PTR token; ~GDIPlusStartup() { // Well, MarcusTU thought this was important :D Gdiplus::GdiplusShutdown(token); } } gdistartup; class ImageLoader_GDIPlus : public olc::ImageLoader { private: std::wstring ConvertS2W(std::string s) { #ifdef __MINGW32__ wchar_t* buffer = new wchar_t[s.length() + 1]; mbstowcs(buffer, s.c_str(), s.length()); buffer[s.length()] = L'\0'; #else int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); wchar_t* buffer = new wchar_t[count]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count); #endif std::wstring w(buffer); delete[] buffer; return w; } public: ImageLoader_GDIPlus() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { // clear out existing sprite spr->pColData.clear(); // Open file UNUSED(pack); Gdiplus::Bitmap* bmp = nullptr; if (pack != nullptr) { // Load sprite from input stream ResourceBuffer rb = pack->GetFileBuffer(sImageFile); bmp = Gdiplus::Bitmap::FromStream(SHCreateMemStream((BYTE*)rb.vMemory.data(), UINT(rb.vMemory.size()))); } else { // Check file exists if (!_gfs::exists(sImageFile)) return olc::rcode::NO_FILE; // Load sprite from file bmp = Gdiplus::Bitmap::FromFile(ConvertS2W(sImageFile).c_str()); } if (bmp->GetLastStatus() != Gdiplus::Ok) return olc::rcode::FAIL; spr->width = bmp->GetWidth(); spr->height = bmp->GetHeight(); spr->pColData.resize(spr->width * spr->height); for (int y = 0; y < spr->height; y++) for (int x = 0; x < spr->width; x++) { Gdiplus::Color c; bmp->GetPixel(x, y, &c); spr->SetPixel(x, y, olc::Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha())); } delete bmp; return olc::rcode::OK; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END IMAGE LOADER: GDI+ | // O------------------------------------------------------------------------------O #pragma endregion #pragma region image_libpng // O------------------------------------------------------------------------------O // | START IMAGE LOADER: libpng, default on linux, requires -lpng (libpng-dev) | // O------------------------------------------------------------------------------O #if defined(OLC_IMAGE_LIBPNG) #include <png.h> namespace olc { void pngReadStream(png_structp pngPtr, png_bytep data, png_size_t length) { png_voidp a = png_get_io_ptr(pngPtr); ((std::istream*)a)->read((char*)data, length); } class ImageLoader_LibPNG : public olc::ImageLoader { public: ImageLoader_LibPNG() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { UNUSED(pack); // clear out existing sprite spr->pColData.clear(); //////////////////////////////////////////////////////////////////////////// // Use libpng, Thanks to Guillaume Cottenceau // https://gist.github.com/niw/5963798 // Also reading png from streams // http://www.piko3d.net/tutorials/libpng-tutorial-loading-png-files-from-streams/ png_structp png; png_infop info; auto loadPNG = [&]() { png_read_info(png, info); png_byte color_type; png_byte bit_depth; png_bytep* row_pointers; spr->width = png_get_image_width(png, info); spr->height = png_get_image_height(png, info); color_type = png_get_color_type(png, info); bit_depth = png_get_bit_depth(png, info); if (bit_depth == 16) png_set_strip_16(png); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png); if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png, 0xFF, PNG_FILLER_AFTER); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); png_read_update_info(png, info); row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * spr->height); for (int y = 0; y < spr->height; y++) { row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info)); } png_read_image(png, row_pointers); //////////////////////////////////////////////////////////////////////////// // Create sprite array spr->pColData.resize(spr->width * spr->height); // Iterate through image rows, converting into sprite format for (int y = 0; y < spr->height; y++) { png_bytep row = row_pointers[y]; for (int x = 0; x < spr->width; x++) { png_bytep px = &(row[x * 4]); spr->SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3])); } } for (int y = 0; y < spr->height; y++) // Thanks maksym33 free(row_pointers[y]); free(row_pointers); png_destroy_read_struct(&png, &info, nullptr); }; png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png) goto fail_load; info = png_create_info_struct(png); if (!info) goto fail_load; if (setjmp(png_jmpbuf(png))) goto fail_load; if (pack == nullptr) { FILE* f = fopen(sImageFile.c_str(), "rb"); if (!f) return olc::rcode::NO_FILE; png_init_io(png, f); loadPNG(); fclose(f); } else { ResourceBuffer rb = pack->GetFileBuffer(sImageFile); std::istream is(&rb); png_set_read_fn(png, (png_voidp)&is, pngReadStream); loadPNG(); } return olc::rcode::OK; fail_load: spr->width = 0; spr->height = 0; spr->pColData.clear(); return olc::rcode::FAIL; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END IMAGE LOADER: | // O------------------------------------------------------------------------------O #pragma endregion #pragma region image_stb // O------------------------------------------------------------------------------O // | START IMAGE LOADER: stb_image.h, all systems, very fast | // O------------------------------------------------------------------------------O // Thanks to Sean Barrett - https://github.com/nothings/stb/blob/master/stb_image.h // MIT License - Copyright(c) 2017 Sean Barrett // Note you need to download the above file into your project folder, and // #define OLC_IMAGE_STB // #define OLC_PGE_APPLICATION // #include "olcPixelGameEngine.h" #if defined(OLC_IMAGE_STB) #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" namespace olc { class ImageLoader_STB : public olc::ImageLoader { public: ImageLoader_STB() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { UNUSED(pack); // clear out existing sprite spr->pColData.clear(); // Open file stbi_uc* bytes = nullptr; int w = 0, h = 0, cmp = 0; if (pack != nullptr) { ResourceBuffer rb = pack->GetFileBuffer(sImageFile); bytes = stbi_load_from_memory((unsigned char*)rb.vMemory.data(), rb.vMemory.size(), &w, &h, &cmp, 4); } else { // Check file exists if (!_gfs::exists(sImageFile)) return olc::rcode::NO_FILE; bytes = stbi_load(sImageFile.c_str(), &w, &h, &cmp, 4); } if (!bytes) return olc::rcode::FAIL; spr->width = w; spr->height = h; spr->pColData.resize(spr->width * spr->height); std::memcpy(spr->pColData.data(), bytes, spr->width * spr->height * 4); delete[] bytes; return olc::rcode::OK; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | START IMAGE LOADER: stb_image.h | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Platforms | // O------------------------------------------------------------------------------O #pragma region platform_windows // O------------------------------------------------------------------------------O // | START PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_WINAPI) #if defined(_WIN32) && !defined(__MINGW32__) #pragma comment(lib, "user32.lib") // Visual Studio Only #pragma comment(lib, "gdi32.lib") // For other Windows Compilers please add #pragma comment(lib, "opengl32.lib") // these libs to your linker input #endif namespace olc { class Platform_Windows : public olc::Platform { private: HWND olc_hWnd = nullptr; std::wstring wsAppName; std::wstring ConvertS2W(std::string s) { #ifdef __MINGW32__ wchar_t* buffer = new wchar_t[s.length() + 1]; mbstowcs(buffer, s.c_str(), s.length()); buffer[s.length()] = L'\0'; #else int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); wchar_t* buffer = new wchar_t[count]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count); #endif std::wstring w(buffer); delete[] buffer; return w; } public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); PostMessage(olc_hWnd, WM_DESTROY, 0, 0); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({ olc_hWnd }, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { WNDCLASS wc; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.hInstance = GetModuleHandle(nullptr); wc.lpfnWndProc = olc_WindowEvent; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.lpszMenuName = nullptr; wc.hbrBackground = nullptr; wc.lpszClassName = olcT("OLC_PIXEL_GAME_ENGINE"); RegisterClass(&wc); // Define window furniture DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; DWORD dwStyle = WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_THICKFRAME; olc::vi2d vTopLeft = vWindowPos; // Handle Fullscreen if (bFullScreen) { dwExStyle = 0; dwStyle = WS_VISIBLE | WS_POPUP; HMONITOR hmon = MonitorFromWindow(olc_hWnd, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = { sizeof(mi) }; if (!GetMonitorInfo(hmon, &mi)) return olc::rcode::FAIL; vWindowSize = { mi.rcMonitor.right, mi.rcMonitor.bottom }; vTopLeft.x = 0; vTopLeft.y = 0; } // Keep client size as requested RECT rWndRect = { 0, 0, vWindowSize.x, vWindowSize.y }; AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle); int width = rWndRect.right - rWndRect.left; int height = rWndRect.bottom - rWndRect.top; olc_hWnd = CreateWindowEx(dwExStyle, olcT("OLC_PIXEL_GAME_ENGINE"), olcT(""), dwStyle, vTopLeft.x, vTopLeft.y, width, height, NULL, NULL, GetModuleHandle(nullptr), this); // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys[0x41] = Key::A; mapKeys[0x42] = Key::B; mapKeys[0x43] = Key::C; mapKeys[0x44] = Key::D; mapKeys[0x45] = Key::E; mapKeys[0x46] = Key::F; mapKeys[0x47] = Key::G; mapKeys[0x48] = Key::H; mapKeys[0x49] = Key::I; mapKeys[0x4A] = Key::J; mapKeys[0x4B] = Key::K; mapKeys[0x4C] = Key::L; mapKeys[0x4D] = Key::M; mapKeys[0x4E] = Key::N; mapKeys[0x4F] = Key::O; mapKeys[0x50] = Key::P; mapKeys[0x51] = Key::Q; mapKeys[0x52] = Key::R; mapKeys[0x53] = Key::S; mapKeys[0x54] = Key::T; mapKeys[0x55] = Key::U; mapKeys[0x56] = Key::V; mapKeys[0x57] = Key::W; mapKeys[0x58] = Key::X; mapKeys[0x59] = Key::Y; mapKeys[0x5A] = Key::Z; mapKeys[VK_F1] = Key::F1; mapKeys[VK_F2] = Key::F2; mapKeys[VK_F3] = Key::F3; mapKeys[VK_F4] = Key::F4; mapKeys[VK_F5] = Key::F5; mapKeys[VK_F6] = Key::F6; mapKeys[VK_F7] = Key::F7; mapKeys[VK_F8] = Key::F8; mapKeys[VK_F9] = Key::F9; mapKeys[VK_F10] = Key::F10; mapKeys[VK_F11] = Key::F11; mapKeys[VK_F12] = Key::F12; mapKeys[VK_DOWN] = Key::DOWN; mapKeys[VK_LEFT] = Key::LEFT; mapKeys[VK_RIGHT] = Key::RIGHT; mapKeys[VK_UP] = Key::UP; mapKeys[VK_RETURN] = Key::ENTER; //mapKeys[VK_RETURN] = Key::RETURN; mapKeys[VK_BACK] = Key::BACK; mapKeys[VK_ESCAPE] = Key::ESCAPE; mapKeys[VK_RETURN] = Key::ENTER; mapKeys[VK_PAUSE] = Key::PAUSE; mapKeys[VK_SCROLL] = Key::SCROLL; mapKeys[VK_TAB] = Key::TAB; mapKeys[VK_DELETE] = Key::DEL; mapKeys[VK_HOME] = Key::HOME; mapKeys[VK_END] = Key::END; mapKeys[VK_PRIOR] = Key::PGUP; mapKeys[VK_NEXT] = Key::PGDN; mapKeys[VK_INSERT] = Key::INS; mapKeys[VK_SHIFT] = Key::SHIFT; mapKeys[VK_CONTROL] = Key::CTRL; mapKeys[VK_SPACE] = Key::SPACE; mapKeys[0x30] = Key::K0; mapKeys[0x31] = Key::K1; mapKeys[0x32] = Key::K2; mapKeys[0x33] = Key::K3; mapKeys[0x34] = Key::K4; mapKeys[0x35] = Key::K5; mapKeys[0x36] = Key::K6; mapKeys[0x37] = Key::K7; mapKeys[0x38] = Key::K8; mapKeys[0x39] = Key::K9; mapKeys[VK_NUMPAD0] = Key::NP0; mapKeys[VK_NUMPAD1] = Key::NP1; mapKeys[VK_NUMPAD2] = Key::NP2; mapKeys[VK_NUMPAD3] = Key::NP3; mapKeys[VK_NUMPAD4] = Key::NP4; mapKeys[VK_NUMPAD5] = Key::NP5; mapKeys[VK_NUMPAD6] = Key::NP6; mapKeys[VK_NUMPAD7] = Key::NP7; mapKeys[VK_NUMPAD8] = Key::NP8; mapKeys[VK_NUMPAD9] = Key::NP9; mapKeys[VK_MULTIPLY] = Key::NP_MUL; mapKeys[VK_ADD] = Key::NP_ADD; mapKeys[VK_DIVIDE] = Key::NP_DIV; mapKeys[VK_SUBTRACT] = Key::NP_SUB; mapKeys[VK_DECIMAL] = Key::NP_DECIMAL; // Thanks scripticuk mapKeys[VK_OEM_1] = Key::OEM_1; // On US and UK keyboards this is the ';:' key mapKeys[VK_OEM_2] = Key::OEM_2; // On US and UK keyboards this is the '/?' key mapKeys[VK_OEM_3] = Key::OEM_3; // On US keyboard this is the '~' key mapKeys[VK_OEM_4] = Key::OEM_4; // On US and UK keyboards this is the '[{' key mapKeys[VK_OEM_5] = Key::OEM_5; // On US keyboard this is '\|' key. mapKeys[VK_OEM_6] = Key::OEM_6; // On US and UK keyboards this is the ']}' key mapKeys[VK_OEM_7] = Key::OEM_7; // On US keyboard this is the single/double quote key. On UK, this is the single quote/@ symbol key mapKeys[VK_OEM_8] = Key::OEM_8; // miscellaneous characters. Varies by keyboard mapKeys[VK_OEM_PLUS] = Key::EQUALS; // the '+' key on any keyboard mapKeys[VK_OEM_COMMA] = Key::COMMA; // the comma key on any keyboard mapKeys[VK_OEM_MINUS] = Key::MINUS; // the minus key on any keyboard mapKeys[VK_OEM_PERIOD] = Key::PERIOD; // the period key on any keyboard mapKeys[VK_CAPITAL] = Key::CAPS_LOCK; return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { #ifdef UNICODE SetWindowText(olc_hWnd, ConvertS2W(s).c_str()); #else SetWindowText(olc_hWnd, s.c_str()); #endif return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::rcode::FAIL; } // Windows Event Handler - this is statically connected to the windows event system static LRESULT CALLBACK olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_MOUSEMOVE: { // Thanks @ForAbby (Discord) uint16_t x = lParam & 0xFFFF; uint16_t y = (lParam >> 16) & 0xFFFF; int16_t ix = *(int16_t*)&x; int16_t iy = *(int16_t*)&y; ptrPGE->olc_UpdateMouse(ix, iy); return 0; } case WM_SIZE: ptrPGE->olc_UpdateWindowSize(lParam & 0xFFFF, (lParam >> 16) & 0xFFFF); return 0; case WM_MOUSEWHEEL: ptrPGE->olc_UpdateMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam)); return 0; case WM_MOUSELEAVE: ptrPGE->olc_UpdateMouseFocus(false); return 0; case WM_SETFOCUS: ptrPGE->olc_UpdateKeyFocus(true); return 0; case WM_KILLFOCUS: ptrPGE->olc_UpdateKeyFocus(false); return 0; case WM_KEYDOWN: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], true); return 0; case WM_KEYUP: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], false); return 0; case WM_SYSKEYDOWN: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], true); return 0; case WM_SYSKEYUP: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], false); return 0; case WM_LBUTTONDOWN:ptrPGE->olc_UpdateMouseState(0, true); return 0; case WM_LBUTTONUP: ptrPGE->olc_UpdateMouseState(0, false); return 0; case WM_RBUTTONDOWN:ptrPGE->olc_UpdateMouseState(1, true); return 0; case WM_RBUTTONUP: ptrPGE->olc_UpdateMouseState(1, false); return 0; case WM_MBUTTONDOWN:ptrPGE->olc_UpdateMouseState(2, true); return 0; case WM_MBUTTONUP: ptrPGE->olc_UpdateMouseState(2, false); return 0; case WM_CLOSE: ptrPGE->olc_Terminate(); return 0; case WM_DESTROY: PostQuitMessage(0); DestroyWindow(hWnd); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } }; } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_linux // O------------------------------------------------------------------------------O // | START PLATFORM: LINUX | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_X11) namespace olc { class Platform_Linux : public olc::Platform { private: X11::Display* olc_Display = nullptr; X11::Window olc_WindowRoot; X11::Window olc_Window; X11::XVisualInfo* olc_VisualInfo; X11::Colormap olc_ColourMap; X11::XSetWindowAttributes olc_SetWindowAttribs; public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { XDestroyWindow(olc_Display, olc_Window); return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({ olc_Display, &olc_Window, olc_VisualInfo }, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { using namespace X11; XInitThreads(); // Grab the deafult display and window olc_Display = XOpenDisplay(NULL); olc_WindowRoot = DefaultRootWindow(olc_Display); // Based on the display capabilities, configure the appearance of the window GLint olc_GLAttribs[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; olc_VisualInfo = glXChooseVisual(olc_Display, 0, olc_GLAttribs); olc_ColourMap = XCreateColormap(olc_Display, olc_WindowRoot, olc_VisualInfo->visual, AllocNone); olc_SetWindowAttribs.colormap = olc_ColourMap; // Register which events we are interested in receiving olc_SetWindowAttribs.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask | StructureNotifyMask; // Create the window olc_Window = XCreateWindow(olc_Display, olc_WindowRoot, vWindowPos.x, vWindowPos.y, vWindowSize.x, vWindowSize.y, 0, olc_VisualInfo->depth, InputOutput, olc_VisualInfo->visual, CWColormap | CWEventMask, &olc_SetWindowAttribs); Atom wmDelete = XInternAtom(olc_Display, "WM_DELETE_WINDOW", true); XSetWMProtocols(olc_Display, olc_Window, &wmDelete, 1); XMapWindow(olc_Display, olc_Window); XStoreName(olc_Display, olc_Window, "OneLoneCoder.com - Pixel Game Engine"); if (bFullScreen) // Thanks DragonEye, again :D { Atom wm_state; Atom fullscreen; wm_state = XInternAtom(olc_Display, "_NET_WM_STATE", False); fullscreen = XInternAtom(olc_Display, "_NET_WM_STATE_FULLSCREEN", False); XEvent xev{ 0 }; xev.type = ClientMessage; xev.xclient.window = olc_Window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = (bFullScreen ? 1 : 0); // the action (0: off, 1: on, 2: toggle) xev.xclient.data.l[1] = fullscreen; // first property to alter xev.xclient.data.l[2] = 0; // second property to alter xev.xclient.data.l[3] = 0; // source indication XMapWindow(olc_Display, olc_Window); XSendEvent(olc_Display, DefaultRootWindow(olc_Display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(olc_Display); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, olc_Window, &gwa); vWindowSize.x = gwa.width; vWindowSize.y = gwa.height; } // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys[0x61] = Key::A; mapKeys[0x62] = Key::B; mapKeys[0x63] = Key::C; mapKeys[0x64] = Key::D; mapKeys[0x65] = Key::E; mapKeys[0x66] = Key::F; mapKeys[0x67] = Key::G; mapKeys[0x68] = Key::H; mapKeys[0x69] = Key::I; mapKeys[0x6A] = Key::J; mapKeys[0x6B] = Key::K; mapKeys[0x6C] = Key::L; mapKeys[0x6D] = Key::M; mapKeys[0x6E] = Key::N; mapKeys[0x6F] = Key::O; mapKeys[0x70] = Key::P; mapKeys[0x71] = Key::Q; mapKeys[0x72] = Key::R; mapKeys[0x73] = Key::S; mapKeys[0x74] = Key::T; mapKeys[0x75] = Key::U; mapKeys[0x76] = Key::V; mapKeys[0x77] = Key::W; mapKeys[0x78] = Key::X; mapKeys[0x79] = Key::Y; mapKeys[0x7A] = Key::Z; mapKeys[XK_F1] = Key::F1; mapKeys[XK_F2] = Key::F2; mapKeys[XK_F3] = Key::F3; mapKeys[XK_F4] = Key::F4; mapKeys[XK_F5] = Key::F5; mapKeys[XK_F6] = Key::F6; mapKeys[XK_F7] = Key::F7; mapKeys[XK_F8] = Key::F8; mapKeys[XK_F9] = Key::F9; mapKeys[XK_F10] = Key::F10; mapKeys[XK_F11] = Key::F11; mapKeys[XK_F12] = Key::F12; mapKeys[XK_Down] = Key::DOWN; mapKeys[XK_Left] = Key::LEFT; mapKeys[XK_Right] = Key::RIGHT; mapKeys[XK_Up] = Key::UP; mapKeys[XK_KP_Enter] = Key::ENTER; mapKeys[XK_Return] = Key::ENTER; mapKeys[XK_BackSpace] = Key::BACK; mapKeys[XK_Escape] = Key::ESCAPE; mapKeys[XK_Linefeed] = Key::ENTER; mapKeys[XK_Pause] = Key::PAUSE; mapKeys[XK_Scroll_Lock] = Key::SCROLL; mapKeys[XK_Tab] = Key::TAB; mapKeys[XK_Delete] = Key::DEL; mapKeys[XK_Home] = Key::HOME; mapKeys[XK_End] = Key::END; mapKeys[XK_Page_Up] = Key::PGUP; mapKeys[XK_Page_Down] = Key::PGDN; mapKeys[XK_Insert] = Key::INS; mapKeys[XK_Shift_L] = Key::SHIFT; mapKeys[XK_Shift_R] = Key::SHIFT; mapKeys[XK_Control_L] = Key::CTRL; mapKeys[XK_Control_R] = Key::CTRL; mapKeys[XK_space] = Key::SPACE; mapKeys[XK_period] = Key::PERIOD; mapKeys[XK_0] = Key::K0; mapKeys[XK_1] = Key::K1; mapKeys[XK_2] = Key::K2; mapKeys[XK_3] = Key::K3; mapKeys[XK_4] = Key::K4; mapKeys[XK_5] = Key::K5; mapKeys[XK_6] = Key::K6; mapKeys[XK_7] = Key::K7; mapKeys[XK_8] = Key::K8; mapKeys[XK_9] = Key::K9; mapKeys[XK_KP_0] = Key::NP0; mapKeys[XK_KP_1] = Key::NP1; mapKeys[XK_KP_2] = Key::NP2; mapKeys[XK_KP_3] = Key::NP3; mapKeys[XK_KP_4] = Key::NP4; mapKeys[XK_KP_5] = Key::NP5; mapKeys[XK_KP_6] = Key::NP6; mapKeys[XK_KP_7] = Key::NP7; mapKeys[XK_KP_8] = Key::NP8; mapKeys[XK_KP_9] = Key::NP9; mapKeys[XK_KP_Multiply] = Key::NP_MUL; mapKeys[XK_KP_Add] = Key::NP_ADD; mapKeys[XK_KP_Divide] = Key::NP_DIV; mapKeys[XK_KP_Subtract] = Key::NP_SUB; mapKeys[XK_KP_Decimal] = Key::NP_DECIMAL; // These keys vary depending on the keyboard. I've included comments for US and UK keyboard layouts mapKeys[XK_semicolon] = Key::OEM_1; // On US and UK keyboards this is the ';:' key mapKeys[XK_slash] = Key::OEM_2; // On US and UK keyboards this is the '/?' key mapKeys[XK_asciitilde] = Key::OEM_3; // On US keyboard this is the '~' key mapKeys[XK_bracketleft] = Key::OEM_4; // On US and UK keyboards this is the '[{' key mapKeys[XK_backslash] = Key::OEM_5; // On US keyboard this is '\|' key. mapKeys[XK_bracketright] = Key::OEM_6; // On US and UK keyboards this is the ']}' key mapKeys[XK_apostrophe] = Key::OEM_7; // On US keyboard this is the single/double quote key. On UK, this is the single quote/@ symbol key mapKeys[XK_numbersign] = Key::OEM_8; // miscellaneous characters. Varies by keyboard. I believe this to be the '#~' key on UK keyboards mapKeys[XK_equal] = Key::EQUALS; // the '+' key on any keyboard mapKeys[XK_comma] = Key::COMMA; // the comma key on any keyboard mapKeys[XK_minus] = Key::MINUS; // the minus key on any keyboard mapKeys[XK_Caps_Lock] = Key::CAPS_LOCK; return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { X11::XStoreName(olc_Display, olc_Window, s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { return olc::OK; } virtual olc::rcode HandleSystemEvent() override { using namespace X11; // Handle Xlib Message Loop - we do this in the // same thread that OpenGL was created so we dont // need to worry too much about multithreading with X11 XEvent xev; while (XPending(olc_Display)) { XNextEvent(olc_Display, &xev); if (xev.type == Expose) { XWindowAttributes gwa; XGetWindowAttributes(olc_Display, olc_Window, &gwa); ptrPGE->olc_UpdateWindowSize(gwa.width, gwa.height); } else if (xev.type == ConfigureNotify) { XConfigureEvent xce = xev.xconfigure; ptrPGE->olc_UpdateWindowSize(xce.width, xce.height); } else if (xev.type == KeyPress) { KeySym sym = XLookupKeysym(&xev.xkey, 0); ptrPGE->olc_UpdateKeyState(mapKeys[sym], true); XKeyEvent* e = (XKeyEvent*)&xev; // Because DragonEye loves numpads XLookupString(e, NULL, 0, &sym, NULL); ptrPGE->olc_UpdateKeyState(mapKeys[sym], true); } else if (xev.type == KeyRelease) { KeySym sym = XLookupKeysym(&xev.xkey, 0); ptrPGE->olc_UpdateKeyState(mapKeys[sym], false); XKeyEvent* e = (XKeyEvent*)&xev; XLookupString(e, NULL, 0, &sym, NULL); ptrPGE->olc_UpdateKeyState(mapKeys[sym], false); } else if (xev.type == ButtonPress) { switch (xev.xbutton.button) { case 1: ptrPGE->olc_UpdateMouseState(0, true); break; case 2: ptrPGE->olc_UpdateMouseState(2, true); break; case 3: ptrPGE->olc_UpdateMouseState(1, true); break; case 4: ptrPGE->olc_UpdateMouseWheel(120); break; case 5: ptrPGE->olc_UpdateMouseWheel(-120); break; default: break; } } else if (xev.type == ButtonRelease) { switch (xev.xbutton.button) { case 1: ptrPGE->olc_UpdateMouseState(0, false); break; case 2: ptrPGE->olc_UpdateMouseState(2, false); break; case 3: ptrPGE->olc_UpdateMouseState(1, false); break; default: break; } } else if (xev.type == MotionNotify) { ptrPGE->olc_UpdateMouse(xev.xmotion.x, xev.xmotion.y); } else if (xev.type == FocusIn) { ptrPGE->olc_UpdateKeyFocus(true); } else if (xev.type == FocusOut) { ptrPGE->olc_UpdateKeyFocus(false); } else if (xev.type == ClientMessage) { ptrPGE->olc_Terminate(); } } return olc::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: LINUX | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_glut // O------------------------------------------------------------------------------O // | START PLATFORM: GLUT (used to make it simple for Apple) | // O------------------------------------------------------------------------------O // // VERY IMPORTANT!!! The Apple port was originally created by @Mumflr (discord) // and the repo for the development of this project can be found here: // https://github.com/MumflrFumperdink/olcPGEMac which contains maccy goodness // and support on how to setup your build environment. // // "MASSIVE MASSIVE THANKS TO MUMFLR" - Javidx9 #if defined(OLC_PLATFORM_GLUT) namespace olc { class Platform_GLUT : public olc::Platform { public: static std::atomic<bool>* bActiveRef; virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({}, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } static void ExitMainLoop() { if (!ptrPGE->OnUserDestroy()) { *bActiveRef = true; return; } platform->ThreadCleanUp(); platform->ApplicationCleanUp(); exit(0); } static void ThreadFunct() { if (!*bActiveRef) { ExitMainLoop(); return; } glutPostRedisplay(); } static void DrawFunct() { ptrPGE->olc_CoreUpdate(); } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { renderer->PrepareDevice(); if (bFullScreen) { vWindowSize.x = glutGet(GLUT_SCREEN_WIDTH); vWindowSize.y = glutGet(GLUT_SCREEN_HEIGHT); glutFullScreen(); } if (vWindowSize.x > glutGet(GLUT_SCREEN_WIDTH) || vWindowSize.y > glutGet(GLUT_SCREEN_HEIGHT)) { perror("ERROR: The specified window dimensions do not fit on your screen\n"); return olc::FAIL; } // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys['A'] = Key::A; mapKeys['B'] = Key::B; mapKeys['C'] = Key::C; mapKeys['D'] = Key::D; mapKeys['E'] = Key::E; mapKeys['F'] = Key::F; mapKeys['G'] = Key::G; mapKeys['H'] = Key::H; mapKeys['I'] = Key::I; mapKeys['J'] = Key::J; mapKeys['K'] = Key::K; mapKeys['L'] = Key::L; mapKeys['M'] = Key::M; mapKeys['N'] = Key::N; mapKeys['O'] = Key::O; mapKeys['P'] = Key::P; mapKeys['Q'] = Key::Q; mapKeys['R'] = Key::R; mapKeys['S'] = Key::S; mapKeys['T'] = Key::T; mapKeys['U'] = Key::U; mapKeys['V'] = Key::V; mapKeys['W'] = Key::W; mapKeys['X'] = Key::X; mapKeys['Y'] = Key::Y; mapKeys['Z'] = Key::Z; mapKeys[GLUT_KEY_F1] = Key::F1; mapKeys[GLUT_KEY_F2] = Key::F2; mapKeys[GLUT_KEY_F3] = Key::F3; mapKeys[GLUT_KEY_F4] = Key::F4; mapKeys[GLUT_KEY_F5] = Key::F5; mapKeys[GLUT_KEY_F6] = Key::F6; mapKeys[GLUT_KEY_F7] = Key::F7; mapKeys[GLUT_KEY_F8] = Key::F8; mapKeys[GLUT_KEY_F9] = Key::F9; mapKeys[GLUT_KEY_F10] = Key::F10; mapKeys[GLUT_KEY_F11] = Key::F11; mapKeys[GLUT_KEY_F12] = Key::F12; mapKeys[GLUT_KEY_DOWN] = Key::DOWN; mapKeys[GLUT_KEY_LEFT] = Key::LEFT; mapKeys[GLUT_KEY_RIGHT] = Key::RIGHT; mapKeys[GLUT_KEY_UP] = Key::UP; mapKeys[13] = Key::ENTER; mapKeys[127] = Key::BACK; mapKeys[27] = Key::ESCAPE; mapKeys[9] = Key::TAB; mapKeys[GLUT_KEY_HOME] = Key::HOME; mapKeys[GLUT_KEY_END] = Key::END; mapKeys[GLUT_KEY_PAGE_UP] = Key::PGUP; mapKeys[GLUT_KEY_PAGE_DOWN] = Key::PGDN; mapKeys[GLUT_KEY_INSERT] = Key::INS; mapKeys[32] = Key::SPACE; mapKeys[46] = Key::PERIOD; mapKeys[48] = Key::K0; mapKeys[49] = Key::K1; mapKeys[50] = Key::K2; mapKeys[51] = Key::K3; mapKeys[52] = Key::K4; mapKeys[53] = Key::K5; mapKeys[54] = Key::K6; mapKeys[55] = Key::K7; mapKeys[56] = Key::K8; mapKeys[57] = Key::K9; // NOTE: MISSING KEYS :O glutKeyboardFunc([](unsigned char key, int x, int y) -> void { switch (glutGetModifiers()) { case 0: //This is when there are no modifiers if ('a' <= key && key <= 'z') key -= 32; break; case GLUT_ACTIVE_SHIFT: ptrPGE->olc_UpdateKeyState(Key::SHIFT, true); break; case GLUT_ACTIVE_CTRL: if ('a' <= key && key <= 'z') key -= 32; ptrPGE->olc_UpdateKeyState(Key::CTRL, true); break; case GLUT_ACTIVE_ALT: if ('a' <= key && key <= 'z') key -= 32; break; } if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], true); }); glutKeyboardUpFunc([](unsigned char key, int x, int y) -> void { switch (glutGetModifiers()) { case 0: //This is when there are no modifiers if ('a' <= key && key <= 'z') key -= 32; break; case GLUT_ACTIVE_SHIFT: ptrPGE->olc_UpdateKeyState(Key::SHIFT, false); break; case GLUT_ACTIVE_CTRL: if ('a' <= key && key <= 'z') key -= 32; ptrPGE->olc_UpdateKeyState(Key::CTRL, false); break; case GLUT_ACTIVE_ALT: if ('a' <= key && key <= 'z') key -= 32; //No ALT in PGE break; } if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], false); }); //Special keys glutSpecialFunc([](int key, int x, int y) -> void { if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], true); }); glutSpecialUpFunc([](int key, int x, int y) -> void { if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], false); }); glutMouseFunc([](int button, int state, int x, int y) -> void { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(0, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(0, true); break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(2, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(2, true); break; case GLUT_RIGHT_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(1, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(1, true); break; } }); auto mouseMoveCall = [](int x, int y) -> void { ptrPGE->olc_UpdateMouse(x, y); }; glutMotionFunc(mouseMoveCall); glutPassiveMotionFunc(mouseMoveCall); glutEntryFunc([](int state) -> void { if (state == GLUT_ENTERED) ptrPGE->olc_UpdateKeyFocus(true); else if (state == GLUT_LEFT) ptrPGE->olc_UpdateKeyFocus(false); }); glutDisplayFunc(DrawFunct); glutIdleFunc(ThreadFunct); return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { glutSetWindowTitle(s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { glutMainLoop(); return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::OK; } }; std::atomic<bool>* Platform_GLUT::bActiveRef{ nullptr }; //Custom Start olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); if (platform->ThreadStartUp() == olc::FAIL) return olc::FAIL; olc_PrepareEngine(); if (!OnUserCreate()) return olc::FAIL; Platform_GLUT::bActiveRef = &bAtomActive; glutWMCloseFunc(Platform_GLUT::ExitMainLoop); bAtomActive = true; platform->StartSystemEventLoop(); //This code will not even be run but why not if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: GLUT | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_emscripten // O------------------------------------------------------------------------------O // | START PLATFORM: Emscripten - Totally Game Changing... | // O------------------------------------------------------------------------------O // // Firstly a big mega thank you to members of the OLC Community for sorting this // out. Making a browser compatible version has been a priority for quite some // time, but I lacked the expertise to do it. This awesome feature is possible // because a group of former strangers got together and formed friendships over // their shared passion for code. If anything demonstrates how powerful helping // each other can be, it's this. - Javidx9 // Emscripten Platform: MaGetzUb, Moros1138, Slavka, Dandistine, Gorbit99, Bispoo // also: Ishidex, Gusgo99, SlicEnDicE, Alexio #if defined(OLC_PLATFORM_EMSCRIPTEN) #include <emscripten/html5.h> #include <emscripten/key_codes.h> extern "C" { EMSCRIPTEN_KEEPALIVE inline int olc_OnPageUnload() { olc::platform->ApplicationCleanUp(); return 0; } } namespace olc { class Platform_Emscripten : public olc::Platform { public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { ThreadCleanUp(); return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({}, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { emscripten_set_canvas_element_size("#canvas", vWindowSize.x, vWindowSize.y); mapKeys[DOM_PK_UNKNOWN] = Key::NONE; mapKeys[DOM_PK_A] = Key::A; mapKeys[DOM_PK_B] = Key::B; mapKeys[DOM_PK_C] = Key::C; mapKeys[DOM_PK_D] = Key::D; mapKeys[DOM_PK_E] = Key::E; mapKeys[DOM_PK_F] = Key::F; mapKeys[DOM_PK_G] = Key::G; mapKeys[DOM_PK_H] = Key::H; mapKeys[DOM_PK_I] = Key::I; mapKeys[DOM_PK_J] = Key::J; mapKeys[DOM_PK_K] = Key::K; mapKeys[DOM_PK_L] = Key::L; mapKeys[DOM_PK_M] = Key::M; mapKeys[DOM_PK_N] = Key::N; mapKeys[DOM_PK_O] = Key::O; mapKeys[DOM_PK_P] = Key::P; mapKeys[DOM_PK_Q] = Key::Q; mapKeys[DOM_PK_R] = Key::R; mapKeys[DOM_PK_S] = Key::S; mapKeys[DOM_PK_T] = Key::T; mapKeys[DOM_PK_U] = Key::U; mapKeys[DOM_PK_V] = Key::V; mapKeys[DOM_PK_W] = Key::W; mapKeys[DOM_PK_X] = Key::X; mapKeys[DOM_PK_Y] = Key::Y; mapKeys[DOM_PK_Z] = Key::Z; mapKeys[DOM_PK_0] = Key::K0; mapKeys[DOM_PK_1] = Key::K1; mapKeys[DOM_PK_2] = Key::K2; mapKeys[DOM_PK_3] = Key::K3; mapKeys[DOM_PK_4] = Key::K4; mapKeys[DOM_PK_5] = Key::K5; mapKeys[DOM_PK_6] = Key::K6; mapKeys[DOM_PK_7] = Key::K7; mapKeys[DOM_PK_8] = Key::K8; mapKeys[DOM_PK_9] = Key::K9; mapKeys[DOM_PK_F1] = Key::F1; mapKeys[DOM_PK_F2] = Key::F2; mapKeys[DOM_PK_F3] = Key::F3; mapKeys[DOM_PK_F4] = Key::F4; mapKeys[DOM_PK_F5] = Key::F5; mapKeys[DOM_PK_F6] = Key::F6; mapKeys[DOM_PK_F7] = Key::F7; mapKeys[DOM_PK_F8] = Key::F8; mapKeys[DOM_PK_F9] = Key::F9; mapKeys[DOM_PK_F10] = Key::F10; mapKeys[DOM_PK_F11] = Key::F11; mapKeys[DOM_PK_F12] = Key::F12; mapKeys[DOM_PK_ARROW_UP] = Key::UP; mapKeys[DOM_PK_ARROW_DOWN] = Key::DOWN; mapKeys[DOM_PK_ARROW_LEFT] = Key::LEFT; mapKeys[DOM_PK_ARROW_RIGHT] = Key::RIGHT; mapKeys[DOM_PK_SPACE] = Key::SPACE; mapKeys[DOM_PK_TAB] = Key::TAB; mapKeys[DOM_PK_SHIFT_LEFT] = Key::SHIFT; mapKeys[DOM_PK_SHIFT_RIGHT] = Key::SHIFT; mapKeys[DOM_PK_CONTROL_LEFT] = Key::CTRL; mapKeys[DOM_PK_CONTROL_RIGHT] = Key::CTRL; mapKeys[DOM_PK_INSERT] = Key::INS; mapKeys[DOM_PK_DELETE] = Key::DEL; mapKeys[DOM_PK_HOME] = Key::HOME; mapKeys[DOM_PK_END] = Key::END; mapKeys[DOM_PK_PAGE_UP] = Key::PGUP; mapKeys[DOM_PK_PAGE_DOWN] = Key::PGDN; mapKeys[DOM_PK_BACKSPACE] = Key::BACK; mapKeys[DOM_PK_ESCAPE] = Key::ESCAPE; mapKeys[DOM_PK_ENTER] = Key::ENTER; mapKeys[DOM_PK_NUMPAD_EQUAL] = Key::EQUALS; mapKeys[DOM_PK_NUMPAD_ENTER] = Key::ENTER; mapKeys[DOM_PK_PAUSE] = Key::PAUSE; mapKeys[DOM_PK_SCROLL_LOCK] = Key::SCROLL; mapKeys[DOM_PK_NUMPAD_0] = Key::NP0; mapKeys[DOM_PK_NUMPAD_1] = Key::NP1; mapKeys[DOM_PK_NUMPAD_2] = Key::NP2; mapKeys[DOM_PK_NUMPAD_3] = Key::NP3; mapKeys[DOM_PK_NUMPAD_4] = Key::NP4; mapKeys[DOM_PK_NUMPAD_5] = Key::NP5; mapKeys[DOM_PK_NUMPAD_6] = Key::NP6; mapKeys[DOM_PK_NUMPAD_7] = Key::NP7; mapKeys[DOM_PK_NUMPAD_8] = Key::NP8; mapKeys[DOM_PK_NUMPAD_9] = Key::NP9; mapKeys[DOM_PK_NUMPAD_MULTIPLY] = Key::NP_MUL; mapKeys[DOM_PK_NUMPAD_DIVIDE] = Key::NP_DIV; mapKeys[DOM_PK_NUMPAD_ADD] = Key::NP_ADD; mapKeys[DOM_PK_NUMPAD_SUBTRACT] = Key::NP_SUB; mapKeys[DOM_PK_NUMPAD_DECIMAL] = Key::NP_DECIMAL; mapKeys[DOM_PK_PERIOD] = Key::PERIOD; mapKeys[DOM_PK_EQUAL] = Key::EQUALS; mapKeys[DOM_PK_COMMA] = Key::COMMA; mapKeys[DOM_PK_MINUS] = Key::MINUS; mapKeys[DOM_PK_CAPS_LOCK] = Key::CAPS_LOCK; mapKeys[DOM_PK_SEMICOLON] = Key::OEM_1; mapKeys[DOM_PK_SLASH] = Key::OEM_2; mapKeys[DOM_PK_BACKQUOTE] = Key::OEM_3; mapKeys[DOM_PK_BRACKET_LEFT] = Key::OEM_4; mapKeys[DOM_PK_BACKSLASH] = Key::OEM_5; mapKeys[DOM_PK_BRACKET_RIGHT] = Key::OEM_6; mapKeys[DOM_PK_QUOTE] = Key::OEM_7; mapKeys[DOM_PK_BACKSLASH] = Key::OEM_8; // Keyboard Callbacks emscripten_set_keydown_callback("#canvas", 0, 1, keyboard_callback); emscripten_set_keyup_callback("#canvas", 0, 1, keyboard_callback); // Mouse Callbacks emscripten_set_wheel_callback("#canvas", 0, 1, wheel_callback); emscripten_set_mousedown_callback("#canvas", 0, 1, mouse_callback); emscripten_set_mouseup_callback("#canvas", 0, 1, mouse_callback); emscripten_set_mousemove_callback("#canvas", 0, 1, mouse_callback); // Touch Callbacks emscripten_set_touchstart_callback("#canvas", 0, 1, touch_callback); emscripten_set_touchmove_callback("#canvas", 0, 1, touch_callback); emscripten_set_touchend_callback("#canvas", 0, 1, touch_callback); // Canvas Focus Callbacks emscripten_set_blur_callback("#canvas", 0, 1, focus_callback); emscripten_set_focus_callback("#canvas", 0, 1, focus_callback); #pragma warning disable format EM_ASM(window.onunload = Module._olc_OnPageUnload; ); // IMPORTANT! - Sorry About This... // // In order to handle certain browser based events, such as resizing and // going to full screen, we have to effectively inject code into the container // running the PGE. Yes, I vomited about 11 times too when the others were // convincing me this is the future. Well, this isnt the future, and if it // were to be, I want no part of what must be a miserable distopian free // for all of anarchic code injection to get rudimentary events like "Resize()". // // Wake up people! Of course theres a spoon. There has to be to keep feeding // the giant web baby. // Fullscreen and Resize Observers EM_ASM({ // cache for reuse Module._olc_EmscriptenShellCss = "width: 100%; height: 70vh; margin-left: auto; margin-right: auto;"; // width / height = aspect ratio Module._olc_WindowAspectRatio = $0 / $1; Module.canvas.parentNode.addEventListener("resize", (e) = > { if (e.defaultPrevented) { e.stopPropagation(); return; } var viewWidth = e.detail.width; var viewHeight = e.detail.width / Module._olc_WindowAspectRatio; if (viewHeight > e.detail.height) { viewHeight = e.detail.height; viewWidth = e.detail.height * Module._olc_WindowAspectRatio; } if (Module.canvas.parentNode.className == 'emscripten_border') Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss + " width: " + viewWidth.toString() + "px; height: " + viewHeight.toString() + "px;"; Module.canvas.setAttribute("width", viewWidth); Module.canvas.setAttribute("height", viewHeight); if (document.fullscreenElement != null) { var top = (e.detail.height - viewHeight) / 2; var left = (e.detail.width - viewWidth) / 2; Module.canvas.style.position = "fixed"; Module.canvas.style.top = top.toString() + "px"; Module.canvas.style.left = left.toString() + "px"; Module.canvas.style.width = ""; Module.canvas.style.height = ""; } // trigger PGE update Module._olc_PGE_UpdateWindowSize(viewWidth, viewHeight); // this is really only needed when enter/exiting fullscreen Module.canvas.focus(); // prevent this event from ever affecting the document beyond this element e.stopPropagation(); }); // helper function to prevent repeating the same code everywhere Module._olc_ResizeCanvas = () = > { // yes, we still have to wait, sigh.. setTimeout(() = > { // if default template, stretch width as well if (Module.canvas.parentNode.className == 'emscripten_border') Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss; // override it's styling so we can get it's stretched size Module.canvas.style.cssText = "width: 100%; height: 100%; outline: none;"; // setup custom resize event var resizeEvent = new CustomEvent('resize', { detail: { width: Module.canvas.clientWidth, height : Module.canvas.clientHeight }, bubbles : true, cancelable : true }); // trigger custom resize event on canvas element Module.canvas.dispatchEvent(resizeEvent); }, 50); }; // Disable Refresh Gesture on mobile document.body.style.cssText += " overscroll-behavior-y: contain;"; if (Module.canvas.parentNode.className == 'emscripten_border') { // force body to have no margin in emscripten's minimal shell document.body.style.margin = "0"; Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss; } Module._olc_ResizeCanvas(); // observe and react to resizing of the container element var resizeObserver = new ResizeObserver((entries) = > {Module._olc_ResizeCanvas(); }).observe(Module.canvas.parentNode); // observe and react to changes that occur when entering/exiting fullscreen var mutationObserver = new MutationObserver((mutationsList, observer) = > { // a change has occurred, let's check them out! for (var i = 0; i < mutationsList.length; i++) { // cycle through all of the newly added elements for (var j = 0; j < mutationsList[i].addedNodes.length; j++) { // if this element is a our canvas, trigger resize if (mutationsList[i].addedNodes[j].id == 'canvas') Module._olc_ResizeCanvas(); } } }).observe(Module.canvas.parentNode, { attributes: false, childList : true, subtree : false }); // add resize listener on window window.addEventListener("resize", (e) = > { Module._olc_ResizeCanvas(); }); }, vWindowSize.x, vWindowSize.y); // Fullscreen and Resize Observers #pragma warning restore format return olc::rcode::OK; } // Interface PGE's UpdateWindowSize, for use in Javascript void UpdateWindowSize(int width, int height) { ptrPGE->olc_UpdateWindowSize(width, height); } //TY Gorbit static EM_BOOL focus_callback(int eventType, const EmscriptenFocusEvent* focusEvent, void* userData) { if (eventType == EMSCRIPTEN_EVENT_BLUR) { ptrPGE->olc_UpdateKeyFocus(false); ptrPGE->olc_UpdateMouseFocus(false); } else if (eventType == EMSCRIPTEN_EVENT_FOCUS) { ptrPGE->olc_UpdateKeyFocus(true); ptrPGE->olc_UpdateMouseFocus(true); } return 0; } //TY Moros static EM_BOOL keyboard_callback(int eventType, const EmscriptenKeyboardEvent* e, void* userData) { if (eventType == EMSCRIPTEN_EVENT_KEYDOWN) ptrPGE->olc_UpdateKeyState(mapKeys[emscripten_compute_dom_pk_code(e->code)], true); // THANK GOD!! for this compute function. And thanks Dandistine for pointing it out! if (eventType == EMSCRIPTEN_EVENT_KEYUP) ptrPGE->olc_UpdateKeyState(mapKeys[emscripten_compute_dom_pk_code(e->code)], false); //Consume keyboard events so that keys like F1 and F5 don't do weird things return EM_TRUE; } //TY Moros static EM_BOOL wheel_callback(int eventType, const EmscriptenWheelEvent* e, void* userData) { if (eventType == EMSCRIPTEN_EVENT_WHEEL) ptrPGE->olc_UpdateMouseWheel(-1 * e->deltaY); return EM_TRUE; } //TY Bispoo static EM_BOOL touch_callback(int eventType, const EmscriptenTouchEvent* e, void* userData) { // Move if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) { ptrPGE->olc_UpdateMouse(e->touches->targetX, e->touches->targetY); } // Start if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) { ptrPGE->olc_UpdateMouse(e->touches->targetX, e->touches->targetY); ptrPGE->olc_UpdateMouseState(0, true); } // End if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) { ptrPGE->olc_UpdateMouseState(0, false); } return EM_TRUE; } //TY Moros static EM_BOOL mouse_callback(int eventType, const EmscriptenMouseEvent* e, void* userData) { //Mouse Movement if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE) ptrPGE->olc_UpdateMouse(e->targetX, e->targetY); //Mouse button press if (e->button == 0) // left click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(0, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(0, false); } if (e->button == 2) // right click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(1, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(1, false); } if (e->button == 1) // middle click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(2, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(2, false); //at the moment only middle mouse needs to consume events. return EM_TRUE; } return EM_FALSE; } virtual olc::rcode SetWindowTitle(const std::string& s) override { emscripten_set_window_title(s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::OK; } static void MainLoop() { olc::Platform::ptrPGE->olc_CoreUpdate(); if (!ptrPGE->olc_IsRunning()) { if (ptrPGE->OnUserDestroy()) { emscripten_cancel_main_loop(); platform->ApplicationCleanUp(); } else { ptrPGE->olc_Reanimate(); } } } }; //Emscripten needs a special Start function //Much of this is usually done in EngineThread, but that isn't used here olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); // Some implementations may form an event loop here if (platform->ThreadStartUp() == olc::FAIL) return olc::FAIL; // Do engine context specific initialisation olc_PrepareEngine(); // Consider the "thread" started bAtomActive = true; // Create user resources as part of this thread for (auto& ext : vExtensions) ext->OnBeforeUserCreate(); if (!OnUserCreate()) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserCreate(); platform->StartSystemEventLoop(); //This causes a heap memory corruption in Emscripten for some reason //Platform_Emscripten::bActiveRef = &bAtomActive; emscripten_set_main_loop(&Platform_Emscripten::MainLoop, 0, 1); // Wait for thread to be exited if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } } extern "C" { EMSCRIPTEN_KEEPALIVE inline void olc_PGE_UpdateWindowSize(int width, int height) { emscripten_set_canvas_element_size("#canvas", width, height); // Thanks slavka ((olc::Platform_Emscripten*)olc::platform.get())->UpdateWindowSize(width, height); } } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: Emscripten | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Auto-Configuration | // O------------------------------------------------------------------------------O #pragma region pge_config namespace olc { void PixelGameEngine::olc_ConfigureSystem() { #if defined(OLC_IMAGE_GDI) olc::Sprite::loader = std::make_unique<olc::ImageLoader_GDIPlus>(); #endif #if defined(OLC_IMAGE_LIBPNG) olc::Sprite::loader = std::make_unique<olc::ImageLoader_LibPNG>(); #endif #if defined(OLC_IMAGE_STB) olc::Sprite::loader = std::make_unique<olc::ImageLoader_STB>(); #endif #if defined(OLC_IMAGE_CUSTOM_EX) olc::Sprite::loader = std::make_unique<OLC_IMAGE_CUSTOM_EX>(); #endif #if defined(OLC_PLATFORM_WINAPI) platform = std::make_unique<olc::Platform_Windows>(); #endif #if defined(OLC_PLATFORM_X11) platform = std::make_unique<olc::Platform_Linux>(); #endif #if defined(OLC_PLATFORM_GLUT) platform = std::make_unique<olc::Platform_GLUT>(); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) platform = std::make_unique<olc::Platform_Emscripten>(); #endif #if defined(OLC_PLATFORM_CUSTOM_EX) platform = std::make_unique<OLC_PLATFORM_CUSTOM_EX>(); #endif #if defined(OLC_GFX_OPENGL10) renderer = std::make_unique<olc::Renderer_OGL10>(); #endif #if defined(OLC_GFX_OPENGL33) renderer = std::make_unique<olc::Renderer_OGL33>(); #endif #if defined(OLC_GFX_OPENGLES2) renderer = std::make_unique<olc::Renderer_OGLES2>(); #endif #if defined(OLC_GFX_DIRECTX10) renderer = std::make_unique<olc::Renderer_DX10>(); #endif #if defined(OLC_GFX_DIRECTX11) renderer = std::make_unique<olc::Renderer_DX11>(); #endif #if defined(OLC_GFX_CUSTOM_EX) renderer = std::make_unique<OLC_RENDERER_CUSTOM_EX>(); #endif // Associate components with PGE instance platform->ptrPGE = this; renderer->ptrPGE = this; } } #pragma endregion #endif // End OLC_PGE_APPLICATION // O------------------------------------------------------------------------------O // | END OF OLC_PGE_APPLICATION | // O------------------------------------------------------------------------------O
[ "21dynamicjustin@gmail.com" ]
21dynamicjustin@gmail.com
4bb2c1b95373a97df3755d317cffa1a8bf64c2df
297173bfae1e4047f62f24575f0aecd5fc37ad8d
/core/variant/variant_destruct.cpp
366b71df3a08b4429b1eb566dff722975e476470
[ "LicenseRef-scancode-unicode", "GPL-3.0-or-later", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-nvidia-2002", "MIT", "LicenseRef-scancode-other-permissive", "CC-BY-4.0", "FTL", "OFL-1.1", "Bison-exception-2.2", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSL-1.0", "Apa...
permissive
hbina/godot
29c5e330a1aa93a3b438a76b8680b95a9e6b0755
dbef4bbd98b655d6f89601c9e44c679b373b3628
refs/heads/master
2023-03-19T19:22:27.316026
2021-11-22T18:43:55
2021-11-22T18:43:55
184,989,149
0
0
MIT
2023-03-06T13:56:52
2019-05-05T06:28:33
C++
UTF-8
C++
false
false
3,972
cpp
/*************************************************************************/ /* variant_destruct.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "variant_destruct.h" #include "core/templates/local_vector.h" static Variant::PTRDestructor destruct_pointers[Variant::VARIANT_MAX] = { nullptr }; template <class T> static void add_destructor() { destruct_pointers[T::get_base_type()] = T::ptr_destruct; } void Variant::_register_variant_destructors() { add_destructor<VariantDestruct<String>>(); add_destructor<VariantDestruct<Transform2D>>(); add_destructor<VariantDestruct<::AABB>>(); add_destructor<VariantDestruct<Basis>>(); add_destructor<VariantDestruct<Transform3D>>(); add_destructor<VariantDestruct<StringName>>(); add_destructor<VariantDestruct<NodePath>>(); add_destructor<VariantDestruct<::RID>>(); add_destructor<VariantDestruct<Callable>>(); add_destructor<VariantDestruct<Signal>>(); add_destructor<VariantDestruct<Dictionary>>(); add_destructor<VariantDestruct<Array>>(); add_destructor<VariantDestruct<PackedByteArray>>(); add_destructor<VariantDestruct<PackedInt32Array>>(); add_destructor<VariantDestruct<PackedInt64Array>>(); add_destructor<VariantDestruct<PackedFloat32Array>>(); add_destructor<VariantDestruct<PackedFloat64Array>>(); add_destructor<VariantDestruct<PackedStringArray>>(); add_destructor<VariantDestruct<PackedVector2Array>>(); add_destructor<VariantDestruct<PackedVector3Array>>(); add_destructor<VariantDestruct<PackedColorArray>>(); } void Variant::_unregister_variant_destructors() { // Nothing to be done. } Variant::PTRDestructor Variant::get_ptr_destructor(Variant::Type p_type) { ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, nullptr); return destruct_pointers[p_type]; } bool Variant::has_destructor(Variant::Type p_type) { ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, false); return destruct_pointers[p_type] != nullptr; }
[ "george@gmarqu.es" ]
george@gmarqu.es
891886fc87c5b28424cabbc6279fcf9a9e9803d4
9d684073707de7b6c1eff7c2f36ef53dd137655d
/qcom-caf/msm8952/display/libhwcomposer/hwc_utils.cpp
1456ea5b4dc3ee1653ecc3d06af6d2d485b01f2e
[]
no_license
segfault2k/stuff
a8f1e5f4a9b023ba3c20b25e28b618dd0d7177b2
591a8cd382791c970fc75a41428be76bef98e375
refs/heads/master
2023-06-27T21:14:22.355725
2021-08-04T22:33:55
2021-08-04T22:33:55
382,970,191
0
2
null
null
null
null
UTF-8
C++
false
false
122,911
cpp
/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2012-2014,2016, The Linux Foundation All rights reserved. * * Not a Contribution, Apache license notifications and license are retained * for attribution purposes only. * * 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 ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL) #define HWC_UTILS_DEBUG 0 #include <math.h> #include <sys/ioctl.h> #include <linux/fb.h> #include <binder/IServiceManager.h> #include <EGL/egl.h> #include <cutils/properties.h> #include <utils/Trace.h> #include <gralloc_priv.h> #include <overlay.h> #include <overlayRotator.h> #include <overlayWriteback.h> #include <overlayCursor.h> #include "hwc_utils.h" #include "hwc_mdpcomp.h" #include "hwc_fbupdate.h" #include "hwc_ad.h" #include "mdp_version.h" #include "hwc_copybit.h" #include "hwc_dump_layers.h" #include "hdmi.h" #include "hwc_qclient.h" #include "QService.h" #include "comptype.h" #include "hwc_virtual.h" #include "qd_utils.h" #include "hwc_qdcm.h" #include <sys/sysinfo.h> #include <dlfcn.h> #include <video/msm_hdmi_modes.h> using namespace qClient; using namespace qService; using namespace android; using namespace overlay; using namespace overlay::utils; using namespace qQdcm; namespace ovutils = overlay::utils; #ifdef QTI_BSP #define EGL_GPU_HINT_1 0x32D0 #define EGL_GPU_HINT_2 0x32D1 #define EGL_GPU_LEVEL_0 0x0 #define EGL_GPU_LEVEL_1 0x1 #define EGL_GPU_LEVEL_2 0x2 #define EGL_GPU_LEVEL_3 0x3 #define EGL_GPU_LEVEL_4 0x4 #define EGL_GPU_LEVEL_5 0x5 #endif #define PROP_DEFAULT_APPBUFFER "hw.sf.app_buff_count" #define MAX_RAM_SIZE 512*1024*1024 #define qHD_WIDTH 540 namespace qhwc { // Std refresh rates for digital videos- 24p, 30p, 48p and 60p uint32_t stdRefreshRates[] = { 30, 24, 48, 60 }; static uint32_t getFBformat(fb_var_screeninfo /*vinfo*/) { uint32_t fbformat = HAL_PIXEL_FORMAT_RGBA_8888; #ifdef GET_FRAMEBUFFER_FORMAT_FROM_HWC // Here, we are adding the formats that are supported by both GPU and MDP. // The formats that fall in this category are RGBA_8888, RGB_565, RGB_888 switch(vinfo.bits_per_pixel) { case 16: fbformat = HAL_PIXEL_FORMAT_RGB_565; break; case 24: if ((vinfo.transp.offset == 0) && (vinfo.transp.length == 0)) fbformat = HAL_PIXEL_FORMAT_RGB_888; break; case 32: if ((vinfo.red.offset == 0) && (vinfo.green.offset == 8) && (vinfo.blue.offset == 16) && (vinfo.transp.offset == 24)) fbformat = HAL_PIXEL_FORMAT_RGBA_8888; break; default: fbformat = HAL_PIXEL_FORMAT_RGBA_8888; } #endif return fbformat; } bool isValidResolution(hwc_context_t *ctx, uint32_t xres, uint32_t yres) { return !((xres > qdutils::MDPVersion::getInstance().getMaxPipeWidth() && !isDisplaySplit(ctx, HWC_DISPLAY_PRIMARY)) || (xres < MIN_DISPLAY_XRES || yres < MIN_DISPLAY_YRES)); } static void handleFbScaling(hwc_context_t *ctx, int xresPanel, int yresPanel, int width, int height) { const int dpy = HWC_DISPLAY_PRIMARY; //Store original display resolution. ctx->dpyAttr[dpy].xresFB = xresPanel; ctx->dpyAttr[dpy].yresFB = yresPanel; ctx->dpyAttr[dpy].fbScaling = false; char property[PROPERTY_VALUE_MAX] = {'\0'}; char *yptr = NULL; if (property_get("debug.hwc.fbsize", property, NULL) > 0) { yptr = strcasestr(property,"x"); if(yptr) { int xresFB = atoi(property); int yresFB = atoi(yptr + 1); if (isValidResolution(ctx, xresFB, yresFB) && xresFB != xresPanel && yresFB != yresPanel) { ctx->dpyAttr[dpy].xresFB = xresFB; ctx->dpyAttr[dpy].yresFB = yresFB; ctx->dpyAttr[dpy].fbScaling = true; //Calculate DPI according to changed resolution. float xdpi = ((float)xresFB * 25.4f) / (float)width; float ydpi = ((float)yresFB * 25.4f) / (float)height; ctx->dpyAttr[dpy].xdpi = xdpi; ctx->dpyAttr[dpy].ydpi = ydpi; } } } ctx->dpyAttr[dpy].fbWidthScaleRatio = (float) ctx->dpyAttr[dpy].xres / (float) ctx->dpyAttr[dpy].xresFB; ctx->dpyAttr[dpy].fbHeightScaleRatio = (float) ctx->dpyAttr[dpy].yres / (float) ctx->dpyAttr[dpy].yresFB; } // Initialize hdmi display attributes based on // hdmi display class state void updateDisplayInfo(hwc_context_t* ctx, int dpy) { struct fb_var_screeninfo info; if (ioctl(ctx->mHDMIDisplay->getFd(), FBIOGET_VSCREENINFO, &info) == -1) { ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__, strerror(errno)); } ctx->dpyAttr[dpy].fbformat = getFBformat(info); ctx->dpyAttr[dpy].fd = ctx->mHDMIDisplay->getFd(); ctx->dpyAttr[dpy].xres = ctx->mHDMIDisplay->getWidth(); ctx->dpyAttr[dpy].yres = ctx->mHDMIDisplay->getHeight(); ctx->dpyAttr[dpy].mMDPScalingMode = ctx->mHDMIDisplay->getMDPScalingMode(); ctx->dpyAttr[dpy].vsync_period = ctx->mHDMIDisplay->getVsyncPeriod(); //FIXME: for now assume HDMI as secure //Will need to read the HDCP status from the driver //and update this accordingly ctx->dpyAttr[dpy].secure = true; ctx->mViewFrame[dpy].left = 0; ctx->mViewFrame[dpy].top = 0; ctx->mViewFrame[dpy].right = ctx->dpyAttr[dpy].xres; ctx->mViewFrame[dpy].bottom = ctx->dpyAttr[dpy].yres; } // Reset hdmi display attributes and list stats structures void resetDisplayInfo(hwc_context_t* ctx, int dpy) { memset(&(ctx->dpyAttr[dpy]), 0, sizeof(ctx->dpyAttr[dpy])); memset(&(ctx->listStats[dpy]), 0, sizeof(ctx->listStats[dpy])); // We reset the fd to -1 here but External display class is responsible // for it when the display is disconnected. This is handled as part of // EXTERNAL_OFFLINE event. ctx->dpyAttr[dpy].fd = -1; } // Initialize composition resources void initCompositionResources(hwc_context_t* ctx, int dpy) { ctx->mFBUpdate[dpy] = IFBUpdate::getObject(ctx, dpy); ctx->mMDPComp[dpy] = MDPComp::getObject(ctx, dpy); } void destroyCompositionResources(hwc_context_t* ctx, int dpy) { if(ctx->mFBUpdate[dpy]) { delete ctx->mFBUpdate[dpy]; ctx->mFBUpdate[dpy] = NULL; } if(ctx->mMDPComp[dpy]) { delete ctx->mMDPComp[dpy]; ctx->mMDPComp[dpy] = NULL; } } static int openFramebufferDevice(hwc_context_t *ctx) { struct fb_fix_screeninfo finfo; struct fb_var_screeninfo info; int fb_fd = openFb(HWC_DISPLAY_PRIMARY); if(fb_fd < 0) { ALOGE("%s: Error Opening FB : %s", __FUNCTION__, strerror(errno)); return -errno; } if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1) { ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__, strerror(errno)); close(fb_fd); return -errno; } if (int(info.width) <= 0 || int(info.height) <= 0) { // the driver doesn't return that information // default to 160 dpi info.width = (int)(((float)info.xres * 25.4f)/160.0f + 0.5f); info.height = (int)(((float)info.yres * 25.4f)/160.0f + 0.5f); } float xdpi = ((float)info.xres * 25.4f) / (float)info.width; float ydpi = ((float)info.yres * 25.4f) / (float)info.height; #ifdef MSMFB_METADATA_GET struct msmfb_metadata metadata; memset(&metadata, 0 , sizeof(metadata)); metadata.op = metadata_op_frame_rate; if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) { ALOGE("%s:Error retrieving panel frame rate: %s", __FUNCTION__, strerror(errno)); close(fb_fd); return -errno; } float fps = (float)metadata.data.panel_frame_rate; #else //XXX: Remove reserved field usage on all baselines //The reserved[3] field is used to store FPS by the driver. float fps = info.reserved[3] & 0xFF; #endif if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1) { ALOGE("%s:Error in ioctl FBIOGET_FSCREENINFO: %s", __FUNCTION__, strerror(errno)); close(fb_fd); return -errno; } ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd; //xres, yres may not be 32 aligned ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8); ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].refreshRate = (uint32_t)fps; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].dynRefreshRate = (uint32_t)fps; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].secure = true; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = (uint32_t)(1000000000l / fps); ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fbformat = getFBformat(info); handleFbScaling(ctx, info.xres, info.yres, info.width, info.height); //Unblank primary on first boot if(ioctl(fb_fd, FBIOBLANK,FB_BLANK_UNBLANK) < 0) { ALOGE("%s: Failed to unblank display", __FUNCTION__); return -errno; } ctx->dpyAttr[HWC_DISPLAY_PRIMARY].isActive = true; return 0; } static void changeDefaultAppBufferCount() { struct sysinfo info; unsigned long int ramSize = 0; if (!sysinfo(&info)) { ramSize = info.totalram ; } int fb_fd = -1; struct fb_var_screeninfo sInfo ={0}; fb_fd = open("/dev/graphics/fb0", O_RDONLY); if (fb_fd >=0) { ioctl(fb_fd, FBIOGET_VSCREENINFO, &sInfo); close(fb_fd); } if ((ramSize && ramSize < MAX_RAM_SIZE) && (sInfo.xres && sInfo.xres <= qHD_WIDTH )) { property_set(PROP_DEFAULT_APPBUFFER, "3"); } } int initContext(hwc_context_t *ctx) { int error = -1; int compositionType = 0; //Right now hwc starts the service but anybody could do it, or it could be //independent process as well. QService::init(); sp<IQClient> client = new QClient(ctx); sp<IQService> iqs = interface_cast<IQService>( defaultServiceManager()->getService( String16("display.qservice"))); if (iqs.get()) { iqs->connect(client); ctx->mQService = reinterpret_cast<QService* >(iqs.get()); } else { ALOGE("%s: Failed to acquire service pointer", __FUNCTION__); return error; } overlay::Overlay::initOverlay(); ctx->dpyAttr[HWC_DISPLAY_PRIMARY].isPluggable = qdutils::MDPVersion::getInstance().isPluggable(); ctx->mHDMIDisplay = new HDMIDisplay(); uint32_t priW = 0, priH = 0; // 1. HDMI as Primary // -If HDMI cable is connected, read display configs from edid data // -If HDMI cable is not connected then use default data in vscreeninfo // 2. HDMI as External // -Initialize HDMI class for use with external display // -Use vscreeninfo to populate display configs if(isPrimaryPluggable(ctx)) { int connected = ctx->mHDMIDisplay->getConnectedState(); if (connected == 1) { error = ctx->mHDMIDisplay->configure(); if (error < 0) { goto OpenFBError; } updateDisplayInfo(ctx, HWC_DISPLAY_PRIMARY); ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = true; } else { error = openFramebufferDevice(ctx); if(error < 0) { goto OpenFBError; } ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = false; } } else { error = openFramebufferDevice(ctx); if(error < 0) { goto OpenFBError; } ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = true; // Send the primary resolution to the hdmi display class // to be used for MDP scaling functionality priW = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres; priH = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres; ctx->mHDMIDisplay->setPrimaryAttributes(priW, priH); } char value[PROPERTY_VALUE_MAX]; ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion(); ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay(); ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType(); ctx->mOverlay = overlay::Overlay::getInstance(); ctx->mRotMgr = RotMgr::getInstance(); ctx->mBWCEnabled = qdutils::MDPVersion::getInstance().supportsBWC(); //default_app_buffer for ferrum if (ctx->mMDP.version == qdutils::MDP_V3_0_5) { changeDefaultAppBufferCount(); } // Initialize composition objects for the primary display initCompositionResources(ctx, HWC_DISPLAY_PRIMARY); // Check if the target supports copybit compostion (dyn/mdp) to // decide if we need to open the copybit module. compositionType = qdutils::QCCompositionType::getInstance().getCompositionType(); // Only MDP copybit is used if ((compositionType & (qdutils::COMPOSITION_TYPE_DYN | qdutils::COMPOSITION_TYPE_MDP)) && ((qdutils::MDPVersion::getInstance().getMDPVersion() == qdutils::MDP_V3_0_4) || (qdutils::MDPVersion::getInstance().getMDPVersion() == qdutils::MDP_V3_0_5))) { ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit(ctx, HWC_DISPLAY_PRIMARY); } ctx->mHWCVirtual = new HWCVirtualVDS(); ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive = false; ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected = false; ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isActive = false; ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected = false; ctx->dpyAttr[HWC_DISPLAY_PRIMARY].mMDPScalingMode= false; ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].mMDPScalingMode = false; ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].mMDPScalingMode = false; //Initialize the primary display viewFrame info ctx->mViewFrame[HWC_DISPLAY_PRIMARY].left = 0; ctx->mViewFrame[HWC_DISPLAY_PRIMARY].top = 0; ctx->mViewFrame[HWC_DISPLAY_PRIMARY].right = (int)ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres; ctx->mViewFrame[HWC_DISPLAY_PRIMARY].bottom = (int)ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres; for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) { ctx->mHwcDebug[i] = new HwcDebug(i); ctx->mLayerRotMap[i] = new LayerRotMap(); ctx->mAnimationState[i] = ANIMATION_STOPPED; ctx->dpyAttr[i].mActionSafePresent = false; ctx->dpyAttr[i].mAsWidthRatio = 0; ctx->dpyAttr[i].mAsHeightRatio = 0; ctx->dpyAttr[i].s3dMode = HDMI_S3D_NONE; ctx->dpyAttr[i].s3dModeForced = false; } //Make sure that the 3D mode is unset at bootup //This makes sure that the state is accurate on framework reboots ctx->mHDMIDisplay->configure3D(HDMI_S3D_NONE); for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) { ctx->mPrevHwLayerCount[i] = 0; } MDPComp::init(ctx); ctx->mAD = new AssertiveDisplay(ctx); ctx->vstate.enable = false; ctx->vstate.fakevsync = false; ctx->mExtOrientation = 0; ctx->numActiveDisplays = 1; // Initialize device orientation to its default orientation ctx->deviceOrientation = 0; ctx->mBufferMirrorMode = false; property_get("sys.hwc.windowbox_aspect_ratio_tolerance", value, "0"); ctx->mAspectRatioToleranceLevel = (((float)atoi(value)) / 100.0f); ctx->enableABC = false; property_get("debug.sf.hwc.canUseABC", value, "0"); ctx->enableABC = atoi(value) ? true : false; // Initializing boot anim completed check to false ctx->mBootAnimCompleted = false; // Initialize gpu perfomance hint related parameters #ifdef QTI_BSP ctx->mEglLib = NULL; ctx->mpfn_eglGpuPerfHintQCOM = NULL; ctx->mpfn_eglGetCurrentDisplay = NULL; ctx->mpfn_eglGetCurrentContext = NULL; ctx->mGPUHintInfo.mGpuPerfModeEnable = false; ctx->mGPUHintInfo.mEGLDisplay = NULL; ctx->mGPUHintInfo.mEGLContext = NULL; ctx->mGPUHintInfo.mCompositionState = COMPOSITION_STATE_MDP; ctx->mGPUHintInfo.mCurrGPUPerfMode = EGL_GPU_LEVEL_0; if(property_get("sys.hwc.gpu_perf_mode", value, "0") > 0) { int val = atoi(value); if(val > 0 && loadEglLib(ctx)) { ctx->mGPUHintInfo.mGpuPerfModeEnable = true; } } #endif // Read the system property to determine if windowboxing feature is enabled. ctx->mWindowboxFeature = false; if(property_get("sys.hwc.windowbox_feature", value, "false") && !strcmp(value, "true")) { ctx->mWindowboxFeature = true; } ctx->mUseMetaDataRefreshRate = true; if(property_get("persist.metadata_dynfps.disable", value, "false") && !strcmp(value, "true")) { ctx->mUseMetaDataRefreshRate = false; } memset(&(ctx->mPtorInfo), 0, sizeof(ctx->mPtorInfo)); ctx->mHPDEnabled = false; //init qdcm service related context. qdcmInitContext(ctx); ALOGI("Initializing Qualcomm Hardware Composer"); ALOGI("MDP version: %d", ctx->mMDP.version); return 0; OpenFBError: ALOGE("%s: Fatal Error: FB Open failed!!!", __FUNCTION__); delete ctx->mHDMIDisplay; return error; } void closeContext(hwc_context_t *ctx) { //close qdcm service related context. qdcmCloseContext(ctx); if(ctx->mOverlay) { delete ctx->mOverlay; ctx->mOverlay = NULL; } if(ctx->mRotMgr) { delete ctx->mRotMgr; ctx->mRotMgr = NULL; } for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) { if(ctx->mCopyBit[i]) { delete ctx->mCopyBit[i]; ctx->mCopyBit[i] = NULL; } } if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) { close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd); ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1; } if(ctx->mHDMIDisplay) { delete ctx->mHDMIDisplay; ctx->mHDMIDisplay = NULL; } for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) { destroyCompositionResources(ctx, i); if(ctx->mHwcDebug[i]) { delete ctx->mHwcDebug[i]; ctx->mHwcDebug[i] = NULL; } if(ctx->mLayerRotMap[i]) { delete ctx->mLayerRotMap[i]; ctx->mLayerRotMap[i] = NULL; } } if(ctx->mHWCVirtual) { delete ctx->mHWCVirtual; ctx->mHWCVirtual = NULL; } if(ctx->mAD) { delete ctx->mAD; ctx->mAD = NULL; } if(ctx->mQService) { delete ctx->mQService; ctx->mQService = NULL; } #ifdef QTI_BSP ctx->mpfn_eglGpuPerfHintQCOM = NULL; ctx->mpfn_eglGetCurrentDisplay = NULL; ctx->mpfn_eglGetCurrentContext = NULL; if(ctx->mEglLib) { dlclose(ctx->mEglLib); ctx->mEglLib = NULL; } #endif } uint32_t getRefreshRate(hwc_context_t* ctx, uint32_t requestedRefreshRate) { qdutils::MDPVersion& mdpHw = qdutils::MDPVersion::getInstance(); int dpy = HWC_DISPLAY_PRIMARY; uint32_t defaultRefreshRate = ctx->dpyAttr[dpy].refreshRate; uint32_t rate = defaultRefreshRate; if(!requestedRefreshRate) return defaultRefreshRate; uint32_t maxNumIterations = (uint32_t)ceil( (float)mdpHw.getMaxFpsSupported()/ (float)requestedRefreshRate); for(uint32_t i = 1; i <= maxNumIterations; i++) { rate = i * roundOff(requestedRefreshRate); if(rate < mdpHw.getMinFpsSupported()) { continue; } else if((rate >= mdpHw.getMinFpsSupported() && rate <= mdpHw.getMaxFpsSupported())) { break; } else { rate = defaultRefreshRate; break; } } return rate; } //Helper to roundoff the refreshrates to the std refresh-rates uint32_t roundOff(uint32_t refreshRate) { int count = (int) (sizeof(stdRefreshRates)/sizeof(stdRefreshRates[0])); uint32_t rate = refreshRate; for(int i=0; i< count; i++) { if(abs((int)(stdRefreshRates[i] - refreshRate)) < 2) { // Most likely used for video, the fps can fluctuate // Ex: b/w 29 and 30 for 30 fps clip rate = stdRefreshRates[i]; break; } } return rate; } //Helper func to set the dyn fps void setRefreshRate(hwc_context_t* ctx, int dpy, uint32_t refreshRate) { //Update only if different if(!ctx || refreshRate == ctx->dpyAttr[dpy].dynRefreshRate) return; const int fbNum = Overlay::getFbForDpy(dpy); char sysfsPath[qdutils::MAX_SYSFS_FILE_PATH]; snprintf (sysfsPath, sizeof(sysfsPath), "/sys/devices/virtual/graphics/fb%d/dynamic_fps", fbNum); int fd = open(sysfsPath, O_WRONLY); if(fd >= 0) { char str[64]; snprintf(str, sizeof(str), "%d", refreshRate); ssize_t ret = write(fd, str, strlen(str)); if(ret < 0) { ALOGE("%s: Failed to write %d with error %s", __FUNCTION__, refreshRate, strerror(errno)); } else { ctx->dpyAttr[dpy].dynRefreshRate = refreshRate; ALOGD_IF(HWC_UTILS_DEBUG, "%s: Wrote %d to dynamic_fps", __FUNCTION__, refreshRate); } close(fd); } else { ALOGE("%s: Failed to open %s with error %s", __FUNCTION__, sysfsPath, strerror(errno)); } } //Helper func to read the dyn fps void readRefreshRate(hwc_context_t* ctx, int dpy) { if(!ctx || !ctx->dpyAttr[dpy].isActive) return; const int fbNum = Overlay::getFbForDpy(dpy); ssize_t len = -1; char sysfsPath[qdutils::MAX_SYSFS_FILE_PATH]; snprintf (sysfsPath, sizeof(sysfsPath), "/sys/devices/virtual/graphics/fb%d/dynamic_fps", fbNum); int fd = open(sysfsPath, O_RDONLY); if(fd >= 0) { char str[64]; len = read(fd, str, sizeof(str)-1); if (len <= 0) { ALOGE("%s: dynamic fps node empty", __FUNCTION__); close(fd); return; } str[len] = '\0'; /* null terminate the string */ ctx->dpyAttr[dpy].dynRefreshRate = atoi(str); ALOGD_IF(HWC_UTILS_DEBUG, "%s: Dynamic fps read as %d", __FUNCTION__, ctx->dpyAttr[dpy].dynRefreshRate); close(fd); } } void dumpsys_log(android::String8& buf, const char* fmt, ...) { va_list varargs; va_start(varargs, fmt); buf.appendFormatV(fmt, varargs); va_end(varargs); } int getExtOrientation(hwc_context_t* ctx) { int extOrient = ctx->mExtOrientation; if(ctx->mBufferMirrorMode) extOrient = getMirrorModeOrientation(ctx); return extOrient; } /* Calculates the destination position based on the action safe rectangle */ void getActionSafePosition(hwc_context_t *ctx, int dpy, hwc_rect_t& rect) { // Position int x = rect.left, y = rect.top; int w = rect.right - rect.left; int h = rect.bottom - rect.top; if(!ctx->dpyAttr[dpy].mActionSafePresent) return; // Read action safe properties int asWidthRatio = ctx->dpyAttr[dpy].mAsWidthRatio; int asHeightRatio = ctx->dpyAttr[dpy].mAsHeightRatio; float wRatio = 1.0; float hRatio = 1.0; float xRatio = 1.0; float yRatio = 1.0; uint32_t fbWidth = ctx->dpyAttr[dpy].xres; uint32_t fbHeight = ctx->dpyAttr[dpy].yres; if(ctx->dpyAttr[dpy].mMDPScalingMode) { // if MDP scaling mode is enabled for external, need to query // the actual width and height, as that is the physical w & h ctx->mHDMIDisplay->getAttributes(fbWidth, fbHeight); } // Since external is rotated 90, need to swap width/height int extOrient = getExtOrientation(ctx); if(extOrient & HWC_TRANSFORM_ROT_90) swap(fbWidth, fbHeight); float asX = 0; float asY = 0; float asW = (float)fbWidth; float asH = (float)fbHeight; // based on the action safe ratio, get the Action safe rectangle asW = ((float)fbWidth * (1.0f - (float)asWidthRatio / 100.0f)); asH = ((float)fbHeight * (1.0f - (float)asHeightRatio / 100.0f)); asX = ((float)fbWidth - asW) / 2; asY = ((float)fbHeight - asH) / 2; // calculate the position ratio xRatio = (float)x/(float)fbWidth; yRatio = (float)y/(float)fbHeight; wRatio = (float)w/(float)fbWidth; hRatio = (float)h/(float)fbHeight; //Calculate the position... x = int((xRatio * asW) + asX); y = int((yRatio * asH) + asY); w = int(wRatio * asW); h = int(hRatio * asH); // Convert it back to hwc_rect_t rect.left = x; rect.top = y; rect.right = w + rect.left; rect.bottom = h + rect.top; return; } // This function gets the destination position for Seconday display // based on the position and aspect ratio with orientation void getAspectRatioPosition(hwc_context_t* ctx, int dpy, int extOrientation, hwc_rect_t& inRect, hwc_rect_t& outRect) { // Physical display resolution float fbWidth = (float)ctx->dpyAttr[dpy].xres; float fbHeight = (float)ctx->dpyAttr[dpy].yres; //display position(x,y,w,h) in correct aspectratio after rotation int xPos = 0; int yPos = 0; float width = fbWidth; float height = fbHeight; // Width/Height used for calculation, after rotation float actualWidth = fbWidth; float actualHeight = fbHeight; float wRatio = 1.0; float hRatio = 1.0; float xRatio = 1.0; float yRatio = 1.0; hwc_rect_t rect = {0, 0, (int)fbWidth, (int)fbHeight}; Dim inPos(inRect.left, inRect.top, inRect.right - inRect.left, inRect.bottom - inRect.top); Dim outPos(outRect.left, outRect.top, outRect.right - outRect.left, outRect.bottom - outRect.top); Whf whf((uint32_t)fbWidth, (uint32_t)fbHeight, 0); eTransform extorient = static_cast<eTransform>(extOrientation); // To calculate the destination co-ordinates in the new orientation preRotateSource(extorient, whf, inPos); if(extOrientation & HAL_TRANSFORM_ROT_90) { // Swap width/height for input position swapWidthHeight(actualWidth, actualHeight); qdutils::getAspectRatioPosition((int)fbWidth, (int)fbHeight, (int)actualWidth, (int)actualHeight, rect); xPos = rect.left; yPos = rect.top; width = float(rect.right - rect.left); height = float(rect.bottom - rect.top); } xRatio = (float)((float)inPos.x/actualWidth); yRatio = (float)((float)inPos.y/actualHeight); wRatio = (float)((float)inPos.w/actualWidth); hRatio = (float)((float)inPos.h/actualHeight); //Calculate the pos9ition... outPos.x = uint32_t((xRatio * width) + (float)xPos); outPos.y = uint32_t((yRatio * height) + (float)yPos); outPos.w = uint32_t(wRatio * width); outPos.h = uint32_t(hRatio * height); ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio Position: x = %d," "y = %d w = %d h = %d", __FUNCTION__, outPos.x, outPos.y, outPos.w, outPos.h); // For sidesync, the dest fb will be in portrait orientation, and the crop // will be updated to avoid the black side bands, and it will be upscaled // to fit the dest RB, so recalculate // the position based on the new width and height if ((extOrientation & HWC_TRANSFORM_ROT_90) && isOrientationPortrait(ctx)) { hwc_rect_t r = {0, 0, 0, 0}; //Calculate the position xRatio = (float)(outPos.x - xPos)/width; // GetaspectRatio -- tricky to get the correct aspect ratio // But we need to do this. qdutils::getAspectRatioPosition((int)width, (int)height, (int)width,(int)height, r); xPos = r.left; yPos = r.top; float tempHeight = float(r.bottom - r.top); yRatio = (float)yPos/height; wRatio = (float)outPos.w/width; hRatio = tempHeight/height; //Map the coordinates back to Framebuffer domain outPos.x = uint32_t(xRatio * fbWidth); outPos.y = uint32_t(yRatio * fbHeight); outPos.w = uint32_t(wRatio * fbWidth); outPos.h = uint32_t(hRatio * fbHeight); ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio for device in" "portrait: x = %d,y = %d w = %d h = %d", __FUNCTION__, outPos.x, outPos.y, outPos.w, outPos.h); } if(ctx->dpyAttr[dpy].mMDPScalingMode) { uint32_t extW = 0, extH = 0; if(dpy == HWC_DISPLAY_EXTERNAL) { ctx->mHDMIDisplay->getAttributes(extW, extH); } else if(dpy == HWC_DISPLAY_VIRTUAL) { extW = ctx->mHWCVirtual->getScalingWidth(); extH = ctx->mHWCVirtual->getScalingHeight(); } ALOGD_IF(HWC_UTILS_DEBUG, "%s: Scaling mode extW=%d extH=%d", __FUNCTION__, extW, extH); fbWidth = (float)ctx->dpyAttr[dpy].xres; fbHeight = (float)ctx->dpyAttr[dpy].yres; //Calculate the position... xRatio = (float)outPos.x/fbWidth; yRatio = (float)outPos.y/fbHeight; wRatio = (float)outPos.w/fbWidth; hRatio = (float)outPos.h/fbHeight; outPos.x = uint32_t(xRatio * (float)extW); outPos.y = uint32_t(yRatio * (float)extH); outPos.w = uint32_t(wRatio * (float)extW); outPos.h = uint32_t(hRatio * (float)extH); } // Convert Dim to hwc_rect_t outRect.left = outPos.x; outRect.top = outPos.y; outRect.right = outPos.x + outPos.w; outRect.bottom = outPos.y + outPos.h; return; } bool isPrimaryPortrait(hwc_context_t *ctx) { int fbWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres; int fbHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres; if(fbWidth < fbHeight) { return true; } return false; } bool isOrientationPortrait(hwc_context_t *ctx) { if(isPrimaryPortrait(ctx)) { return !(ctx->deviceOrientation & 0x1); } return (ctx->deviceOrientation & 0x1); } void calcExtDisplayPosition(hwc_context_t *ctx, private_handle_t *hnd, int dpy, hwc_rect_t& sourceCrop, hwc_rect_t& displayFrame, int& transform, ovutils::eTransform& orient) { // Swap width and height when there is a 90deg transform int extOrient = getExtOrientation(ctx); if ((dpy || isPrimaryPluggable(ctx)) && ctx->mOverlay->isUIScalingOnExternalSupported()) { if(!isYuvBuffer(hnd)) { if(extOrient & HWC_TRANSFORM_ROT_90) { int dstWidth = ctx->dpyAttr[dpy].xres; int dstHeight = ctx->dpyAttr[dpy].yres;; int srcWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres; int srcHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres; if(!isPrimaryPortrait(ctx)) { swap(srcWidth, srcHeight); } // Get Aspect Ratio for external qdutils::getAspectRatioPosition(dstWidth, dstHeight, srcWidth, srcHeight, displayFrame); // Crop - this is needed, because for sidesync, the dest fb will // be in portrait orientation, so update the crop to not show the // black side bands. if (isOrientationPortrait(ctx)) { sourceCrop = displayFrame; displayFrame.left = 0; displayFrame.top = 0; displayFrame.right = dstWidth; displayFrame.bottom = dstHeight; } } if(ctx->dpyAttr[dpy].mMDPScalingMode) { uint32_t extW = 0, extH = 0; // if MDP scaling mode is enabled, map the co-ordinates to new // domain(downscaled) float fbWidth = (float)ctx->dpyAttr[dpy].xres; float fbHeight = (float)ctx->dpyAttr[dpy].yres; // query MDP configured attributes if(dpy == HWC_DISPLAY_EXTERNAL) { ctx->mHDMIDisplay->getAttributes(extW, extH); } else if(dpy == HWC_DISPLAY_VIRTUAL) { extW = ctx->mHWCVirtual->getScalingWidth(); extH = ctx->mHWCVirtual->getScalingHeight(); } ALOGD_IF(HWC_UTILS_DEBUG, "%s: Scaling mode extW=%d extH=%d", __FUNCTION__, extW, extH); //Calculate the ratio... float wRatio = ((float)extW)/fbWidth; float hRatio = ((float)extH)/fbHeight; //convert Dim to hwc_rect_t displayFrame.left = int(wRatio*(float)displayFrame.left); displayFrame.top = int(hRatio*(float)displayFrame.top); displayFrame.right = int(wRatio*(float)displayFrame.right); displayFrame.bottom = int(hRatio*(float)displayFrame.bottom); ALOGD_IF(DEBUG_MDPDOWNSCALE, "Calculated external display frame" " for MDPDownscale feature [%d %d %d %d]", displayFrame.left, displayFrame.top, displayFrame.right, displayFrame.bottom); } }else { if(extOrient || ctx->dpyAttr[dpy].mMDPScalingMode) { getAspectRatioPosition(ctx, dpy, extOrient, displayFrame, displayFrame); } } // If there is a external orientation set, use that if(extOrient) { transform = extOrient; orient = static_cast<ovutils::eTransform >(extOrient); } // Calculate the actionsafe dimensions for External(dpy = 1 or 2) getActionSafePosition(ctx, dpy, displayFrame); } } /* Returns the orientation which needs to be set on External for * SideSync/Buffer Mirrormode */ int getMirrorModeOrientation(hwc_context_t *ctx) { int extOrientation = 0; int deviceOrientation = ctx->deviceOrientation; if(!isPrimaryPortrait(ctx)) deviceOrientation = (deviceOrientation + 1) % 4; if (deviceOrientation == 0) extOrientation = HWC_TRANSFORM_ROT_270; else if (deviceOrientation == 1)//90 extOrientation = 0; else if (deviceOrientation == 2)//180 extOrientation = HWC_TRANSFORM_ROT_90; else if (deviceOrientation == 3)//270 extOrientation = HWC_TRANSFORM_FLIP_V | HWC_TRANSFORM_FLIP_H; return extOrientation; } /* Get External State names */ const char* getExternalDisplayState(uint32_t external_state) { static const char* externalStates[EXTERNAL_MAXSTATES] = {0}; externalStates[EXTERNAL_OFFLINE] = STR(EXTERNAL_OFFLINE); externalStates[EXTERNAL_ONLINE] = STR(EXTERNAL_ONLINE); externalStates[EXTERNAL_PAUSE] = STR(EXTERNAL_PAUSE); externalStates[EXTERNAL_RESUME] = STR(EXTERNAL_RESUME); if(external_state >= EXTERNAL_MAXSTATES) { return "EXTERNAL_INVALID"; } return externalStates[external_state]; } bool isDownscaleRequired(hwc_layer_1_t const* layer) { hwc_rect_t displayFrame = layer->displayFrame; hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf); int dst_w, dst_h, src_w, src_h; dst_w = displayFrame.right - displayFrame.left; dst_h = displayFrame.bottom - displayFrame.top; src_w = sourceCrop.right - sourceCrop.left; src_h = sourceCrop.bottom - sourceCrop.top; if(layer->transform & HWC_TRANSFORM_ROT_90) swap(src_w, src_h); if(((src_w > dst_w) || (src_h > dst_h))) return true; return false; } bool isDownscaleWithinThreshold(hwc_layer_1_t const* layer, float threshold) { hwc_rect_t displayFrame = layer->displayFrame; hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf); int dst_w, dst_h, src_w, src_h; dst_w = displayFrame.right - displayFrame.left; dst_h = displayFrame.bottom - displayFrame.top; src_w = sourceCrop.right - sourceCrop.left; src_h = sourceCrop.bottom - sourceCrop.top; if(layer->transform & HWC_TRANSFORM_ROT_90) swap(src_w, src_h); if(dst_w && dst_h) { float w_scale = ((float)src_w / (float)dst_w); float h_scale = ((float)src_h / (float)dst_h); if((w_scale > threshold) or (h_scale > threshold)) return false; } return true; } bool needsScaling(hwc_layer_1_t const* layer) { int dst_w, dst_h, src_w, src_h; hwc_rect_t displayFrame = layer->displayFrame; hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf); dst_w = displayFrame.right - displayFrame.left; dst_h = displayFrame.bottom - displayFrame.top; src_w = sourceCrop.right - sourceCrop.left; src_h = sourceCrop.bottom - sourceCrop.top; if(layer->transform & HWC_TRANSFORM_ROT_90) swap(src_w, src_h); if(((src_w != dst_w) || (src_h != dst_h))) return true; return false; } // Checks if layer needs scaling with split bool needsScalingWithSplit(hwc_context_t* ctx, hwc_layer_1_t const* layer, const int& dpy) { int src_width_l, src_height_l; int src_width_r, src_height_r; int dst_width_l, dst_height_l; int dst_width_r, dst_height_r; int hw_w = ctx->dpyAttr[dpy].xres; int hw_h = ctx->dpyAttr[dpy].yres; hwc_rect_t cropL, dstL, cropR, dstR; const int lSplit = getLeftSplit(ctx, dpy); hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t displayFrame = layer->displayFrame; private_handle_t *hnd = (private_handle_t *)layer->handle; cropL = sourceCrop; dstL = displayFrame; hwc_rect_t scissorL = { 0, 0, lSplit, hw_h }; scissorL = getIntersection(ctx->mViewFrame[dpy], scissorL); qhwc::calculate_crop_rects(cropL, dstL, scissorL, 0); cropR = sourceCrop; dstR = displayFrame; hwc_rect_t scissorR = { lSplit, 0, hw_w, hw_h }; scissorR = getIntersection(ctx->mViewFrame[dpy], scissorR); qhwc::calculate_crop_rects(cropR, dstR, scissorR, 0); // Sanitize Crop to stitch sanitizeSourceCrop(cropL, cropR, hnd); // Calculate the left dst dst_width_l = dstL.right - dstL.left; dst_height_l = dstL.bottom - dstL.top; src_width_l = cropL.right - cropL.left; src_height_l = cropL.bottom - cropL.top; // check if there is any scaling on the left if(((src_width_l != dst_width_l) || (src_height_l != dst_height_l))) return true; // Calculate the right dst dst_width_r = dstR.right - dstR.left; dst_height_r = dstR.bottom - dstR.top; src_width_r = cropR.right - cropR.left; src_height_r = cropR.bottom - cropR.top; // check if there is any scaling on the right if(((src_width_r != dst_width_r) || (src_height_r != dst_height_r))) return true; return false; } bool isAlphaScaled(hwc_layer_1_t const* layer) { if(needsScaling(layer) && isAlphaPresent(layer)) { return true; } return false; } bool isAlphaPresent(hwc_layer_1_t const* layer) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(hnd) { int format = hnd->format; switch(format) { case HAL_PIXEL_FORMAT_RGBA_8888: case HAL_PIXEL_FORMAT_BGRA_8888: // In any more formats with Alpha go here.. return true; default : return false; } } return false; } bool isAlphaPresentinFB(hwc_context_t *ctx, int dpy) { switch(ctx->dpyAttr[dpy].fbformat) { case HAL_PIXEL_FORMAT_RGBA_8888: case HAL_PIXEL_FORMAT_BGRA_8888: return true; default : return false; } return false; } static void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform, hwc_rect_t& crop, hwc_rect_t& dst) { int hw_w = ctx->dpyAttr[dpy].xres; int hw_h = ctx->dpyAttr[dpy].yres; if(dst.left < 0 || dst.top < 0 || dst.right > hw_w || dst.bottom > hw_h) { hwc_rect_t scissor = {0, 0, hw_w, hw_h }; scissor = getIntersection(ctx->mViewFrame[dpy], scissor); qhwc::calculate_crop_rects(crop, dst, scissor, transform); } } static void trimList(hwc_context_t *ctx, hwc_display_contents_1_t *list, const int& dpy) { for(uint32_t i = 0; i < list->numHwLayers - 1; i++) { hwc_layer_1_t *layer = &list->hwLayers[i]; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf); int transform = (list->hwLayers[i].flags & HWC_COLOR_FILL) ? 0 : list->hwLayers[i].transform; trimLayer(ctx, dpy, transform, (hwc_rect_t&)crop, (hwc_rect_t&)list->hwLayers[i].displayFrame); layer->sourceCropf.left = (float)crop.left; layer->sourceCropf.right = (float)crop.right; layer->sourceCropf.top = (float)crop.top; layer->sourceCropf.bottom = (float)crop.bottom; } } void setListStats(hwc_context_t *ctx, hwc_display_contents_1_t *list, int dpy) { const int prevYuvCount = ctx->listStats[dpy].yuvCount; memset(&ctx->listStats[dpy], 0, sizeof(ListStats)); ctx->listStats[dpy].numAppLayers = (int)list->numHwLayers - 1; ctx->listStats[dpy].fbLayerIndex = (int)list->numHwLayers - 1; ctx->listStats[dpy].skipCount = 0; ctx->listStats[dpy].preMultipliedAlpha = false; ctx->listStats[dpy].isSecurePresent = false; ctx->listStats[dpy].yuvCount = 0; char property[PROPERTY_VALUE_MAX]; ctx->listStats[dpy].isDisplayAnimating = false; ctx->listStats[dpy].secureUI = false; ctx->listStats[dpy].yuv4k2kCount = 0; ctx->dpyAttr[dpy].mActionSafePresent = isActionSafePresent(ctx, dpy); ctx->listStats[dpy].renderBufIndexforABC = -1; ctx->listStats[dpy].secureRGBCount = 0; ctx->listStats[dpy].secureYUVCount = 0; ctx->listStats[dpy].refreshRateRequest = ctx->dpyAttr[dpy].refreshRate; ctx->listStats[dpy].cursorLayerPresent = false; uint32_t refreshRate = 0; int s3dFormat = HAL_NO_3D; int s3dLayerCount = 0; ctx->listStats[dpy].mAIVVideoMode = false; resetROI(ctx, dpy); trimList(ctx, list, dpy); optimizeLayerRects(list); for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) { hwc_layer_1_t const* layer = &list->hwLayers[i]; private_handle_t *hnd = (private_handle_t *)layer->handle; #ifdef QTI_BSP // Window boxing feature is applicable obly for external display, So // enable mAIVVideoMode only for external display if(ctx->mWindowboxFeature && dpy && isAIVVideoLayer(layer)) { ctx->listStats[dpy].mAIVVideoMode = true; } if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) { ctx->listStats[dpy].isDisplayAnimating = true; } if(isSecureDisplayBuffer(hnd)) { ctx->listStats[dpy].secureUI = true; } #endif // continue if number of app layers exceeds MAX_NUM_APP_LAYERS if(ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS) continue; // Valid cursor must be the top most layer if((int)i == (ctx->listStats[dpy].numAppLayers - 1) && isCursorLayer(&list->hwLayers[i])) { ctx->listStats[dpy].cursorLayerPresent = true; } //reset yuv indices ctx->listStats[dpy].yuvIndices[i] = -1; ctx->listStats[dpy].yuv4k2kIndices[i] = -1; if (isSecureBuffer(hnd) || isProtectedBuffer(hnd)) { // Protected Buffer must be treated as Secure Layer ctx->listStats[dpy].isSecurePresent = true; if(not isYuvBuffer(hnd)) { // cache secureRGB layer parameters like we cache for YUV layers int& secureRGBCount = ctx->listStats[dpy].secureRGBCount; ctx->listStats[dpy].secureRGBIndices[secureRGBCount] = (int)i; secureRGBCount++; } else { int& secureYUVCount = ctx->listStats[dpy].secureYUVCount; secureYUVCount++; } } if (isSkipLayer(&list->hwLayers[i])) { ctx->listStats[dpy].skipCount++; } if (UNLIKELY(isYuvBuffer(hnd))) { int& yuvCount = ctx->listStats[dpy].yuvCount; ctx->listStats[dpy].yuvIndices[yuvCount] = (int)i; yuvCount++; if(UNLIKELY(isYUVSplitNeeded(hnd))){ int& yuv4k2kCount = ctx->listStats[dpy].yuv4k2kCount; ctx->listStats[dpy].yuv4k2kIndices[yuv4k2kCount] = (int)i; yuv4k2kCount++; } // Gets set if one YUV layer is 3D if (displaySupports3D(ctx,dpy)) { s3dFormat = get3DFormat(hnd); if(s3dFormat != HAL_NO_3D) s3dLayerCount++; } } if(layer->blending == HWC_BLENDING_PREMULT) ctx->listStats[dpy].preMultipliedAlpha = true; #ifdef DYNAMIC_FPS qdutils::MDPVersion& mdpHw = qdutils::MDPVersion::getInstance(); if (!dpy && mdpHw.isDynFpsSupported() && ctx->mUseMetaDataRefreshRate){ /* Dyn fps: get refreshrate from metadata */ MetaData_t *mdata = hnd ? (MetaData_t *)hnd->base_metadata : NULL; if (mdata && (mdata->operation & UPDATE_REFRESH_RATE)) { // Valid refreshRate in metadata and within the range uint32_t rate = getRefreshRate(ctx, mdata->refreshrate); if (!refreshRate) { refreshRate = rate; } else if(refreshRate != rate) { /* Support multiple refresh rates if they are same * else set to default. */ refreshRate = ctx->dpyAttr[dpy].refreshRate; } } } #endif } //Set the TV's 3D mode based on format if it was not forced //Only one 3D YUV layer is supported on external //If there is more than one 3D YUV layer, the switch to 3D cannot occur. if( !ctx->dpyAttr[dpy].s3dModeForced && (s3dLayerCount <= 1)) { //XXX: Rapidly going in and out of 3D mode in some cases such // as rotation might cause flickers. The OEMs are recommended to disable // rotation on HDMI globally or in the app that plays 3D video setup3DMode(ctx, dpy, convertS3DFormatToMode(s3dFormat)); } if(ctx->listStats[dpy].yuvCount > 0) { if (property_get("hw.cabl.yuv", property, NULL) > 0) { if (atoi(property) != 1) { property_set("hw.cabl.yuv", "1"); } } } else { if (property_get("hw.cabl.yuv", property, NULL) > 0) { if (atoi(property) != 0) { property_set("hw.cabl.yuv", "0"); } } } //The marking of video begin/end is useful on some targets where we need //to have a padding round to be able to shift pipes across mixers. if(prevYuvCount != ctx->listStats[dpy].yuvCount) { ctx->mVideoTransFlag = true; } if(dpy == HWC_DISPLAY_PRIMARY) { ctx->mAD->markDoable(ctx, list); //Store the requested fresh rate ctx->listStats[dpy].refreshRateRequest = refreshRate ? refreshRate : ctx->dpyAttr[dpy].refreshRate; } } static void calc_cut(double& leftCutRatio, double& topCutRatio, double& rightCutRatio, double& bottomCutRatio, int orient) { if(orient & HAL_TRANSFORM_FLIP_H) { swap(leftCutRatio, rightCutRatio); } if(orient & HAL_TRANSFORM_FLIP_V) { swap(topCutRatio, bottomCutRatio); } if(orient & HAL_TRANSFORM_ROT_90) { //Anti clock swapping double tmpCutRatio = leftCutRatio; leftCutRatio = topCutRatio; topCutRatio = rightCutRatio; rightCutRatio = bottomCutRatio; bottomCutRatio = tmpCutRatio; } } bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) { if((ctx->mMDP.version < qdutils::MDSS_V5) && (ctx->mMDP.version > qdutils::MDP_V3_0) && ctx->mSecuring) { return true; } if (isSecureModePolicy(ctx->mMDP.version)) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(ctx->mSecureMode) { if (! isSecureBuffer(hnd)) { ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...", __FUNCTION__); return true; } } else { if (isSecureBuffer(hnd)) { ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...", __FUNCTION__); return true; } } } return false; } bool isSecureModePolicy(int mdpVersion) { if (mdpVersion < qdutils::MDSS_V5) return true; else return false; } bool isRotatorSupportedFormat(private_handle_t *hnd) { // Following rotator src formats are supported by mdp driver // TODO: Add more formats in future, if mdp driver adds support if(hnd != NULL) { switch(hnd->format) { case HAL_PIXEL_FORMAT_RGBA_8888: case HAL_PIXEL_FORMAT_RGBA_5551: case HAL_PIXEL_FORMAT_RGBA_4444: case HAL_PIXEL_FORMAT_RGB_565: case HAL_PIXEL_FORMAT_RGB_888: case HAL_PIXEL_FORMAT_BGRA_8888: return true; default: return false; } } return false; } bool isRotationDoable(hwc_context_t *ctx, private_handle_t *hnd) { // Rotate layers, if it is not secure display buffer and not // for the MDP versions below MDP5 if((!isSecureDisplayBuffer(hnd) && isRotatorSupportedFormat(hnd) && !(ctx->mMDP.version < qdutils::MDSS_V5))|| isYuvBuffer(hnd)) { return true; } return false; } // returns true if Action safe dimensions are set and target supports Actionsafe bool isActionSafePresent(hwc_context_t *ctx, int dpy) { // if external supports underscan, do nothing // it will be taken care in the driver // Disable Action safe for 8974 due to HW limitation for downscaling // layers with overlapped region // Disable Actionsafe for non HDMI displays. if (!(dpy == HWC_DISPLAY_EXTERNAL || isPrimaryPluggable(ctx)) || qdutils::MDPVersion::getInstance().is8x74v2() || ctx->mHDMIDisplay->isCEUnderscanSupported()) { return false; } char value[PROPERTY_VALUE_MAX]; // Read action safe properties property_get("persist.sys.actionsafe.width", value, "0"); ctx->dpyAttr[dpy].mAsWidthRatio = atoi(value); property_get("persist.sys.actionsafe.height", value, "0"); ctx->dpyAttr[dpy].mAsHeightRatio = atoi(value); if(!ctx->dpyAttr[dpy].mAsWidthRatio && !ctx->dpyAttr[dpy].mAsHeightRatio) { //No action safe ratio set, return return false; } return true; } int getBlending(int blending) { switch(blending) { case HWC_BLENDING_NONE: return overlay::utils::OVERLAY_BLENDING_OPAQUE; case HWC_BLENDING_PREMULT: return overlay::utils::OVERLAY_BLENDING_PREMULT; case HWC_BLENDING_COVERAGE : default: return overlay::utils::OVERLAY_BLENDING_COVERAGE; } } //Crops source buffer against destination and FB boundaries void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst, const hwc_rect_t& scissor, int orient) { int& crop_l = crop.left; int& crop_t = crop.top; int& crop_r = crop.right; int& crop_b = crop.bottom; int crop_w = crop.right - crop.left; int crop_h = crop.bottom - crop.top; int& dst_l = dst.left; int& dst_t = dst.top; int& dst_r = dst.right; int& dst_b = dst.bottom; int dst_w = abs(dst.right - dst.left); int dst_h = abs(dst.bottom - dst.top); const int& sci_l = scissor.left; const int& sci_t = scissor.top; const int& sci_r = scissor.right; const int& sci_b = scissor.bottom; double leftCutRatio = 0.0, rightCutRatio = 0.0, topCutRatio = 0.0, bottomCutRatio = 0.0; if(dst_l < sci_l) { leftCutRatio = (double)(sci_l - dst_l) / (double)dst_w; dst_l = sci_l; } if(dst_r > sci_r) { rightCutRatio = (double)(dst_r - sci_r) / (double)dst_w; dst_r = sci_r; } if(dst_t < sci_t) { topCutRatio = (double)(sci_t - dst_t) / (double)dst_h; dst_t = sci_t; } if(dst_b > sci_b) { bottomCutRatio = (double)(dst_b - sci_b) / (double)dst_h; dst_b = sci_b; } calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient); crop_l += (int)round((double)crop_w * leftCutRatio); crop_t += (int)round((double)crop_h * topCutRatio); crop_r -= (int)round((double)crop_w * rightCutRatio); crop_b -= (int)round((double)crop_h * bottomCutRatio); } bool areLayersIntersecting(const hwc_layer_1_t* layer1, const hwc_layer_1_t* layer2) { hwc_rect_t irect = getIntersection(layer1->displayFrame, layer2->displayFrame); return isValidRect(irect); } bool isSameRect(const hwc_rect& rect1, const hwc_rect& rect2) { return ((rect1.left == rect2.left) && (rect1.top == rect2.top) && (rect1.right == rect2.right) && (rect1.bottom == rect2.bottom)); } bool isValidRect(const hwc_rect& rect) { return ((rect.bottom > rect.top) && (rect.right > rect.left)) ; } bool operator ==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) { if(lhs.left == rhs.left && lhs.top == rhs.top && lhs.right == rhs.right && lhs.bottom == rhs.bottom ) return true ; return false; } bool layerUpdating(const hwc_layer_1_t* layer) { hwc_region_t surfDamage = layer->surfaceDamage; return ((surfDamage.numRects == 0) || isValidRect(layer->surfaceDamage.rects[0])); } hwc_rect_t calculateDirtyRect(const hwc_layer_1_t* layer, hwc_rect_t& scissor) { hwc_region_t surfDamage = layer->surfaceDamage; hwc_rect_t src = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t dst = layer->displayFrame; int x_off = dst.left - src.left; int y_off = dst.top - src.top; hwc_rect dirtyRect = (hwc_rect){0, 0, 0, 0}; hwc_rect_t updatingRect = dst; if (surfDamage.numRects == 0) { // full layer updating, dirty rect is full frame dirtyRect = getIntersection(layer->displayFrame, scissor); } else { for(uint32_t i = 0; i < surfDamage.numRects; i++) { updatingRect = moveRect(surfDamage.rects[i], x_off, y_off); hwc_rect_t intersect = getIntersection(updatingRect, scissor); if(isValidRect(intersect)) { dirtyRect = getUnion(intersect, dirtyRect); } } } return dirtyRect; } bool CanOptimizeForSmallUpdate(hwc_context_t* ctx, int dpy,hwc_display_contents_1_t* list) { bool ret = false; const int numAppLayers = ctx->listStats[dpy].numAppLayers; if(ctx->mMDP.panel == MIPI_CMD_PANEL) return ret; if(not (list->flags & HWC_GEOMETRY_CHANGED) and not isYuvPresent(ctx, dpy) and numAppLayers > 1) ret = true; return ret; } hwc_rect_t moveRect(const hwc_rect_t& rect, const int& x_off, const int& y_off) { hwc_rect_t res; if(!isValidRect(rect)) return (hwc_rect_t){0, 0, 0, 0}; res.left = rect.left + x_off; res.top = rect.top + y_off; res.right = rect.right + x_off; res.bottom = rect.bottom + y_off; return res; } /* computes the intersection of two rects */ hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2) { hwc_rect_t res; if(!isValidRect(rect1) || !isValidRect(rect2)){ return (hwc_rect_t){0, 0, 0, 0}; } res.left = max(rect1.left, rect2.left); res.top = max(rect1.top, rect2.top); res.right = min(rect1.right, rect2.right); res.bottom = min(rect1.bottom, rect2.bottom); if(!isValidRect(res)) return (hwc_rect_t){0, 0, 0, 0}; return res; } /* computes the union of two rects */ hwc_rect_t getUnion(const hwc_rect &rect1, const hwc_rect &rect2) { hwc_rect_t res; if(!isValidRect(rect1)){ return rect2; } if(!isValidRect(rect2)){ return rect1; } res.left = min(rect1.left, rect2.left); res.top = min(rect1.top, rect2.top); res.right = max(rect1.right, rect2.right); res.bottom = max(rect1.bottom, rect2.bottom); return res; } /* Not a geometrical rect deduction. Deducts rect2 from rect1 only if it results * a single rect */ hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2) { hwc_rect_t res = rect1; if((rect1.left == rect2.left) && (rect1.right == rect2.right)) { if((rect1.top == rect2.top) && (rect2.bottom <= rect1.bottom)) res.top = rect2.bottom; else if((rect1.bottom == rect2.bottom)&& (rect2.top >= rect1.top)) res.bottom = rect2.top; } else if((rect1.top == rect2.top) && (rect1.bottom == rect2.bottom)) { if((rect1.left == rect2.left) && (rect2.right <= rect1.right)) res.left = rect2.right; else if((rect1.right == rect2.right)&& (rect2.left >= rect1.left)) res.right = rect2.left; } return res; } void optimizeLayerRects(const hwc_display_contents_1_t *list) { int i= (int)list->numHwLayers-2; while(i > 0) { //see if there is no blending required. //If it is opaque see if we can substract this region from below //layers. if(list->hwLayers[i].blending == HWC_BLENDING_NONE && list->hwLayers[i].planeAlpha == 0xFF) { int j= i-1; hwc_rect_t& topframe = (hwc_rect_t&)list->hwLayers[i].displayFrame; while(j >= 0) { if(!needsScaling(&list->hwLayers[j])) { hwc_layer_1_t* layer = (hwc_layer_1_t*)&list->hwLayers[j]; hwc_rect_t& bottomframe = layer->displayFrame; hwc_rect_t bottomCrop = integerizeSourceCrop(layer->sourceCropf); int transform = (layer->flags & HWC_COLOR_FILL) ? 0 : layer->transform; hwc_rect_t irect = getIntersection(bottomframe, topframe); if(isValidRect(irect)) { hwc_rect_t dest_rect; //if intersection is valid rect, deduct it dest_rect = deductRect(bottomframe, irect); qhwc::calculate_crop_rects(bottomCrop, bottomframe, dest_rect, transform); //Update layer sourceCropf layer->sourceCropf.left =(float)bottomCrop.left; layer->sourceCropf.top = (float)bottomCrop.top; layer->sourceCropf.right = (float)bottomCrop.right; layer->sourceCropf.bottom = (float)bottomCrop.bottom; } } j--; } } i--; } } void getNonWormholeRegion(hwc_display_contents_1_t* list, hwc_rect_t& nwr) { size_t last = list->numHwLayers - 1; hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame; //Initiliaze nwr to first frame nwr.left = list->hwLayers[0].displayFrame.left; nwr.top = list->hwLayers[0].displayFrame.top; nwr.right = list->hwLayers[0].displayFrame.right; nwr.bottom = list->hwLayers[0].displayFrame.bottom; for (size_t i = 1; i < last; i++) { hwc_rect_t displayFrame = list->hwLayers[i].displayFrame; nwr = getUnion(nwr, displayFrame); } //Intersect with the framebuffer nwr = getIntersection(nwr, fbDisplayFrame); } void closeAcquireFds(hwc_display_contents_1_t* list) { if(LIKELY(list)) { for(uint32_t i = 0; i < list->numHwLayers; i++) { //Close the acquireFenceFds //HWC_FRAMEBUFFER are -1 already by SF, rest we close. if(list->hwLayers[i].acquireFenceFd >= 0) { close(list->hwLayers[i].acquireFenceFd); list->hwLayers[i].acquireFenceFd = -1; } } //Writeback if(list->outbufAcquireFenceFd >= 0) { close(list->outbufAcquireFenceFd); list->outbufAcquireFenceFd = -1; } } } void hwc_sync_rotator(hwc_context_t *ctx, hwc_display_contents_1_t* /* list */, int dpy) { ATRACE_CALL(); //Send acquireFenceFds to rotator for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) { int rotFd = ctx->mRotMgr->getRotDevFd(); int rotReleaseFd = -1; overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i); hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i); if((currRot == NULL) || (currLayer == NULL)) { continue; } struct mdp_buf_sync rotData; memset(&rotData, 0, sizeof(rotData)); rotData.acq_fen_fd = &currLayer->acquireFenceFd; rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this rotData.session_id = currRot->getSessId(); if(currLayer->acquireFenceFd >= 0) { rotData.acq_fen_fd_cnt = 1; //1 ioctl call per rot session } int ret = 0; if(not ctx->mLayerRotMap[dpy]->isRotCached(i)) ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData); if(ret < 0) { ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s", __FUNCTION__, strerror(errno)); close(rotReleaseFd); } else { close(currLayer->acquireFenceFd); //For MDP to wait on. currLayer->acquireFenceFd = dup(rotReleaseFd); //A buffer is free to be used by producer as soon as its copied to //rotator currLayer->releaseFenceFd = rotReleaseFd; } } } bool isLayerMarkedForHWRotator(hwc_context_t *ctx, hwc_layer_1_t* layer, int dpy) { for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) { hwc_layer_1_t* rotLayer = ctx->mLayerRotMap[dpy]->getLayer(i); if(layer->handle == rotLayer->handle) return true; } return false; } int hwc_sync_mdss(hwc_context_t *ctx, hwc_display_contents_1_t *list, int dpy, bool isExtAnimating, int fd) { ATRACE_CALL(); int ret = 0; int acquireFd[MAX_NUM_APP_LAYERS]; int count = 0; int releaseFd = -1; int retireFd = -1; int fbFd = ctx->dpyAttr[dpy].fd; struct mdp_buf_sync data; memset(&data, 0, sizeof(data)); data.acq_fen_fd = acquireFd; data.rel_fen_fd = &releaseFd; data.retire_fen_fd = &retireFd; data.flags = MDP_BUF_SYNC_FLAG_RETIRE_FENCE; //Accumulate acquireFenceFds for MDP Overlays if(list->outbufAcquireFenceFd >= 0) { //Writeback output buffer acquireFd[count++] = list->outbufAcquireFenceFd; } for(uint32_t i = 0; i < list->numHwLayers; i++) { if(((isAbcInUse(ctx)== true ) || (list->hwLayers[i].compositionType == HWC_OVERLAY)) && list->hwLayers[i].acquireFenceFd >= 0) { // if ABC is enabled for more than one layer. // renderBufIndexforABC will work as FB.Hence // set the acquireFD from fd - which is coming from copybit if(fd >= 0 && (isAbcInUse(ctx) == true)) { if(ctx->listStats[dpy].renderBufIndexforABC ==(int32_t)i) acquireFd[count++] = fd; else continue; } else acquireFd[count++] = list->hwLayers[i].acquireFenceFd; } if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) { if(fd >= 0) { //set the acquireFD from fd - which is coming from c2d acquireFd[count++] = fd; // Buffer sync IOCTL should be async when using c2d fence data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT; } else if(list->hwLayers[i].acquireFenceFd >= 0) acquireFd[count++] = list->hwLayers[i].acquireFenceFd; } } data.acq_fen_fd_cnt = count; //Waits for acquire fences, returns a release fence ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data); if(ret < 0) { ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s", __FUNCTION__, strerror(errno)); ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu", __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd, dpy, list->numHwLayers); close(releaseFd); releaseFd = -1; close(retireFd); retireFd = -1; } for(uint32_t i = 0; i < list->numHwLayers; i++) { if(list->hwLayers[i].compositionType == HWC_OVERLAY || #ifdef QTI_BSP list->hwLayers[i].compositionType == HWC_BLIT || #endif list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) { //Populate releaseFenceFds. if(isExtAnimating) { // Release all the app layer fds immediately, // if animation is in progress. list->hwLayers[i].releaseFenceFd = -1; } else if(list->hwLayers[i].releaseFenceFd < 0 && !isLayerMarkedForHWRotator(ctx, &list->hwLayers[i], dpy)) { #ifdef QTI_BSP //If rotator has not already populated this field // & if it's a not VPU layer // if ABC is enabled for more than one layer if(fd >= 0 && (isAbcInUse(ctx) == true) && ctx->listStats[dpy].renderBufIndexforABC !=(int32_t)i){ list->hwLayers[i].releaseFenceFd = dup(fd); } else if((list->hwLayers[i].compositionType == HWC_BLIT)&& (isAbcInUse(ctx) == false)){ //For Blit, the app layers should be released when the Blit //is complete. This fd was passed from copybit->draw list->hwLayers[i].releaseFenceFd = dup(fd); } else #endif { list->hwLayers[i].releaseFenceFd = dup(releaseFd); } } } } if (ctx->mCopyBit[dpy]) { if((!dpy && ctx->mPtorInfo.isActive())) { ctx->mCopyBit[dpy]->setReleaseFd(releaseFd); } } //Signals when MDP finishes reading rotator buffers. ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd); close(releaseFd); releaseFd = -1; list->retireFenceFd = retireFd; return ret; } void hwc_sync_sz(hwc_context_t* ctx, hwc_display_contents_1_t* list, int dpy) { ATRACE_CALL(); for(uint32_t i = 0; i < list->numHwLayers; i++) { list->hwLayers[i].releaseFenceFd = -1; } if (ctx->mCopyBit[dpy]) { if((!dpy && ctx->mPtorInfo.isActive()) or ctx->mMDP.version < qdutils::MDP_V4_0) { ctx->mCopyBit[dpy]->setReleaseFd(-1); } } ctx->mLayerRotMap[dpy]->setReleaseFd(-1); list->retireFenceFd = -1; } int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy, int fd) { ATRACE_CALL(); int ret = 0; bool isExtAnimating = false; if(dpy) isExtAnimating = ctx->listStats[dpy].isDisplayAnimating; bool swapzero = false; char property[PROPERTY_VALUE_MAX]; if(property_get("debug.egl.swapinterval", property, "1") > 0) { if(atoi(property) == 0) swapzero = true; } if(swapzero) { hwc_sync_sz(ctx, list, dpy); } else { hwc_sync_rotator(ctx, list, dpy); ret = hwc_sync_mdss(ctx, list, dpy, isExtAnimating, fd); } if(fd >= 0) { close(fd); fd = -1; } return ret; } void setMdpFlags(hwc_context_t *ctx, hwc_layer_1_t *layer, ovutils::eMdpFlags &mdpFlags, int rotDownscale, int transform) { private_handle_t *hnd = (private_handle_t *)layer->handle; MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL; if(layer->blending == HWC_BLENDING_PREMULT) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT); } if(metadata && (metadata->operation & PP_PARAM_INTERLACED) && metadata->interlaced) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_DEINTERLACE); } // Mark MDP flags with SECURE_OVERLAY_SESSION for driver if(isSecureBuffer(hnd)) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SECURE_OVERLAY_SESSION); ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SMP_FORCE_ALLOC); } if(isProtectedBuffer(hnd)) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SMP_FORCE_ALLOC); } if(isSecureDisplayBuffer(hnd)) { // Mark MDP flags with SECURE_DISPLAY_OVERLAY_SESSION for driver ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION); } //Pre-rotation will be used using rotator. if(has90Transform(layer) && isRotationDoable(ctx, hnd)) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOURCE_ROTATED_90); } //No 90 component and no rot-downscale then flips done by MDP //If we use rot then it might as well do flips if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) { if(transform & HWC_TRANSFORM_FLIP_H) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H); } if(transform & HWC_TRANSFORM_FLIP_V) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_V); } } if(metadata && ((metadata->operation & PP_PARAM_HSIC) || (metadata->operation & PP_PARAM_IGC) || (metadata->operation & PP_PARAM_SHARP2))) { ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN); } } int configRotator(Rotator *rot, Whf& whf, hwc_rect_t& crop, const eMdpFlags& mdpFlags, const eTransform& orient, const int& downscale, const uint32_t& frame_rate) { //Check if input switched from secure->non-secure OR non-secure->secure //Need to fail rotator setup as rotator buffer needs reallocation. if(!rot->isRotBufReusable(mdpFlags)) return -1; // Fix alignments for TILED format if(whf.format == MDP_Y_CRCB_H2V2_TILE || whf.format == MDP_Y_CBCR_H2V2_TILE) { whf.w = utils::alignup(whf.w, 64); whf.h = utils::alignup(whf.h, 32); } rot->setSource(whf); if (qdutils::MDPVersion::getInstance().getMDPVersion() >= qdutils::MDSS_V5) { Dim rotCrop(crop.left, crop.top, crop.right - crop.left, crop.bottom - crop.top); rot->setCrop(rotCrop); } rot->setFrameRate(frame_rate); rot->setFlags(mdpFlags); rot->setTransform(orient); rot->setDownscale(downscale); if(!rot->commit()) return -1; return 0; } int configMdp(Overlay *ov, const PipeArgs& parg, const eTransform& orient, const hwc_rect_t& crop, const hwc_rect_t& pos, const MetaData_t *metadata, const eDest& dest) { ov->setSource(parg, dest); ov->setTransform(orient, dest); int crop_w = crop.right - crop.left; int crop_h = crop.bottom - crop.top; Dim dcrop(crop.left, crop.top, crop_w, crop_h); ov->setCrop(dcrop, dest); int posW = pos.right - pos.left; int posH = pos.bottom - pos.top; Dim position(pos.left, pos.top, posW, posH); ov->setPosition(position, dest); if (metadata) ov->setVisualParams(*metadata, dest); if (!ov->commit(dest)) { return -1; } return 0; } int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy, eMdpFlags& mdpFlags, eZorder& z, const eDest& dest) { hwc_rect_t dst = layer->displayFrame; trimLayer(ctx, dpy, 0, dst, dst); int w = ctx->dpyAttr[dpy].xres; int h = ctx->dpyAttr[dpy].yres; int dst_w = dst.right - dst.left; int dst_h = dst.bottom - dst.top; uint32_t color = layer->transform; Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888)); ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL); if (layer->blending == HWC_BLENDING_PREMULT) ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT); PipeArgs parg(mdpFlags, whf, z, static_cast<eRotFlags>(0), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); // Configure MDP pipe for Color layer Dim pos(dst.left, dst.top, dst_w, dst_h); ctx->mOverlay->setSource(parg, dest); ctx->mOverlay->setColor(color, dest); ctx->mOverlay->setTransform(0, dest); ctx->mOverlay->setCrop(pos, dest); ctx->mOverlay->setPosition(pos, dest); if (!ctx->mOverlay->commit(dest)) { ALOGE("%s: Configure color layer failed!", __FUNCTION__); return -1; } return 0; } void updateSource(eTransform& orient, Whf& whf, hwc_rect_t& crop, Rotator *rot) { Dim transformedCrop(crop.left, crop.top, crop.right - crop.left, crop.bottom - crop.top); if (qdutils::MDPVersion::getInstance().getMDPVersion() >= qdutils::MDSS_V5) { //B-family rotator internally could modify destination dimensions if //downscaling is supported whf = rot->getDstWhf(); transformedCrop = rot->getDstDimensions(); } else { //A-family rotator rotates entire buffer irrespective of crop, forcing //us to recompute the crop based on transform orient = static_cast<eTransform>(ovutils::getMdpOrient(orient)); preRotateSource(orient, whf, transformedCrop); } crop.left = transformedCrop.x; crop.top = transformedCrop.y; crop.right = transformedCrop.x + transformedCrop.w; crop.bottom = transformedCrop.y + transformedCrop.h; } bool configHwCursor(const int fd, int dpy, hwc_layer_1_t* layer) { if(dpy > HWC_DISPLAY_PRIMARY) { // HWCursor not supported on secondary displays return false; } private_handle_t *hnd = (private_handle_t *)layer->handle; hwc_rect dst = layer->displayFrame; hwc_rect src = integerizeSourceCrop(layer->sourceCropf); int srcW = src.right - src.left; int srcH = src.bottom - src.top; int dstW = dst.right - dst.left; int dstH = dst.bottom - dst.top; Whf whf(getWidth(hnd), getHeight(hnd), hnd->format); Dim crop(src.left, src.top, srcW, srcH); Dim dest(dst.left, dst.top, dstW, dstH); ovutils::PipeArgs pargs(ovutils::OV_MDP_FLAGS_NONE, whf, Z_SYSTEM_ALLOC, ovutils::ROT_FLAGS_NONE, layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); ALOGD_IF(HWC_UTILS_DEBUG, "%s: CursorInfo: w = %d h = %d " "crop [%d, %d, %d, %d] dst [%d, %d, %d, %d]", __FUNCTION__, getWidth(hnd), getHeight(hnd), src.left, src.top, srcW, srcH, dst.left, dst.top, dstW, dstH); return HWCursor::getInstance()->config(fd, (void*)hnd->base, pargs, crop, dest); } void freeHwCursor(const int fd, int dpy) { if (dpy == HWC_DISPLAY_PRIMARY) { HWCursor::getInstance()->free(fd); } } int getRotDownscale(hwc_context_t *ctx, const hwc_layer_1_t *layer) { if(not qdutils::MDPVersion::getInstance().isRotDownscaleEnabled()) { return 0; } int downscale = 0; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t dst = layer->displayFrame; private_handle_t *hnd = (private_handle_t *)layer->handle; if(not hnd) { return 0; } MetaData_t *metadata = (MetaData_t *)hnd->base_metadata; bool isInterlaced = metadata && (metadata->operation & PP_PARAM_INTERLACED) && metadata->interlaced; int transform = layer->transform; uint32_t format = ovutils::getMdpFormat(hnd->format, hnd->flags); if(isYuvBuffer(hnd)) { if(ctx->mMDP.version >= qdutils::MDP_V4_2 && ctx->mMDP.version < qdutils::MDSS_V5) { downscale = Rotator::getDownscaleFactor(crop.right - crop.left, crop.bottom - crop.top, dst.right - dst.left, dst.bottom - dst.top, format, isInterlaced); } else { Dim adjCrop(crop.left, crop.top, crop.right - crop.left, crop.bottom - crop.top); Dim pos(dst.left, dst.top, dst.right - dst.left, dst.bottom - dst.top); if(transform & HAL_TRANSFORM_ROT_90) { swap(adjCrop.w, adjCrop.h); } downscale = Rotator::getDownscaleFactor(adjCrop.w, adjCrop.h, pos.w, pos.h, format, isInterlaced); } } return downscale; } bool isZoomModeEnabled(hwc_rect_t crop) { // This does not work for zooming in top left corner of the image return(crop.top > 0 || crop.left > 0); } void updateCropAIVVideoMode(hwc_context_t *ctx, hwc_rect_t& crop, int dpy) { ALOGD_IF(HWC_UTILS_DEBUG, "dpy %d Source crop [%d %d %d %d]", dpy, crop.left, crop.top, crop.right, crop.bottom); if(isZoomModeEnabled(crop)) { Dim srcCrop(crop.left, crop.top, crop.right - crop.left, crop.bottom - crop.top); int extW = ctx->dpyAttr[dpy].xres; int extH = ctx->dpyAttr[dpy].yres; //Crop the original video in order to fit external display aspect ratio if(srcCrop.w * extH < extW * srcCrop.h) { int offset = (srcCrop.h - ((srcCrop.w * extH) / extW)) / 2; crop.top += offset; crop.bottom -= offset; } else { int offset = (srcCrop.w - ((extW * srcCrop.h) / extH)) / 2; crop.left += offset; crop.right -= offset; } ALOGD_IF(HWC_UTILS_DEBUG, "External Resolution [%d %d] dpy %d Modified" " source crop [%d %d %d %d]", extW, extH, dpy, crop.left, crop.top, crop.right, crop.bottom); } } void updateDestAIVVideoMode(hwc_context_t *ctx, hwc_rect_t crop, hwc_rect_t& dst, int dpy) { ALOGD_IF(HWC_UTILS_DEBUG, "dpy %d Destination position [%d %d %d %d]", dpy, dst.left, dst.top, dst.right, dst.bottom); Dim srcCrop(crop.left, crop.top, crop.right - crop.left, crop.bottom - crop.top); int extW = ctx->dpyAttr[dpy].xres; int extH = ctx->dpyAttr[dpy].yres; // Set the destination coordinates of external display to full screen, // when zoom in mode is enabled or the ratio between video aspect ratio // and external display aspect ratio is below the minimum tolerance level // and above maximum tolerance level float videoAspectRatio = ((float)srcCrop.w / (float)srcCrop.h); float extDisplayAspectRatio = ((float)extW / (float)extH); float videoToExternalRatio = videoAspectRatio / extDisplayAspectRatio; if((fabs(1.0f - videoToExternalRatio) <= ctx->mAspectRatioToleranceLevel) || (isZoomModeEnabled(crop))) { dst.left = 0; dst.top = 0; dst.right = extW; dst.bottom = extH; } ALOGD_IF(HWC_UTILS_DEBUG, "External Resolution [%d %d] dpy %d Modified" " Destination position [%d %d %d %d] Source crop [%d %d %d %d]", extW, extH, dpy, dst.left, dst.top, dst.right, dst.bottom, crop.left, crop.top, crop.right, crop.bottom); } void updateCoordinates(hwc_context_t *ctx, hwc_rect_t& crop, hwc_rect_t& dst, int dpy) { updateCropAIVVideoMode(ctx, crop, dpy); updateDestAIVVideoMode(ctx, crop, dst, dpy); } int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy, eMdpFlags& mdpFlags, eZorder& z, const eDest& dest, Rotator **rot) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(!hnd) { if (layer->flags & HWC_COLOR_FILL) { // Configure Color layer return configColorLayer(ctx, layer, dpy, mdpFlags, z, dest); } ALOGE("%s: layer handle is NULL", __FUNCTION__); return -1; } MetaData_t *metadata = (MetaData_t *)hnd->base_metadata; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t dst = layer->displayFrame; int transform = layer->transform; eTransform orient = static_cast<eTransform>(transform); int rotFlags = ovutils::ROT_FLAGS_NONE; uint32_t format = ovutils::getMdpFormat(hnd->format, hnd->flags); Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size); // Handle R/B swap if (layer->flags & HWC_FORMAT_RB_SWAP) { if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888) whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888); else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888) whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888); } // update source crop and destination position of AIV video layer. if(ctx->listStats[dpy].mAIVVideoMode && isYuvBuffer(hnd)) { updateCoordinates(ctx, crop, dst, dpy); } calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient); int downscale = getRotDownscale(ctx, layer); setMdpFlags(ctx, layer, mdpFlags, downscale, transform); //if 90 component or downscale, use rot if((has90Transform(layer) or downscale) and isRotationDoable(ctx, hnd)) { *rot = ctx->mRotMgr->getNext(); if(*rot == NULL) return -1; ctx->mLayerRotMap[dpy]->add(layer, *rot); BwcPM::setBwc(ctx, dpy, hnd, crop, dst, transform, downscale, mdpFlags); uint32_t frame_rate = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].refreshRate; if(!dpy && !isSecondaryConnected(ctx)) { if(metadata && (metadata->operation & UPDATE_REFRESH_RATE)) frame_rate = metadata->refreshrate; } //Configure rotator for pre-rotation if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale, frame_rate) < 0) { ALOGE("%s: configRotator failed!", __FUNCTION__); return -1; } updateSource(orient, whf, crop, *rot); rotFlags |= ROT_PREROTATED; } //For the mdp, since either we are pre-rotating or MDP does flips orient = OVERLAY_TRANSFORM_0; transform = 0; PipeArgs parg(mdpFlags, whf, z, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) { ALOGE("%s: commit failed for low res panel", __FUNCTION__); return -1; } return 0; } //Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR, private_handle_t *hnd) { if(cropL.right - cropL.left) { if(isYuvBuffer(hnd)) { //Always safe to even down left ovutils::even_floor(cropL.left); //If right is even, automatically width is even, since left is //already even ovutils::even_floor(cropL.right); } //Make sure there are no gaps between left and right splits if the layer //is spread across BOTH halves if(cropR.right - cropR.left) { cropR.left = cropL.right; } } if(cropR.right - cropR.left) { if(isYuvBuffer(hnd)) { //Always safe to even down left ovutils::even_floor(cropR.left); //If right is even, automatically width is even, since left is //already even ovutils::even_floor(cropR.right); } } } int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z, const eDest& lDest, const eDest& rDest, Rotator **rot) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(!hnd) { ALOGE("%s: layer handle is NULL", __FUNCTION__); return -1; } MetaData_t *metadata = (MetaData_t *)hnd->base_metadata; int hw_w = ctx->dpyAttr[dpy].xres; int hw_h = ctx->dpyAttr[dpy].yres; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t dst = layer->displayFrame; int transform = layer->transform; eTransform orient = static_cast<eTransform>(transform); int rotFlags = ROT_FLAGS_NONE; uint32_t format = ovutils::getMdpFormat(hnd->format, hnd->flags); Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size); // Handle R/B swap if (layer->flags & HWC_FORMAT_RB_SWAP) { if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888) whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888); else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888) whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888); } // update source crop and destination position of AIV video layer. if(ctx->listStats[dpy].mAIVVideoMode && isYuvBuffer(hnd)) { updateCoordinates(ctx, crop, dst, dpy); } /* Calculate the external display position based on MDP downscale, ActionSafe, and extorientation features. */ calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient); int downscale = getRotDownscale(ctx, layer); setMdpFlags(ctx, layer, mdpFlagsL, downscale, transform); if(lDest != OV_INVALID && rDest != OV_INVALID) { //Enable overfetch setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE); } //Will do something only if feature enabled and conditions suitable //hollow call otherwise if(ctx->mAD->prepare(ctx, crop, whf, hnd)) { overlay::Writeback *wb = overlay::Writeback::getInstance(); whf.format = wb->getOutputFormat(); } if((has90Transform(layer) or downscale) and isRotationDoable(ctx, hnd)) { (*rot) = ctx->mRotMgr->getNext(); if((*rot) == NULL) return -1; ctx->mLayerRotMap[dpy]->add(layer, *rot); uint32_t frame_rate = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].refreshRate; if(!dpy && !isSecondaryConnected(ctx)) { if(metadata && (metadata->operation & UPDATE_REFRESH_RATE)) frame_rate = metadata->refreshrate; } //Configure rotator for pre-rotation if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale, frame_rate) < 0) { ALOGE("%s: configRotator failed!", __FUNCTION__); return -1; } updateSource(orient, whf, crop, *rot); rotFlags |= ROT_PREROTATED; } eMdpFlags mdpFlagsR = mdpFlagsL; setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER); hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0}; hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0}; const int lSplit = getLeftSplit(ctx, dpy); // Calculate Left rects if(dst.left < lSplit) { tmp_cropL = crop; tmp_dstL = dst; hwc_rect_t scissor = {0, 0, lSplit, hw_h }; scissor = getIntersection(ctx->mViewFrame[dpy], scissor); qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0); } // Calculate Right rects if(dst.right > lSplit) { tmp_cropR = crop; tmp_dstR = dst; hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h }; scissor = getIntersection(ctx->mViewFrame[dpy], scissor); qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0); } sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd); //When buffer is H-flipped, contents of mixer config also needs to swapped //Not needed if the layer is confined to one half of the screen. //If rotator has been used then it has also done the flips, so ignore them. if((orient & OVERLAY_TRANSFORM_FLIP_H) && (dst.left < lSplit) && (dst.right > lSplit) && (*rot) == NULL) { hwc_rect_t new_cropR; new_cropR.left = tmp_cropL.left; new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left); hwc_rect_t new_cropL; new_cropL.left = new_cropR.right; new_cropL.right = tmp_cropR.right; tmp_cropL.left = new_cropL.left; tmp_cropL.right = new_cropL.right; tmp_cropR.left = new_cropR.left; tmp_cropR.right = new_cropR.right; } //For the mdp, since either we are pre-rotating or MDP does flips orient = OVERLAY_TRANSFORM_0; transform = 0; //configure left mixer if(lDest != OV_INVALID) { PipeArgs pargL(mdpFlagsL, whf, z, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, pargL, orient, tmp_cropL, tmp_dstL, metadata, lDest) < 0) { ALOGE("%s: commit failed for left mixer config", __FUNCTION__); return -1; } } //configure right mixer if(rDest != OV_INVALID) { PipeArgs pargR(mdpFlagsR, whf, z, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); tmp_dstR.right = tmp_dstR.right - lSplit; tmp_dstR.left = tmp_dstR.left - lSplit; if(configMdp(ctx->mOverlay, pargR, orient, tmp_cropR, tmp_dstR, metadata, rDest) < 0) { ALOGE("%s: commit failed for right mixer config", __FUNCTION__); return -1; } } return 0; } int configure3DVideo(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z, const eDest& lDest, const eDest& rDest, Rotator **rot) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(!hnd) { ALOGE("%s: layer handle is NULL", __FUNCTION__); return -1; } //Both pipes are configured to the same mixer eZorder lz = z; eZorder rz = (eZorder)(z + 1); MetaData_t *metadata = (MetaData_t *)hnd->base_metadata; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf); hwc_rect_t dst = layer->displayFrame; int transform = layer->transform; eTransform orient = static_cast<eTransform>(transform); int rotFlags = ROT_FLAGS_NONE; uint32_t format = ovutils::getMdpFormat(hnd->format, hnd->flags); Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size); int downscale = getRotDownscale(ctx, layer); setMdpFlags(ctx, layer, mdpFlagsL, downscale, transform); //XXX: Check if rotation is supported and valid for 3D if((has90Transform(layer) or downscale) and isRotationDoable(ctx, hnd)) { (*rot) = ctx->mRotMgr->getNext(); if((*rot) == NULL) return -1; ctx->mLayerRotMap[dpy]->add(layer, *rot); uint32_t frame_rate = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].refreshRate; if(!dpy && !isSecondaryConnected(ctx)) { if(metadata && (metadata->operation & UPDATE_REFRESH_RATE)) frame_rate = metadata->refreshrate; } //Configure rotator for pre-rotation if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale, frame_rate) < 0) { ALOGE("%s: configRotator failed!", __FUNCTION__); return -1; } updateSource(orient, whf, crop, *rot); rotFlags |= ROT_PREROTATED; } eMdpFlags mdpFlagsR = mdpFlagsL; hwc_rect_t cropL = crop, dstL = dst; hwc_rect_t cropR = crop, dstR = dst; int hw_w = ctx->dpyAttr[dpy].xres; int hw_h = ctx->dpyAttr[dpy].yres; if(get3DFormat(hnd) == HAL_3D_SIDE_BY_SIDE_L_R || get3DFormat(hnd) == HAL_3D_SIDE_BY_SIDE_R_L) { // Calculate Left rects // XXX: This assumes crop.right/2 is the center point of the video cropL.right = crop.right/2; dstL.left = dst.left/2; dstL.right = dst.right/2; // Calculate Right rects cropR.left = crop.right/2; dstR.left = hw_w/2 + dst.left/2; dstR.right = hw_w/2 + dst.right/2; } else if(get3DFormat(hnd) == HAL_3D_TOP_BOTTOM) { // Calculate Left rects cropL.bottom = crop.bottom/2; dstL.top = dst.top/2; dstL.bottom = dst.bottom/2; // Calculate Right rects cropR.top = crop.bottom/2; dstR.top = hw_h/2 + dst.top/2; dstR.bottom = hw_h/2 + dst.bottom/2; } else { ALOGE("%s: Unsupported 3D mode ", __FUNCTION__); return -1; } //For the mdp, since either we are pre-rotating or MDP does flips orient = OVERLAY_TRANSFORM_0; transform = 0; //configure left pipe if(lDest != OV_INVALID) { PipeArgs pargL(mdpFlagsL, whf, lz, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, pargL, orient, cropL, dstL, metadata, lDest) < 0) { ALOGE("%s: commit failed for left mixer config", __FUNCTION__); return -1; } } //configure right pipe if(rDest != OV_INVALID) { PipeArgs pargR(mdpFlagsR, whf, rz, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, pargR, orient, cropR, dstR, metadata, rDest) < 0) { ALOGE("%s: commit failed for right mixer config", __FUNCTION__); return -1; } } return 0; } int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z, const eDest& lDest, const eDest& rDest, Rotator **rot) { private_handle_t *hnd = (private_handle_t *)layer->handle; if(!hnd) { ALOGE("%s: layer handle is NULL", __FUNCTION__); return -1; } MetaData_t *metadata = (MetaData_t *)hnd->base_metadata; hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);; hwc_rect_t dst = layer->displayFrame; int transform = layer->transform; eTransform orient = static_cast<eTransform>(transform); const int downscale = 0; int rotFlags = ROT_FLAGS_NONE; //Splitting only YUV layer on primary panel needs different zorders //for both layers as both the layers are configured to single mixer eZorder lz = z; eZorder rz = (eZorder)(z + 1); Whf whf(getWidth(hnd), getHeight(hnd), getMdpFormat(hnd->format), (uint32_t)hnd->size); // update source crop and destination position of AIV video layer. if(ctx->listStats[dpy].mAIVVideoMode && isYuvBuffer(hnd)) { updateCoordinates(ctx, crop, dst, dpy); } /* Calculate the external display position based on MDP downscale, ActionSafe, and extorientation features. */ calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient); setMdpFlags(ctx, layer, mdpFlagsL, 0, transform); trimLayer(ctx, dpy, transform, crop, dst); if(has90Transform(layer) && isRotationDoable(ctx, hnd)) { (*rot) = ctx->mRotMgr->getNext(); if((*rot) == NULL) return -1; ctx->mLayerRotMap[dpy]->add(layer, *rot); uint32_t frame_rate = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].refreshRate; if(!dpy && !isSecondaryConnected(ctx)) { if(metadata && (metadata->operation & UPDATE_REFRESH_RATE)) frame_rate = metadata->refreshrate; } //Configure rotator for pre-rotation if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale, frame_rate) < 0) { ALOGE("%s: configRotator failed!", __FUNCTION__); return -1; } updateSource(orient, whf, crop, *rot); rotFlags |= ROT_PREROTATED; } eMdpFlags mdpFlagsR = mdpFlagsL; int lSplit = dst.left + (dst.right - dst.left)/2; hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0}; hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0}; if(lDest != OV_INVALID) { tmp_cropL = crop; tmp_dstL = dst; hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom }; qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0); } if(rDest != OV_INVALID) { tmp_cropR = crop; tmp_dstR = dst; hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom }; qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0); } sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd); //When buffer is H-flipped, contents of mixer config also needs to swapped //Not needed if the layer is confined to one half of the screen. //If rotator has been used then it has also done the flips, so ignore them. if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID && rDest != OV_INVALID && (*rot) == NULL) { hwc_rect_t new_cropR; new_cropR.left = tmp_cropL.left; new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left); hwc_rect_t new_cropL; new_cropL.left = new_cropR.right; new_cropL.right = tmp_cropR.right; tmp_cropL.left = new_cropL.left; tmp_cropL.right = new_cropL.right; tmp_cropR.left = new_cropR.left; tmp_cropR.right = new_cropR.right; } //For the mdp, since either we are pre-rotating or MDP does flips orient = OVERLAY_TRANSFORM_0; transform = 0; //configure left half if(lDest != OV_INVALID) { PipeArgs pargL(mdpFlagsL, whf, lz, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, pargL, orient, tmp_cropL, tmp_dstL, metadata, lDest) < 0) { ALOGE("%s: commit failed for left half config", __FUNCTION__); return -1; } } //configure right half if(rDest != OV_INVALID) { PipeArgs pargR(mdpFlagsR, whf, rz, static_cast<eRotFlags>(rotFlags), layer->planeAlpha, (ovutils::eBlending) getBlending(layer->blending)); if(configMdp(ctx->mOverlay, pargR, orient, tmp_cropR, tmp_dstR, metadata, rDest) < 0) { ALOGE("%s: commit failed for right half config", __FUNCTION__); return -1; } } return 0; } bool canUseRotator(hwc_context_t *ctx, int dpy) { if(ctx->mOverlay->isDMAMultiplexingSupported() && isSecondaryConnected(ctx) && !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) { /* mdss driver on certain targets support multiplexing of DMA pipe * in LINE and BLOCK modes for writeback panels. */ if(dpy == HWC_DISPLAY_PRIMARY) return false; } if((ctx->mMDP.version == qdutils::MDP_V3_0_4) ||(ctx->mMDP.version == qdutils::MDP_V3_0_5)) return false; return true; } int getLeftSplit(hwc_context_t *ctx, const int& dpy) { //Default even split for all displays with high res int lSplit = ctx->dpyAttr[dpy].xres / 2; if(dpy == HWC_DISPLAY_PRIMARY && qdutils::MDPVersion::getInstance().getLeftSplit()) { //Override if split published by driver for primary lSplit = qdutils::MDPVersion::getInstance().getLeftSplit(); } return lSplit; } bool isDisplaySplit(hwc_context_t* ctx, int dpy) { qdutils::MDPVersion& mdpHw = qdutils::MDPVersion::getInstance(); if(ctx->dpyAttr[dpy].xres > mdpHw.getMaxMixerWidth()) { return true; } if(dpy == HWC_DISPLAY_PRIMARY && mdpHw.getRightSplit()) { return true; } return false; } //clear prev layer prop flags and realloc for current frame void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) { if(ctx->layerProp[dpy]) { delete[] ctx->layerProp[dpy]; ctx->layerProp[dpy] = NULL; } ctx->layerProp[dpy] = new LayerProp[numAppLayers]; } bool isAbcInUse(hwc_context_t *ctx){ return (ctx->enableABC && ctx->listStats[0].renderBufIndexforABC == 0); } void dumpBuffer(private_handle_t *ohnd, char *bufferName) { if (ohnd != NULL && ohnd->base) { char dumpFilename[PATH_MAX]; bool bResult = false; int width = getWidth(ohnd); int height = getHeight(ohnd); int format = ohnd->format; //dummy aligned w & h. int alW = 0, alH = 0; int size = getBufferSizeAndDimensions(width, height, format, alW, alH); snprintf(dumpFilename, sizeof(dumpFilename), "/data/%s.%s.%dx%d.raw", bufferName, overlay::utils::getFormatString(utils::getMdpFormat(format)), width, height); FILE* fp = fopen(dumpFilename, "w+"); if (NULL != fp) { bResult = (bool) fwrite((void*)ohnd->base, size, 1, fp); fclose(fp); } ALOGD("Buffer[%s] Dump to %s: %s", bufferName, dumpFilename, bResult ? "Success" : "Fail"); } } bool isGLESComp(hwc_context_t *ctx, hwc_display_contents_1_t* list) { int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers; for(int index = 0; index < numAppLayers; index++) { hwc_layer_1_t* layer = &(list->hwLayers[index]); if(layer->compositionType == HWC_FRAMEBUFFER) return true; } return false; } void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) { #ifdef QTI_BSP struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo; if(!gpuHint->mGpuPerfModeEnable || !ctx || !list) return; /* Set the GPU hint flag to high for MIXED/GPU composition only for first frame after MDP -> GPU/MIXED mode transition. Set the GPU hint to default if the previous composition is GPU or current GPU composition is due to idle fallback */ if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) { gpuHint->mEGLDisplay = (*(ctx->mpfn_eglGetCurrentDisplay))(); if(!gpuHint->mEGLDisplay) { ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__); return; } gpuHint->mEGLContext = (*(ctx->mpfn_eglGetCurrentContext))(); if(!gpuHint->mEGLContext) { ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__); return; } } if(isGLESComp(ctx, list)) { if(gpuHint->mCompositionState != COMPOSITION_STATE_GPU && !MDPComp::isIdleFallback()) { EGLint attr_list[] = {EGL_GPU_HINT_1, EGL_GPU_LEVEL_3, EGL_NONE }; if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) && !((*(ctx->mpfn_eglGpuPerfHintQCOM))(gpuHint->mEGLDisplay, gpuHint->mEGLContext, attr_list))) { ALOGW("eglGpuPerfHintQCOM failed for Built in display"); } else { gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3; gpuHint->mCompositionState = COMPOSITION_STATE_GPU; } } else { EGLint attr_list[] = {EGL_GPU_HINT_1, EGL_GPU_LEVEL_0, EGL_NONE }; if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) && !((*(ctx->mpfn_eglGpuPerfHintQCOM))(gpuHint->mEGLDisplay, gpuHint->mEGLContext, attr_list))) { ALOGW("eglGpuPerfHintQCOM failed for Built in display"); } else { gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0; } if(MDPComp::isIdleFallback()) { gpuHint->mCompositionState = COMPOSITION_STATE_IDLE_FALLBACK; } } } else { /* set the GPU hint flag to default for MDP composition */ EGLint attr_list[] = {EGL_GPU_HINT_1, EGL_GPU_LEVEL_0, EGL_NONE }; if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) && !((*(ctx->mpfn_eglGpuPerfHintQCOM))(gpuHint->mEGLDisplay, gpuHint->mEGLContext, attr_list))) { ALOGW("eglGpuPerfHintQCOM failed for Built in display"); } else { gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0; } gpuHint->mCompositionState = COMPOSITION_STATE_MDP; } #endif } bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2) { // To be peripheral, 3 boundaries should match. uint8_t eqBounds = 0; if (rect1.left == rect2.left) eqBounds++; if (rect1.top == rect2.top) eqBounds++; if (rect1.right == rect2.right) eqBounds++; if (rect1.bottom == rect2.bottom) eqBounds++; return (eqBounds == 3); } void processBootAnimCompleted(hwc_context_t *ctx, hwc_display_contents_1_t *list) { const uint32_t numBootUpLayers = 2; /* All other checks namely "init.svc.bootanim" or * HWC_GEOMETRY_CHANGED fail in correctly identifying the * exact bootup transition to homescreen */ char cryptoState[PROPERTY_VALUE_MAX]; char voldDecryptState[PROPERTY_VALUE_MAX]; bool isEncrypted = false; bool main_class_services_started = false; if(property_get("ro.crypto.state", cryptoState, "unencrypted")) { ALOGD_IF(HWC_UTILS_DEBUG, "%s: cryptostate= %s", \ __FUNCTION__, cryptoState); if(!strcmp(cryptoState, "encrypted")) { isEncrypted = true; if(property_get("vold.decrypt", voldDecryptState, "") && !strcmp(voldDecryptState, "trigger_restart_framework")) main_class_services_started = true; ALOGD_IF(HWC_UTILS_DEBUG, "%s: vold= %s", __FUNCTION__, \ voldDecryptState); } } if((!isEncrypted ||(isEncrypted && main_class_services_started)) && (list->numHwLayers > numBootUpLayers)) { // Applying default mode after bootanimation is finished And // If Data is Encrypted, it is ready for access. ctx->mBootAnimCompleted = true; qdcmApplyDefaultAfterBootAnimationDone(ctx); ALOGD_IF(HWC_UTILS_DEBUG, "%s: SettingDefaultMode ", __FUNCTION__); } } void BwcPM::setBwc(const hwc_context_t *ctx, const int& dpy, const private_handle_t *hnd, const hwc_rect_t& crop, const hwc_rect_t& dst, const int& transform,const int& downscale, ovutils::eMdpFlags& mdpFlags) { //Target doesnt support Bwc qdutils::MDPVersion& mdpHw = qdutils::MDPVersion::getInstance(); if(not mdpHw.supportsBWC()) { return; } //Disabled at runtime if(not ctx->mBWCEnabled) return; //BWC not supported with rot-downscale if(downscale) return; //Not enabled for secondary displays if(dpy) return; //Not enabled for non-video buffers if(not isYuvBuffer(hnd)) return; int src_w = crop.right - crop.left; int src_h = crop.bottom - crop.top; int dst_w = dst.right - dst.left; int dst_h = dst.bottom - dst.top; if(transform & HAL_TRANSFORM_ROT_90) { swap(src_w, src_h); } //src width > MAX mixer supported dim if(src_w > (int) qdutils::MDPVersion::getInstance().getMaxPipeWidth()) { return; } //H/w requirement for BWC only. Pipe can still support 4096 if(src_h > 4092) { return; } //Decimation necessary, cannot use BWC. H/W requirement. if(qdutils::MDPVersion::getInstance().supportsDecimation()) { uint8_t horzDeci = 0; uint8_t vertDeci = 0; ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horzDeci, vertDeci); if(horzDeci || vertDeci) return; } ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN); } void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) { if(mCount >= RotMgr::MAX_ROT_SESS) return; mLayer[mCount] = layer; mRot[mCount] = rot; mCount++; } void LayerRotMap::reset() { for (int i = 0; i < RotMgr::MAX_ROT_SESS; i++) { mLayer[i] = 0; mRot[i] = 0; } mCount = 0; } void LayerRotMap::clear() { RotMgr::getInstance()->markUnusedTop(mCount); reset(); } bool LayerRotMap::isRotCached(uint32_t index) const { overlay::Rotator* rot = getRot(index); hwc_layer_1_t* layer = getLayer(index); if(rot and layer and layer->handle) { private_handle_t *hnd = (private_handle_t *)(layer->handle); return (rot->isRotCached(hnd->fd,(uint32_t)(hnd->offset))); } return false; } void LayerRotMap::setReleaseFd(const int& fence) { for(uint32_t i = 0; i < mCount; i++) { if(mRot[i] and mLayer[i] and mLayer[i]->handle) { /* Ensure that none of the above (Rotator-instance, * layer and layer-handle) are NULL*/ if(isRotCached(i)) mRot[i]->setPrevBufReleaseFd(dup(fence)); else mRot[i]->setCurrBufReleaseFd(dup(fence)); } } } hwc_rect expandROIFromMidPoint(hwc_rect roi, hwc_rect fullFrame) { int lRoiWidth = 0, rRoiWidth = 0; int half_frame_width = fullFrame.right/2; hwc_rect lFrame = fullFrame; hwc_rect rFrame = fullFrame; lFrame.right = (lFrame.right - lFrame.left)/2; rFrame.left = lFrame.right; hwc_rect lRoi = getIntersection(roi, lFrame); hwc_rect rRoi = getIntersection(roi, rFrame); lRoiWidth = lRoi.right - lRoi.left; rRoiWidth = rRoi.right - rRoi.left; if(lRoiWidth && rRoiWidth) { if(lRoiWidth < rRoiWidth) roi.left = half_frame_width - rRoiWidth; else roi.right = half_frame_width + lRoiWidth; } return roi; } void resetROI(hwc_context_t *ctx, const int dpy) { const int fbXRes = (int)ctx->dpyAttr[dpy].xres; const int fbYRes = (int)ctx->dpyAttr[dpy].yres; /* When source split is enabled, both the panels are calibrated * in a single coordinate system. So only one ROI is generated * for the whole panel extending equally from the midpoint and * populated for the left side. */ if(!qdutils::MDPVersion::getInstance().isSrcSplit() && isDisplaySplit(ctx, dpy)) { const int lSplit = getLeftSplit(ctx, dpy); ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes}; ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes}; } else { ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes}; ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0}; } } hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary) { if(!isValidRect(roi)) return roi; struct hwc_rect t_roi = roi; const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign(); const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign(); const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign(); const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign(); int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth(); const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight(); bool isPingPongSplitEnabled = (qdutils::MDPVersion::getInstance().is8976() && qdutils::MDPVersion::getInstance().isPingPongSplit()); /* Assumptions: * LEFT_ALIGN, WIDTH_ALIGN, TOP_ALIGN, HEIGHT_ALIGN are typically even */ if(isPingPongSplitEnabled) { MIN_WIDTH *= 2; const int boundarywidth = (boundary.right - boundary.left); if(t_roi.left > boundarywidth/2) { /* roi-left should be left of boundarywidth */ t_roi.left = boundarywidth - t_roi.left; } if(t_roi.right < boundarywidth/2) { /* roi-right should be right of boundarywidth */ t_roi.right = boundarywidth - t_roi.right; } if((boundarywidth/2 - t_roi.left) > (t_roi.right - boundarywidth/2)) { t_roi.right = boundarywidth - t_roi.left; } else { t_roi.left = boundarywidth - t_roi.right; } } /* Ensure roi is of minimum width recommended by the panel */ if((t_roi.right - t_roi.left) < MIN_WIDTH) { const int corWidth = MIN_WIDTH - (t_roi.right - t_roi.left); t_roi.left = t_roi.left - (corWidth >> 1); t_roi.right = t_roi.right + (corWidth >> 1) + (corWidth & 1); if(isPingPongSplitEnabled) t_roi.left -= (corWidth & 1); if(t_roi.left < boundary.left) { t_roi.left = boundary.left; if(isPingPongSplitEnabled) t_roi.right = boundary.right; else t_roi.right = t_roi.left + MIN_WIDTH; } else if(t_roi.right > boundary.right) { t_roi.right = boundary.right; if(isPingPongSplitEnabled) t_roi.left = boundary.left; else t_roi.left = t_roi.right - MIN_WIDTH; } } /* Ensuire roi is of minimum height recommended by the panel */ if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) { const int corHeight = MIN_HEIGHT - (t_roi.bottom - t_roi.top); t_roi.top = t_roi.top - (corHeight >> 1); t_roi.bottom = t_roi.bottom + (corHeight >> 1) + (corHeight & 1); if(isPingPongSplitEnabled) t_roi.top -= (corHeight & 1); if(t_roi.top < boundary.top) { t_roi.top = boundary.top; if(isPingPongSplitEnabled) t_roi.bottom = boundary.bottom; else t_roi.bottom = t_roi.top + MIN_HEIGHT; } else if(t_roi.bottom > boundary.bottom) { t_roi.bottom = boundary.bottom; if(isPingPongSplitEnabled) t_roi.top = boundary.top; else t_roi.top = t_roi.bottom - MIN_HEIGHT; } } /* Align left and width to meet panel restrictions */ if(LEFT_ALIGN) { const int alignedWidthDiff = (t_roi.left % LEFT_ALIGN); t_roi.left -= alignedWidthDiff; if(isPingPongSplitEnabled) t_roi.right += alignedWidthDiff; } if(WIDTH_ALIGN) { int width = t_roi.right - t_roi.left; int alignWidth = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN); int corWidth = alignWidth - width; t_roi.left = t_roi.left - (corWidth >> 1); t_roi.right = t_roi.right + (corWidth >> 1) + (corWidth & 1); if(LEFT_ALIGN && (t_roi.left % LEFT_ALIGN)) { int errLeft = t_roi.left % LEFT_ALIGN; t_roi.left = t_roi.left - errLeft; t_roi.right = t_roi.right + WIDTH_ALIGN - errLeft; } if(t_roi.right > boundary.right || t_roi.left < boundary.left) { //Give up and go for complete width t_roi.left = boundary.left; t_roi.right = boundary.right; } } /* Align top and height to meet panel restrictions */ if(TOP_ALIGN) { const int alignedHeightDiff = (t_roi.top % TOP_ALIGN); t_roi.top -= alignedHeightDiff; if(isPingPongSplitEnabled) t_roi.bottom += alignedHeightDiff; } if(HEIGHT_ALIGN) { int height = t_roi.bottom - t_roi.top; int alignHeight = HEIGHT_ALIGN * ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN); int corHeight = alignHeight - height; t_roi.top = t_roi.top - (corHeight >> 1); t_roi.bottom = t_roi.bottom + (corHeight >> 1) + (corHeight & 1); if(TOP_ALIGN && (t_roi.top % TOP_ALIGN)) { int errTop = t_roi.top % TOP_ALIGN; t_roi.top = t_roi.top - errTop; t_roi.bottom = t_roi.bottom + HEIGHT_ALIGN - errTop; } if(t_roi.bottom > boundary.bottom || t_roi.top < boundary.top) { //Give up and go for complete height t_roi.top = boundary.top; t_roi.bottom = boundary.bottom; } } return t_roi; } void handle_pause(hwc_context_t* ctx, int dpy) { if(ctx->dpyAttr[dpy].connected) { ctx->mDrawLock.lock(); ctx->dpyAttr[dpy].isActive = true; ctx->dpyAttr[dpy].isPause = true; ctx->proc->invalidate(ctx->proc); // Wait for 1 composition to finish ctx->mDrawLock.wait(); // At this point all the pipes used by External have been // marked as UNSET. // Perform commit to unstage the pipes. if (!Overlay::displayCommit(ctx->dpyAttr[dpy].fd)) { ALOGE("%s: display commit fail! for %d dpy", __FUNCTION__, dpy); } ctx->mDrawLock.unlock(); ctx->proc->invalidate(ctx->proc); } return; } void handle_resume(hwc_context_t* ctx, int dpy) { if(ctx->dpyAttr[dpy].connected) { ctx->mDrawLock.lock(); ctx->dpyAttr[dpy].isConfiguring = true; ctx->dpyAttr[dpy].isActive = true; ctx->proc->invalidate(ctx->proc); //Wait for 1 composition to finish ctx->mDrawLock.wait(); //At this point external has all the pipes it would need. ctx->dpyAttr[dpy].isPause = false; ctx->mDrawLock.unlock(); ctx->proc->invalidate(ctx->proc); } return; } void clearPipeResources(hwc_context_t* ctx, int dpy) { if(ctx->mOverlay) { ctx->mOverlay->configBegin(); ctx->mOverlay->configDone(); } if(ctx->mRotMgr) { ctx->mRotMgr->clear(); } // Call a display commit to ensure that pipes and associated // fd's are cleaned up. if(!Overlay::displayCommit(ctx->dpyAttr[dpy].fd)) { ALOGE("%s: display commit failed for %d", __FUNCTION__, dpy); } } // Handles online events when HDMI is the primary display. In particular, // online events for hdmi connected before AND after boot up and HWC init. void handle_online(hwc_context_t* ctx, int dpy) { // Close the current fd if it was opened earlier on when HWC // was initialized. if (ctx->dpyAttr[dpy].fd >= 0) { close(ctx->dpyAttr[dpy].fd); ctx->dpyAttr[dpy].fd = -1; } // TODO: If HDMI is connected after the display has booted up, // and the best configuration is different from the default // then we need to deal with this appropriately. int error = ctx->mHDMIDisplay->configure(); if (error < 0) { ALOGE("Error opening FrameBuffer"); return; } updateDisplayInfo(ctx, dpy); initCompositionResources(ctx, dpy); ctx->dpyAttr[dpy].connected = true; } // Handles offline events for HDMI. This can be used for offline events // initiated by the HDMI driver and the CEC framework. void handle_offline(hwc_context_t* ctx, int dpy) { destroyCompositionResources(ctx, dpy); // Clear all pipe resources and call a display commit to ensure // that all the fd's are closed. This will ensure that the HDMI // core turns off and that we receive an event the next time the // cable is connected. if (isPrimaryPluggable(ctx)) { clearPipeResources(ctx, dpy); } ctx->mHDMIDisplay->teardown(); resetDisplayInfo(ctx, dpy); ctx->dpyAttr[dpy].connected = false; ctx->dpyAttr[dpy].isActive = false; } int convertS3DFormatToMode(int s3DFormat) { int ret; switch(s3DFormat) { case HAL_3D_SIDE_BY_SIDE_L_R: case HAL_3D_SIDE_BY_SIDE_R_L: ret = HDMI_S3D_SIDE_BY_SIDE; break; case HAL_3D_TOP_BOTTOM: ret = HDMI_S3D_TOP_AND_BOTTOM; break; default: ret = HDMI_S3D_NONE; } return ret; } bool needs3DComposition(hwc_context_t* ctx, int dpy) { return (displaySupports3D(ctx, dpy) && ctx->dpyAttr[dpy].connected && ctx->dpyAttr[dpy].s3dMode != HDMI_S3D_NONE); } void setup3DMode(hwc_context_t *ctx, int dpy, int s3dMode) { if (ctx->dpyAttr[dpy].s3dMode != s3dMode) { ALOGD("%s: setup 3D mode: %d", __FUNCTION__, s3dMode); if(ctx->mHDMIDisplay->configure3D(s3dMode)) { ctx->dpyAttr[dpy].s3dMode = s3dMode; } } } bool displaySupports3D(hwc_context_t* ctx, int dpy) { return ((dpy == HWC_DISPLAY_EXTERNAL) || ((dpy == HWC_DISPLAY_PRIMARY) && isPrimaryPluggable(ctx))); } bool loadEglLib(hwc_context_t* ctx) { bool success = false; #ifdef QTI_BSP dlerror(); ctx->mEglLib = dlopen("libEGL_adreno.so", RTLD_NOW); if(ctx->mEglLib) { *(void **)&(ctx->mpfn_eglGpuPerfHintQCOM) = dlsym(ctx->mEglLib, "eglGpuPerfHintQCOM"); *(void **)&(ctx->mpfn_eglGetCurrentDisplay) = dlsym(ctx->mEglLib,"eglGetCurrentDisplay"); *(void **)&(ctx->mpfn_eglGetCurrentContext) = dlsym(ctx->mEglLib,"eglGetCurrentContext"); if (!ctx->mpfn_eglGpuPerfHintQCOM || !ctx->mpfn_eglGetCurrentDisplay || !ctx->mpfn_eglGetCurrentContext) { ALOGE("Failed to load symbols from libEGL"); dlclose(ctx->mEglLib); ctx->mEglLib = NULL; return false; } success = true; ALOGI("Successfully Loaded GPUPerfHint APIs"); } else { ALOGE("Couldn't load libEGL: %s", dlerror()); } #endif return success; } };//namespace qhwc
[ "sebastian.sariego.benitez@gmail.com" ]
sebastian.sariego.benitez@gmail.com
eebf5b4e0adcca848f3592c84acc6209ab661050
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/chrome/browser/ui/ash/multi_user/multi_user_warning_dialog.h
53fc4bec35f020152895c26ece1be50e4f753c02
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
467
h
// Copyright 2014 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. #ifndef CHROME_BROWSER_UI_ASH_MULTI_USER_MULTI_USER_WARNING_DIALOG_H_ #define CHROME_BROWSER_UI_ASH_MULTI_USER_MULTI_USER_WARNING_DIALOG_H_ #include "base/callback_forward.h" namespace chromeos { void ShowMultiprofilesWarningDialog( const base::Callback<void(bool)>& on_accept); } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
3467b1f72502f1eabce79142813a20e1f3ccb4df
28f18e6b5ec90ecbe68272ef1572f29c3e9b0a53
/test/algorithms/closest_points/ar_ar.cpp
e9c5107b255f861f3782c86df15f2641c5007581
[ "BSL-1.0" ]
permissive
boostorg/geometry
24efac7a54252b7ac25cd2e9154e9228e53b40b7
3755fab69f91a5e466404f17f635308314301303
refs/heads/develop
2023-08-19T01:14:39.091451
2023-07-28T09:14:33
2023-07-28T09:14:33
7,590,021
400
239
BSL-1.0
2023-09-14T17:20:26
2013-01-13T15:59:29
C++
UTF-8
C++
false
false
17,047
cpp
// Boost.Geometry // Unit Test // Copyright (c) 2021, Oracle and/or its affiliates. // Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_closest_points_areal_areal #endif #include "common.hpp" #include "empty_geometry.hpp" namespace bg = boost::geometry; //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_polygon_or_ring_polygon_or_ring(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "polygon or ring /polygon or ring closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::ring<Point> Ring; typedef bg::model::polygon<Point> Polygon; typedef test_geometry<Ring, Ring, Segment> tester; tester::apply("POLYGON((2 2,2 0,0 2,2 2))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); tester::apply("POLYGON((2 2,2 0,0 2,2 2))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies, true, true); // rings intersect tester::apply("POLYGON((1 1,0.1 0.1,2 1,1 1))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); // ring inside ring //TODO: disable temporarily; possible bug in intersection //tester::apply("POLYGON((0.1 0.1,0.2 0.1,0.1 0.2,0.1 0.1))", // "POLYGON((0 0,1 0,0 1,0 0))", // "SEGMENT(0.1 0.1,0.1 0.1)", // strategies); typedef test_geometry<Ring, Polygon, Segment> tester2; tester2::apply("POLYGON((2 2,2 0,0 2,2 2))", "POLYGON((0 0,1 0,0 1,0 0)(0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); // ring-polygon intersect tester2::apply("POLYGON((1 1,0.1 0.1,2 1,1 1))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); typedef test_geometry<Polygon, Ring, Segment> tester3; tester3::apply("POLYGON((2 2,2 0,0 2,2 2)(1.5 1,1 1.5,1.5 1.5,1.5 1))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); // polygon-ring intersect tester3::apply("POLYGON((1 1,0.1 0.1,2 1,1 1))", "POLYGON((0 0,1 0,0 1,0 0))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); typedef test_geometry<Polygon, Polygon, Segment> tester4; tester4::apply("POLYGON((2 2,2 0,0 2,2 2)(1.5 1,1 1.5,1.5 1.5,1.5 1))", "POLYGON((0 0,1 0,0 1,0 0)(0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); // polygons one included in the other tester4::apply("POLYGON((10 10,10 0,0 10,10 10)(8 8,4 8,8 4,8 8))", "POLYGON((9 9,9 2,2 9,9 9))", "SEGMENT(9 9,9 9)", strategies); tester4::apply("POLYGON((10 10,10 0,0 10,10 10)(8 8,4 8,8 4,8 8))", "POLYGON((9 9,9 2,2 9,9 9)(7 7,6 7,7 6,7 7))", "SEGMENT(9 9,9 9)", strategies); //touches(cartesian), intersects(spherical,geographic) tester4::apply("POLYGON((10 10,10 0,0 10,10 10)(8 8,4 8,8 4,8 8))", "POLYGON((9 9,9 2,2 9,9 9)(7 7,6 7,7 5,7 7))", "SEGMENT(7 5,7 5)", "SEGMENT(6.99222 5.01561,6.99222 5.01561)", strategies); //intersects tester4::apply("POLYGON((10 10,10 0,0 10,10 10)(8 8,4 8,8 4,8 8))", "POLYGON((9 9,9 2,2 9,9 9)(7 7,6 7,7 4.5,7 7))", "SEGMENT(6.66667 5.33333,6.66667 5.33333)", "SEGMENT(6.66211 5.34732,6.66211 5.34732)", strategies); } //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_polygon_multi_polygon(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "polygon / multi-polygon closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::ring<Point> Ring; typedef bg::model::polygon<Point> Polygon; typedef bg::model::multi_polygon<Polygon> MultiPolygon; typedef test_geometry<Ring, MultiPolygon, Segment> tester; tester::apply("POLYGON((2 2,2 0,0 2,2 2))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); tester::apply("POLYGON((2 2,2 0,0 2,2 2))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies, true, true); // multipolygon-ring intersect tester::apply("POLYGON((1 1,0.1 0.1,2 1,1 1))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0))((2 2,2 0,0 2,2 2)))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); typedef test_geometry<Polygon, MultiPolygon, Segment> tester2; tester2::apply("POLYGON((2 2,2 0,0 2,2 2))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); // multipolygon-polygon intersect tester2::apply("POLYGON((1 1,0.1 0.1,2 1,1 1)(1 0.9,1.02 0.9,1 0.8,1 0.9))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0))((2 2,2 0,0 2,2 2)))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); } //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_multi_polygon_multi_polygon(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "multi-polygon / multi-polygon closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::polygon<Point> Polygon; typedef bg::model::multi_polygon<Polygon> MultiPolygon; typedef test_geometry<MultiPolygon, MultiPolygon, Segment> tester; tester::apply("MULTIPOLYGON(((2 2,2 0,0 2,2 2)),\ ((1.5 1,1 1.5,1.5 1.5,1.5 1)))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies); tester::apply("MULTIPOLYGON(((2 2,2 0,0 2,2 2)),\ ((1.5 1,1 1.5,1.5 1.5,1.5 1)))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(1.5 0.5,1 0)", "SEGMENT(0.50019 1.50021,0 1)", "SEGMENT(1.496909 0.503379,1 0)", strategies, true, true); // multipolygon-multipolygon intersect tester::apply("MULTIPOLYGON(((1 1,0.1 0.1,2 1,1 1)),\ ((1 0.9,1.02 0.9,1 0.8,1 0.9)))", "MULTIPOLYGON(((0 0,1 0,0 1,0 0))((2 2,2 0,0 2,2 2)))", "SEGMENT(0.5 0.5,0.5 0.5)", "SEGMENT(0.500004 0.500053,0.500004 0.500053)", strategies); } //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_box_polygon_or_ring(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "box / polygon or ring closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::ring<Point> Ring; typedef bg::model::polygon<Point> Polygon; typedef bg::model::box<Point> Box; typedef test_geometry<Box, Ring, Segment> tester; tester::apply("BOX(10 10,20 20)", "POLYGON((0 0,2 0,0 2,0 0))", "SEGMENT(10 10,1 1)", "SEGMENT(10 10,0.922834 1.07763)", "SEGMENT(10 10,0.983761 1.0167)", strategies); tester::apply("BOX(10 10,20 20)", "POLYGON((0 0,2 0,0 2,0 0))", "SEGMENT(10 10,1 1)", "SEGMENT(10 10,0.922834 1.07763)", "SEGMENT(10 10,0.983761 1.0167)", strategies, true, true); //intersect tester::apply("BOX(10 10,20 20)", "POLYGON((15 15,15 25,25 30,15 15))", "SEGMENT(15 15,15 15)", strategies); tester::apply("BOX(10 10,20 20)", "POLYGON((0 0,30 0,40 15,30 30,0 30,0 0))", "SEGMENT(20 20,20 20)", strategies); typedef test_geometry<Box, Polygon, Segment> tester2; tester2::apply("BOX(10 10,20 20)", "POLYGON((0 0,2 0,0 2,0 0)(0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4))", "SEGMENT(10 10,1 1)", "SEGMENT(10 10,0.922834 1.07763)", "SEGMENT(10 10,0.983761 1.0167)", strategies); //intersect tester2::apply("BOX(10 10,20 20)", "POLYGON((15 15,15 25,25 30,15 15))", "SEGMENT(15 15,15 15)", strategies); tester2::apply("BOX(10 10,20 20)", "POLYGON((0 0,30 0,40 15,30 30,0 30,0 0))", "SEGMENT(20 20,20 20)", strategies); tester::apply("BOX(0 1,100 2)", "POLYGON((0 0,100 3,110 0,0 0))", "SEGMENT(33.3333 1,33.3333 1)", "SEGMENT(19.1476 1,19.1476 1)", "SEGMENT(19.0629 1,19.0629 1)", strategies); } //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_box_multi_polygon(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "box / multi-polygon closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::polygon<Point> Polygon; typedef bg::model::multi_polygon<Polygon> MultiPolygon; typedef bg::model::box<Point> Box; typedef test_geometry<Box, MultiPolygon, Segment> tester; tester::apply("BOX(10 10,20 20)", "MULTIPOLYGON(((0 0,2 0,0 2,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(10 10,1 1)", "SEGMENT(10 10,0.922834 1.07763)", "SEGMENT(10 10,0.983761 1.0167)", strategies); tester::apply("BOX(10 10,20 20)", "MULTIPOLYGON(((0 0,2 0,0 2,0 0)),\ ((0.4 0.4,0.4 0.1,0.1 0.4,0.4 0.4)))", "SEGMENT(10 10,1 1)", "SEGMENT(10 10,0.922834 1.07763)", "SEGMENT(10 10,0.983761 1.0167)", strategies, true, true); //intersects tester::apply("BOX(10 10,20 20)", "MULTIPOLYGON(((15 15,15 25,25 30,15 15)),\ ((0 0,0 1,1 1,1 0,0 0)))", "SEGMENT(15 15,15 15)", strategies); tester::apply("BOX(0 1,100 2)", "MULTIPOLYGON(((0 0,100 3,110 0,0 0)),\ ((0 3,3 3,3 4,0 3)))", "SEGMENT(33.3333 1,33.3333 1)", "SEGMENT(19.1476 1,19.1476 1)", "SEGMENT(19.0629 1,19.0629 1)", strategies); } //=========================================================================== template <typename Point, typename Strategies> void test_closest_points_box_box(Strategies const& strategies) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "box / box closest_points tests" << std::endl; #endif typedef bg::model::segment<Point> Segment; typedef bg::model::box<Point> Box; typedef test_geometry<Box, Box, Segment> tester; tester::apply("BOX(10 10,20 20)", "BOX(30 30,40 40)", "SEGMENT(20 20,30 30)", strategies); tester::apply("BOX(10 10,20 20)", "BOX(30 30,40 40)", "SEGMENT(20 20,30 30)", strategies, true, true); tester::apply("BOX(10 10,20 20)", "BOX(15 30,40 40)", "SEGMENT(15 20,15 30)", strategies, false); tester::apply("BOX(15 30,40 40)", "BOX(10 10,20 20)", "SEGMENT(15 30,15 20)", "SEGMENT(20 30,20 20)", strategies, false); tester::apply("BOX(10 10,20 20)", "BOX(5 30,40 40)", "SEGMENT(10 20,10 30)", strategies); tester::apply("BOX(10 10,20 20)", "BOX(5 30,15 40)", "SEGMENT(10 20,10 30)", "SEGMENT(15 20,15 30)", strategies, false); tester::apply("BOX(5 30,15 40)", "BOX(10 10,20 20)", "SEGMENT(10 30,10 20)", strategies, false); tester::apply("BOX(10 10,20 20)", "BOX(0 30,5 40)", "SEGMENT(10 20,5 30)", strategies); //intersect tester::apply("BOX(10 10,20 20)", "BOX(15 15,30 30)", "SEGMENT(15 15,15 15)", "SEGMENT(20 20,20 20)", strategies, false); tester::apply("BOX(15 15,30 30)", "BOX(10 10,20 20)", "SEGMENT(15 15,15 15)", strategies, false); tester::apply("BOX(10 10,30 30)", "BOX(15 15,20 20)", "SEGMENT(15 15,15 15)", strategies); } //=========================================================================== //=========================================================================== //=========================================================================== template < typename Point, typename Strategies > void test_all_ar_ar(Strategies strategies) { test_closest_points_polygon_or_ring_polygon_or_ring<Point>(strategies); test_closest_points_polygon_multi_polygon<Point>(strategies); test_closest_points_multi_polygon_multi_polygon<Point>(strategies); //test_closest_points_box_polygon_or_ring<Point>(strategies); //test_closest_points_box_multi_polygon<Point>(strategies); //test_closest_points_box_box<Point>(strategies); test_more_empty_input_areal_areal<Point>(strategies); } BOOST_AUTO_TEST_CASE( test_all_areal_areal ) { test_all_ar_ar<car_point>(cartesian()); test_all_ar_ar<sph_point>(spherical()); test_all_ar_ar<sph_point>(spherical( bg::formula::mean_radius<double>(bg::srs::spheroid<double>()))); test_all_ar_ar<geo_point>(andoyer()); test_all_ar_ar<geo_point>(thomas()); test_all_ar_ar<geo_point>(vincenty()); }
[ "fisikop@gmail.com" ]
fisikop@gmail.com
c2bc08e2e9d86a5a877285e26826576a9c7c19c2
75cde75df244b8ae8e424c2a7f517873c42c0214
/DGG/src/YXMetric/YXPathTracer.h
0d509e50f9024900330e8171694609745fe11a72
[]
no_license
wxnfifth/DGG_project
6f5b12ca6f56504fbffc3f949eae4e0acdf2097c
b355111bf13f4054c0b906e183999cc3bd47d44d
refs/heads/master
2016-09-06T07:16:08.041878
2016-01-31T20:27:02
2016-01-31T20:27:02
40,108,437
2
0
null
null
null
null
UTF-8
C++
false
false
1,354
h
#ifndef _YXPATHTRACER_H_ #define _YXPATHTRACER_H_ #include "YXMetric.h" using std::vector; struct YXPathPoint{ //edge: v1-->v2, on triangle v1v2v3, then the point is : v1*a+v2*b+v3*(1-a-b) int edgeId; double a, b; YXPathPoint() : edgeId(0), a(0.0), b(0.0) {} YXPathPoint(int e, double a, double b) : edgeId(e), a(a), b(b) {} }; typedef vector<YXPathPoint> YXPath; class YXPathTracer{ public: YXMesh3D mesh; YXMetric metric; void init(const char * filename) { int rt_value = mesh.load(filename); assert( rt_value == 0); metric.buildFromMesh(mesh); metric.assignNormalsForMesh(mesh); } void unfoldStraightLine(int base_edge, double position, double dis1, double dis2, double remain_length, YXPath & path) const; void computeSinglePath(int start_edge, double angle, double length, YXPath & path) const; void computeSinglePathArbitraryStart(int start_edge, double angle, double length, YXPath & path , int source_index = -1) const; void computePatch(int start_vertex, int numOfPaths, double length, vector<YXPath> &paths) const; YXPoint3D convertToYXPoint3D(const YXPathPoint & p) const; int getFaceIndex(const YXPathPoint& p) const; void generateObj(const vector<YXPath> &paths, const char * filename) const; double approxCurvature(int v, const YXPoint3D & B, const YXPoint3D & C); }; #endif
[ "wxnfifth@gmail.com" ]
wxnfifth@gmail.com
bc2b658f0072be9901187fffba9d82b189c90b9a
1834c0796ee324243f550357c67d8bcd7c94de17
/SDK/TCF_MeshDescription_classes.hpp
b109be651581b20201cb58b27329b860668c2f75
[]
no_license
DarkCodez/TCF-SDK
ce41cc7dab47c98b382ad0f87696780fab9898d2
134a694d3f0a42ea149a811750fcc945437a70cc
refs/heads/master
2023-08-25T20:54:04.496383
2021-10-25T11:26:18
2021-10-25T11:26:18
423,337,506
1
0
null
2021-11-01T04:31:21
2021-11-01T04:31:20
null
UTF-8
C++
false
false
9,070
hpp
#pragma once // The Cycle Frontier (1.X) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "TCF_MeshDescription_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class MeshDescription.MeshDescription // 0x0000 (0x0028 - 0x0028) class UMeshDescription : public UObject { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class MeshDescription.MeshDescription"); return ptr; } }; // Class MeshDescription.MeshDescriptionBase // 0x0368 (0x0390 - 0x0028) class UMeshDescriptionBase : public UObject { public: unsigned char UnknownData00[0x368]; // 0x0028(0x0368) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class MeshDescription.MeshDescriptionBase"); return ptr; } void SetVertexPosition(const struct FVertexID& VertexID, const struct FVector& Position); void SetPolygonVertexInstance(const struct FPolygonID& PolygonID, int PerimeterIndex, const struct FVertexInstanceID& VertexInstanceID); void SetPolygonPolygonGroup(const struct FPolygonID& PolygonID, const struct FPolygonGroupID& PolygonGroupID); void ReversePolygonFacing(const struct FPolygonID& PolygonID); void ReserveNewVertices(int NumberOfNewVertices); void ReserveNewVertexInstances(int NumberOfNewVertexInstances); void ReserveNewTriangles(int NumberOfNewTriangles); void ReserveNewPolygons(int NumberOfNewPolygons); void ReserveNewPolygonGroups(int NumberOfNewPolygonGroups); void ReserveNewEdges(int NumberOfNewEdges); bool IsVertexValid(const struct FVertexID& VertexID); bool IsVertexOrphaned(const struct FVertexID& VertexID); bool IsVertexInstanceValid(const struct FVertexInstanceID& VertexInstanceID); bool IsTriangleValid(const struct FTriangleID& TriangleID); bool IsTrianglePartOfNgon(const struct FTriangleID& TriangleID); bool IsPolygonValid(const struct FPolygonID& PolygonID); bool IsPolygonGroupValid(const struct FPolygonGroupID& PolygonGroupID); bool IsEmpty(); bool IsEdgeValid(const struct FEdgeID& EdgeID); bool IsEdgeInternalToPolygon(const struct FEdgeID& EdgeID, const struct FPolygonID& PolygonID); bool IsEdgeInternal(const struct FEdgeID& EdgeID); void GetVertexVertexInstances(const struct FVertexID& VertexID, TArray<struct FVertexInstanceID>* OutVertexInstanceIDs); struct FVector GetVertexPosition(const struct FVertexID& VertexID); struct FEdgeID GetVertexPairEdge(const struct FVertexID& VertexID0, const struct FVertexID& VertexID1); struct FVertexID GetVertexInstanceVertex(const struct FVertexInstanceID& VertexInstanceID); struct FEdgeID GetVertexInstancePairEdge(const struct FVertexInstanceID& VertexInstanceID0, const struct FVertexInstanceID& VertexInstanceID1); struct FVertexInstanceID GetVertexInstanceForTriangleVertex(const struct FTriangleID& TriangleID, const struct FVertexID& VertexID); struct FVertexInstanceID GetVertexInstanceForPolygonVertex(const struct FPolygonID& PolygonID, const struct FVertexID& VertexID); void GetVertexInstanceConnectedTriangles(const struct FVertexInstanceID& VertexInstanceID, TArray<struct FTriangleID>* OutConnectedTriangleIDs); void GetVertexInstanceConnectedPolygons(const struct FVertexInstanceID& VertexInstanceID, TArray<struct FPolygonID>* OutConnectedPolygonIDs); void GetVertexConnectedTriangles(const struct FVertexID& VertexID, TArray<struct FTriangleID>* OutConnectedTriangleIDs); void GetVertexConnectedPolygons(const struct FVertexID& VertexID, TArray<struct FPolygonID>* OutConnectedPolygonIDs); void GetVertexConnectedEdges(const struct FVertexID& VertexID, TArray<struct FEdgeID>* OutEdgeIDs); void GetVertexAdjacentVertices(const struct FVertexID& VertexID, TArray<struct FVertexID>* OutAdjacentVertexIDs); void GetTriangleVertices(const struct FTriangleID& TriangleID, TArray<struct FVertexID>* OutVertexIDs); void GetTriangleVertexInstances(const struct FTriangleID& TriangleID, TArray<struct FVertexInstanceID>* OutVertexInstanceIDs); struct FVertexInstanceID GetTriangleVertexInstance(const struct FTriangleID& TriangleID, int Index); struct FPolygonGroupID GetTrianglePolygonGroup(const struct FTriangleID& TriangleID); struct FPolygonID GetTrianglePolygon(const struct FTriangleID& TriangleID); void GetTriangleEdges(const struct FTriangleID& TriangleID, TArray<struct FEdgeID>* OutEdgeIDs); void GetTriangleAdjacentTriangles(const struct FTriangleID& TriangleID, TArray<struct FTriangleID>* OutTriangleIDs); void GetPolygonVertices(const struct FPolygonID& PolygonID, TArray<struct FVertexID>* OutVertexIDs); void GetPolygonVertexInstances(const struct FPolygonID& PolygonID, TArray<struct FVertexInstanceID>* OutVertexInstanceIDs); void GetPolygonTriangles(const struct FPolygonID& PolygonID, TArray<struct FTriangleID>* OutTriangleIDs); struct FPolygonGroupID GetPolygonPolygonGroup(const struct FPolygonID& PolygonID); void GetPolygonPerimeterEdges(const struct FPolygonID& PolygonID, TArray<struct FEdgeID>* OutEdgeIDs); void GetPolygonInternalEdges(const struct FPolygonID& PolygonID, TArray<struct FEdgeID>* OutEdgeIDs); void GetPolygonGroupPolygons(const struct FPolygonGroupID& PolygonGroupID, TArray<struct FPolygonID>* OutPolygonIDs); void GetPolygonAdjacentPolygons(const struct FPolygonID& PolygonID, TArray<struct FPolygonID>* OutPolygonIDs); int GetNumVertexVertexInstances(const struct FVertexID& VertexID); int GetNumVertexInstanceConnectedTriangles(const struct FVertexInstanceID& VertexInstanceID); int GetNumVertexInstanceConnectedPolygons(const struct FVertexInstanceID& VertexInstanceID); int GetNumVertexConnectedTriangles(const struct FVertexID& VertexID); int GetNumVertexConnectedPolygons(const struct FVertexID& VertexID); int GetNumVertexConnectedEdges(const struct FVertexID& VertexID); int GetNumPolygonVertices(const struct FPolygonID& PolygonID); int GetNumPolygonTriangles(const struct FPolygonID& PolygonID); int GetNumPolygonInternalEdges(const struct FPolygonID& PolygonID); int GetNumPolygonGroupPolygons(const struct FPolygonGroupID& PolygonGroupID); int GetNumEdgeConnectedTriangles(const struct FEdgeID& EdgeID); int GetNumEdgeConnectedPolygons(const struct FEdgeID& EdgeID); void GetEdgeVertices(const struct FEdgeID& EdgeID, TArray<struct FVertexID>* OutVertexIDs); struct FVertexID GetEdgeVertex(const struct FEdgeID& EdgeID, int VertexNumber); void GetEdgeConnectedTriangles(const struct FEdgeID& EdgeID, TArray<struct FTriangleID>* OutConnectedTriangleIDs); void GetEdgeConnectedPolygons(const struct FEdgeID& EdgeID, TArray<struct FPolygonID>* OutConnectedPolygonIDs); void Empty(); void DeleteVertexInstance(const struct FVertexInstanceID& VertexInstanceID, TArray<struct FVertexID>* OrphanedVertices); void DeleteVertex(const struct FVertexID& VertexID); void DeleteTriangle(const struct FTriangleID& TriangleID, TArray<struct FEdgeID>* OrphanedEdges, TArray<struct FVertexInstanceID>* OrphanedVertexInstances, TArray<struct FPolygonGroupID>* OrphanedPolygonGroupsPtr); void DeletePolygonGroup(const struct FPolygonGroupID& PolygonGroupID); void DeletePolygon(const struct FPolygonID& PolygonID, TArray<struct FEdgeID>* OrphanedEdges, TArray<struct FVertexInstanceID>* OrphanedVertexInstances, TArray<struct FPolygonGroupID>* OrphanedPolygonGroups); void DeleteEdge(const struct FEdgeID& EdgeID, TArray<struct FVertexID>* OrphanedVertices); void CreateVertexWithID(const struct FVertexID& VertexID); void CreateVertexInstanceWithID(const struct FVertexInstanceID& VertexInstanceID, const struct FVertexID& VertexID); struct FVertexInstanceID CreateVertexInstance(const struct FVertexID& VertexID); struct FVertexID CreateVertex(); void CreateTriangleWithID(const struct FTriangleID& TriangleID, const struct FPolygonGroupID& PolygonGroupID, TArray<struct FVertexInstanceID> VertexInstanceIDs, TArray<struct FEdgeID>* NewEdgeIDs); struct FTriangleID CreateTriangle(const struct FPolygonGroupID& PolygonGroupID, TArray<struct FVertexInstanceID> VertexInstanceIDs, TArray<struct FEdgeID>* NewEdgeIDs); void CreatePolygonWithID(const struct FPolygonID& PolygonID, const struct FPolygonGroupID& PolygonGroupID, TArray<struct FVertexInstanceID>* VertexInstanceIDs, TArray<struct FEdgeID>* NewEdgeIDs); void CreatePolygonGroupWithID(const struct FPolygonGroupID& PolygonGroupID); struct FPolygonGroupID CreatePolygonGroup(); struct FPolygonID CreatePolygon(const struct FPolygonGroupID& PolygonGroupID, TArray<struct FVertexInstanceID>* VertexInstanceIDs, TArray<struct FEdgeID>* NewEdgeIDs); void CreateEdgeWithID(const struct FEdgeID& EdgeID, const struct FVertexID& VertexID0, const struct FVertexID& VertexID1); struct FEdgeID CreateEdge(const struct FVertexID& VertexID0, const struct FVertexID& VertexID1); void ComputePolygonTriangulation(const struct FPolygonID& PolygonID); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "30532128+pubgsdk@users.noreply.github.com" ]
30532128+pubgsdk@users.noreply.github.com
0dcde98c47952e68d69ddcac8444bbc3612cb13c
ef80cdd8a5593a0ab659d7ccc8dde11f2bf6e679
/updateit.cpp
255db355648d154d39195814f6aebf4cdd839e82
[]
no_license
atyamsriharsha/My-Spoj-Solutions
26ac4830b4eb3c4ba95a7d731ebb595ef4b93093
7d8aabc41bd0ce41a80cd6342b7ea182d0d83a7a
refs/heads/master
2020-06-07T12:59:39.250327
2015-07-07T14:23:29
2015-07-07T14:23:29
38,692,463
1
3
null
null
null
null
UTF-8
C++
false
false
643
cpp
#include <iostream> #include <cmath> #include <string.h> #include <stdio.h> #include <stdlib.h> using namespace std ; int main(int argc, char const *argv[]) { int test,i ; scanf("%d",&test) ; while(test) { int n,u ; scanf("%d %d",&n,&u) ; int a[n] ; for(i=0;i<n;i++) a[i]=0 ; while(u) { int l,r,val ; scanf("%d %d %d",&l,&r,&val) ; for(i=l;i<=r;i++) a[i]=a[i]+val ; u -- ; } int q ; scanf("%d",&q) ; while(q) { int q1 ; cin >> q1 ; printf("%d\n",a[q1]) ; q-- ; } test-- ; } return 0; }
[ "atyamsriharsha@gmail.com" ]
atyamsriharsha@gmail.com