blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
885908f1ea7433ca70468cbc61173724bd33b85b
9721541f4671d4216edfaa11279eebfd5f0a251f
/modules/json/include/modules/json/io/json/ordinalrefpropertyjsonconverter.h
f0684ddcf3526bcdbbf5375a29a258e8c2cc4ca8
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
petersteneteg/inviwo
dfeb5dcdd80a5b842ae8eee804a9b114ef124eb4
ea0e5139a6b0a5ba0bc46c8e883a35308d7ed7d6
refs/heads/master
2023-06-07T00:25:40.731166
2022-09-12T07:22:06
2022-09-12T07:22:06
206,647,917
0
0
BSD-2-Clause
2019-09-05T20:10:22
2019-09-05T20:04:09
null
UTF-8
C++
false
false
3,140
h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020-2022 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #pragma once #include <modules/json/io/json/glmjsonconverter.h> #include <inviwo/core/properties/ordinalrefproperty.h> #include <nlohmann/json.hpp> namespace inviwo { using json = ::nlohmann::json; /** * Converts an OrdinalRefProperty to a JSON object. * Produces layout according to the members of OrdinalRefProperty: * { {"value": val}, {"increment": increment}, * {"minValue": minVal}, {"maxValue": maxVal} * } * @see OrdinalRefProperty * * Usage example: * \code{.cpp} * OrdinalRefProperty<double> p; * json j = p; * \endcode */ template <typename T> void to_json(json& j, const OrdinalRefProperty<T>& p) { j = json{{"value", p.get()}, {"minValue", p.getMinValue()}, {"maxValue", p.getMaxValue()}, {"increment", p.getIncrement()}}; } /** * Converts a JSON object to an OrdinalRefProperty. * Expects object layout according to the members of OrdinalRefProperty: * { {"value": val}, {"increment": increment}, * {"minValue": minVal}, {"maxValue": maxVal} * } * @see OrdinalRefProperty * * Usage example: * \code{.cpp} * auto p = j.get<OrdinalRefProperty<double>>(); * \endcode */ template <typename T> void from_json(const json& j, OrdinalRefProperty<T>& p) { auto value = j.value("value", p.get()); // Optional parameters auto minVal = j.value("minValue", p.getMinValue()); auto maxVal = j.value("maxValue", p.getMaxValue()); auto increment = j.value("increment", p.getIncrement()); p.set(value, minVal, maxVal, increment); } } // namespace inviwo
[ "peter@steneteg.se" ]
peter@steneteg.se
438bfdb829988f5dd2b1fac3dd73bc85ed33b35e
5cce90d8a8c739da50997ae31980407f3b79c60c
/code/threads/scheduler.h
850bf3bd90aa7572274574b79a5d14b4569d4350
[ "MIT-Modern-Variant" ]
permissive
ronel129/code
da44af8cc35317cf5bedcf99dfc90b348ed73b43
f62c37d795aed720dfbb743ff4c9f89abc3cff46
refs/heads/master
2016-08-04T21:49:43.980362
2013-04-09T01:46:59
2013-04-09T01:46:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
h
// scheduler.h // Data structures for the thread dispatcher and scheduler. // Primarily, the list of threads that are ready to run. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef SCHEDULER_H #define SCHEDULER_H #include "copyright.h" #include "list.h" #include "thread.h" // The following class defines the scheduler/dispatcher abstraction -- // the data structures and operations needed to keep track of which // thread is running, and which threads are ready but not running. class Scheduler { public: Scheduler(); // Initialize list of ready threads ~Scheduler(); // De-allocate ready list void ReadyToRun(Thread* thread); // Thread can be dispatched. Thread* FindNextToRun(); // Dequeue first thread on the ready // list, if any, and return thread. void Run(Thread* nextThread); // Cause nextThread to start running void Print(); // Print contents of ready list Thread* RemoveThreadByPid(int pid); // Remove Thread by pid private: List *readyList; // queue of threads that are ready to run, // but not running }; #endif // SCHEDULER_H
[ "ronel129@gmail.com" ]
ronel129@gmail.com
fa46a300c3dcd2373c2e3598be03c7aeee50d6a5
1b3b13ff4015ccd29150cf0462dac96993ea3d32
/serv/serv.si4project/Backup/common(5014).h
a3f684c6d91dc4ce48966f93e8ff142e0776fc07
[]
no_license
CharlesPu/intern
88fbbf3633e9103d7401ddee79c5766896179177
347287c50167a6caf793f47d9acc0cd3c8e3bf62
refs/heads/master
2021-09-14T02:06:12.439330
2018-05-07T13:30:37
2018-05-07T13:30:37
117,245,011
0
0
null
null
null
null
UTF-8
C++
false
false
1,989
h
#ifndef COMMON_H #define COMMON_H #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <fcntl.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <net/if.h> #include <linux/socket.h> #include <linux/can.h> #include <linux/can/error.h> #include <linux/can/raw.h> #include <time.h> #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; /******************** 配置项 ********************/ //#define DES //#define PRINT_ULTI_SND_REC //#define PRINT_CAN //#define PRINT_BUFFER #define TASK_NUM 4 #define filter_num 5 unsigned short filter_id[filter_num]={ // /*per 10ms*/ 0x00F9, // /*per 25ms*/ 0x0175,0x0189,0x0197, 0x019D,0x01A6,0x01AF,0x01F5, // /*per 50ms*/ 0x02A5, /*per 250ms*/ 0x03F5, // /*per 500ms*/ 0x04A5,0x04C9 }; /****************************************************/ #define PORT 4000 // The port which is communicate with server #define BACKLOG 10// tongshi lianjie de kehuduan shuliang #define BUF_LENGTH 4000 // Buffer length #define ttyO0 0 #define ttyO1 1 #define ttyO2 2 #define ttyO3 3 #define ttyO4 4 #define ttyO5 5 #ifndef AF_CAN #define AF_CAN 29 #endif #ifndef PF_CAN #define PF_CAN AF_CAN #endif #define errout(_s) fprintf(stderr, "error class: %s\n", (_s)) #define errcode(_d) fprintf(stderr, "error code: %02x\n", (_d)) #define myerr(str) fprintf(stderr, "%s, %s, %d: %s\n", __FILE__, __func__, __LINE__, str) class Server; class Buffer; typedef struct _CANthreadPara { int fd1; int master; int frameId; int fd2; Server* _server; Buffer* _sbuffer; }CTP; typedef struct _ServerThreadPara { Server* _pServer; CTP* _pCtp; }STP; typedef struct _TimerPara { int seconds; int mseconds; }TTP; #endif // COMMON_H
[ "pu17rui@sina.com" ]
pu17rui@sina.com
3f3fef45cbf8bfead5ddebf7dff40fbd5cdb2118
df7370513086efd70984564b6fb34beed08c6670
/src/test/test-problem.cpp
e2fd13f97e64666ae595a83a9a967c6f80650dc2
[ "MIT" ]
permissive
drb27/stock
4472231f407161fccde4643f2bfe2718ab1da9f1
4b531236b215090b9aad90a93bfdd841d8413713
refs/heads/master
2021-01-23T09:33:52.293257
2015-03-12T11:50:00
2015-03-12T11:52:00
30,944,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
#include "test-problem.h" #include <stocklib/problem.h> #include <stocklib/urltask.h> class fact : public contained_problem<int,int> { public: fact(int x) : contained_problem<int,int>(x) {} protected: virtual int do_work(int x); }; int fact::do_work(int x) { if (x==1) return 1; else return x * do_work(x-1); } ProblemTestFixture::ProblemTestFixture() { } ProblemTestFixture::~ProblemTestFixture() { } void ProblemTestFixture::setUp() { } void ProblemTestFixture::tearDown() { } /** * Tests a basic problem solve. */ void ProblemTestFixture::testSimpleProblem() { problem<int,int> p( [](int x){ return x+x; }, 8 ); CPPUNIT_ASSERT(16==p.solve()); } /** * Tests a basic problem solve. */ void ProblemTestFixture::testFunctor() { /* Basic functionality */ problem<int,int> p( [](int x){ return x+x; }, 8 ); CPPUNIT_ASSERT(16==p()); } void ProblemTestFixture::testContainedProblem() { { fact f(4); CPPUNIT_ASSERT(24==f.solve()); } urltask t("http://www.scatterpic.com/api/motd.php"); WorkResult r = t.perform_sync(); CPPUNIT_ASSERT( t.ready() ); CPPUNIT_ASSERT( r == WorkResult::Success ); }
[ "david.bradshaw.usa@gmail.com" ]
david.bradshaw.usa@gmail.com
eafc97a0649e48d890a006522158a66ecf791270
4572bb6f477c456042daca809c76b57fc6390ac8
/OOP and files 2.cpp
b584ed3b1ad2a0e383100cb07b87fba93556446e
[]
no_license
smakesoska1/Programming-Techniques
8ed1c448c613f21bd150f142c4ec1a62753f6a98
1fd72471b81ac76e80809c91406ff2ecfdbf0f5f
refs/heads/main
2023-07-17T08:14:39.623677
2021-08-29T18:20:03
2021-08-29T18:20:03
401,108,767
0
0
null
null
null
null
UTF-8
C++
false
false
4,308
cpp
#include <iostream> #include<fstream> #include<string> #include<vector> #include<stdexcept> #include<cmath> #include<algorithm> class Spremnik { protected: double tezina; std::string naziv; public: Spremnik(double tezina,std::string naziv): tezina(tezina),naziv(naziv){} virtual~Spremnik(){} double DajTezinu() const{return tezina;} virtual double DajUkupnuTezinu() const=0; virtual Spremnik *DajKopiju() const=0; virtual void Ispisi() const=0; }; /*class Skladiste{ }*/ class Sanduk:public Spremnik { std::vector<double>tezine; public: Sanduk(double tezina,std::string naziv,std::vector<double>tezine):Spremnik(tezina,naziv),tezine(tezine){} double DajUkupnuTezinu() const override{ double tezinasanduk=DajTezinu(); //ukupna for(int i=0;i<tezine.size();i++) tezinasanduk=tezinasanduk+tezine[i]; return tezinasanduk;} Sanduk* DajKopiju() const override{return new Sanduk(*this);} void Ispisi() const override { std::cout<<"Vrsta spremnika: Sanduk"<<std::endl<<"Sadrzaj: "<<naziv<<std::endl<<"Tezine predmeta: "; for(int i=0;i<tezine.size();i++) std::cout<<tezine[i]<<" "; std::cout<<"(kg)"<<std::endl<<"Vlastita tezina: "<<DajTezinu()<<" (kg)"<<std::endl<<"Ukupna tezina: "<<DajUkupnuTezinu()<<" (kg)"<<std::endl; } }; class Bure:public Spremnik { double spectezina; double zapremina; public: Bure(double tezina,std::string naziv,double spectezina,double zapremina): Spremnik(tezina,naziv),spectezina(spectezina),zapremina(zapremina){} Bure* DajKopiju() const override{return new Bure(*this);} double DajUkupnuTezinu() const override { double ukupnatezina; ukupnatezina=spectezina*zapremina/1000+DajTezinu(); return ukupnatezina; } void Ispisi() const override { std::cout<<"Vrsta spremnika: Bure"<<std::endl<<"Sadrzaj: "<<naziv<<std::endl<<"Vlastita tezina: "<<DajTezinu()<<" (kg)"<<std::endl<<"Specificna tezina tecnosti: "<<spectezina<<" (kg/m^3)"<<std::endl<<"Zapremina tecnosti: "<<zapremina<<" (l)"<<std::endl<<"Ukupna tezina: "<<DajUkupnuTezinu()<<" (kg)"<<std::endl; } }; class Vreca:public Spremnik{ double tezinamaterije; public: Vreca(double tezina,std::string naziv,double tezinamaterije):Spremnik(tezina,naziv),tezinamaterije(tezinamaterije){} Vreca* DajKopiju() const override{return new Vreca(*this);} double DajUkupnuTezinu() const override {double materija=DajTezinu(); return materija+tezinamaterije; } void Ispisi() const override { std::cout<<"Vrsta spremnika: Vreca"<<std::endl<<"Sadrzaj: "<<naziv<<std::endl<<"Vlastita tezina: "<<DajTezinu()<<" (kg)"<<std::endl<<"Tezina pohranjene materije: "<<tezinamaterije<<" (kg)"<<std::endl<<"Ukupna tezina: "<<DajUkupnuTezinu()<<" (kg)"<<std::endl; } }; class PolimorfniSpremnik { Spremnik *spremnik; void Test() const { if(!spremnik) throw std::logic_error("Nespecificiran spremnik"); } public: PolimorfniSpremnik():spremnik(nullptr){}; ~PolimorfniSpremnik(){delete spremnik;} PolimorfniSpremnik(const Spremnik &spremnik11){spremnik=spremnik11.DajKopiju();} PolimorfniSpremnik(const PolimorfniSpremnik &spremnik11) { if(!spremnik11.spremnik) spremnik=nullptr; else spremnik=spremnik11.spremnik->DajKopiju(); } PolimorfniSpremnik(PolimorfniSpremnik &&spremnik11) { spremnik=spremnik11.spremnik; spremnik11.spremnik=nullptr; } PolimorfniSpremnik &operator=(const PolimorfniSpremnik &spremnik11) { if(&spremnik11!=this){ delete spremnik; if(!spremnik11.spremnik) spremnik=nullptr; else spremnik=spremnik11.spremnik->DajKopiju(); } return *this;} PolimorfniSpremnik &operator=(PolimorfniSpremnik &&spremnik11) { if(&spremnik11!=this){ delete spremnik; spremnik=spremnik11.spremnik; spremnik11.spremnik=nullptr;} return *this; } double DajTezinu() const{Test();return spremnik->DajTezinu();} double DajUkupnuTezinu() const{Test();return spremnik->DajUkupnuTezinu();} void Ispisi() const{Test();return spremnik->Ispisi();} }; int main() { return 0; }
[ "smakesoska1@etf.unsa.ba" ]
smakesoska1@etf.unsa.ba
f57d512472101f98513bb00610e3ef8efb41ef16
08c58057c112ef6ef5ceb0e125815d2a80c1f1f0
/cfg/factions.hpp
51e52caea9f678e2c6e77b729569a613359890c5
[]
no_license
uniflare/FF7_InA
62d11504110376a668c4105daaaaefd99c7949cb
08b955dc5b8c6932985d093d6c761cb356f0a292
refs/heads/master
2021-01-01T06:23:45.236535
2017-11-10T03:30:07
2017-11-10T03:30:07
97,420,082
0
0
null
2017-07-17T00:35:20
2017-07-17T00:35:20
null
UTF-8
C++
false
false
281
hpp
#include "factions\global.hpp" #include "factions\sides\blufor.hpp" #include "factions\sides\opfor.hpp" class InA_Factions { #include "factions\aaf.hpp" #include "factions\army.hpp" #include "factions\marines.hpp" #include "factions\nato.hpp" #include "factions\russia.hpp" };
[ "uniflare@gmail.com" ]
uniflare@gmail.com
8ae3906afd3d82c80f928c919d3975c87668a8a9
6ed56d2539b65f651932c0eaa5aa7438c148eb39
/태욱/11654.cpp
9e2ffc191b9f50e7509eda70552f135e8c9a5a2d
[]
no_license
SSU-SSORA/AlgorithmStudy
d7b560c00545390395419261c86a89762d72189b
6c62b01eadfb5f8ca70135192ee645d527e822ad
refs/heads/master
2021-01-15T21:33:59.769235
2017-08-10T03:27:05
2017-08-10T03:27:05
99,875,641
0
2
null
2017-08-10T03:27:06
2017-08-10T03:10:42
C++
UTF-8
C++
false
false
99
cpp
#include <iostream> int main(void) { char a; std::cin >> a; std::cout << static_cast<int>(a); }
[ "sjrnfu12@naver.com" ]
sjrnfu12@naver.com
6d661ef6b86ee476d1198b4641ce3921d7932762
42b95f5a14ba4c505f6973b2138909f5a4e07d6e
/Arduino/mpu/mpu9250_OpenGL/src/rOc_timer.cpp
46e67e4577725bbb8938ff47a75c4e9995c142a4
[]
no_license
titoluyo/makerzone
8f9785b9c46b4108bda7127c8c57ce1f6dd41863
3fe2d7b3b831f8be156533e548e8e4ffd5636fa2
refs/heads/master
2021-01-22T21:28:37.098251
2020-06-24T05:12:13
2020-06-24T05:12:13
39,574,906
1
1
null
2020-06-24T00:31:31
2015-07-23T15:20:11
C++
UTF-8
C++
false
false
1,469
cpp
#include <rOc_timer.h> // Constructor of the class, initialize timer at zero rOc_timer::rOc_timer() { restart(); } // Restart the timer (at zero) void rOc_timer::restart() { // Store current initial time gettimeofday(&initialTime, NULL); } // Return the ellapsed time in microseconds uint64_t rOc_timer::ellapsedMicroseconds() { // Get current time struct timeval currentTime; gettimeofday(&currentTime, NULL); // Compute ellapsed seconds and microseconds int64_t useconds =currentTime.tv_usec-initialTime.tv_usec; uint64_t seconds =currentTime.tv_sec-initialTime.tv_sec; // Check for particular case if (useconds<0) return 1000000+useconds+(seconds-1)*1000000; // Return ellapsed miscroseconds return seconds*1000000+useconds; } // Return the ellapsed time in milliseconds uint64_t rOc_timer::ellapsedMilliseconds() { // Milliseconds = microseconds/1000 return ellapsedMicroseconds()/1000; } // Return the ellapsed time in seconds uint64_t rOc_timer::ellapsedSeconds() { // Get current time struct timeval currentTime; gettimeofday(&currentTime, NULL); // Compute ellapsed seconds and microseconds int64_t useconds =currentTime.tv_usec-initialTime.tv_usec; uint64_t seconds =currentTime.tv_sec-initialTime.tv_sec; // Check for particular case if (useconds<0) return seconds-1; // Return ellapsed seconds return seconds; }
[ "tluyo@hotmail.com" ]
tluyo@hotmail.com
4c734563e007ba7cdd4596329140ae3bcde2a7dc
e2d411eac3ed5b5297258cbfb820ea9904fafc0a
/examples/SGTL5000_Specific/dap_bass_enhance/dap_bass_enhance.ino
b550c1a7898097628bf183497061f50658eb0396
[]
no_license
natcl/Audio
ec820c109f2cecf9315c08047bfa74538b42cb31
8798978f2a8ae1ae657d5509dd38a1446e56e37a
refs/heads/master
2020-12-29T00:12:57.079155
2014-08-27T21:42:05
2014-08-27T21:42:05
23,406,810
1
0
null
null
null
null
UTF-8
C++
false
false
1,887
ino
/* DAP Bass enhance example SGTL5000 only This example code is in the public domain */ #include <Audio.h> #include <Wire.h> #include <SD.h> const int myInput = AUDIO_INPUT_LINEIN; // const int myInput = AUDIO_INPUT_MIC; // Create the Audio components. These should be created in the // order data flows, inputs/sources -> processing -> outputs // AudioInputI2S audioInput; // audio shield: mic or line-in AudioOutputI2S audioOutput; // audio shield: headphones & line-out // Create Audio connections between the components // AudioConnection c1(audioInput, 0, audioOutput, 0); // left passing through AudioConnection c2(audioInput, 1, audioOutput, 1); // right passing through // Create an object to control the audio shield. // AudioControlSGTL5000 audioShield; void setup() { // Audio connections require memory to work. For more // detailed information, see the MemoryAndCpuUsage example AudioMemory(4); // Enable the audio shield and set the output volume. audioShield.enable(); audioShield.inputSelect(myInput); audioShield.volume(0.75); audioShield.unmuteLineout(); // just enable it to use default settings. audioShield.enhanceBassEnable(); // all we need to do for default bass enhancement settings. // audioShield.enhanceBass((float)lr_level,(float)bass_level); // audioShield.enhanceBass((float)lr_level,(float)bass_level,(uint8_t)hpf_bypass,(uint8_t)cutoff); // please see http://www.pjrc.com/teensy/SGTL5000.pdf page 50 for valid values for BYPASS_HPF and CUTOFF } elapsedMillis chgMsec=0; float lastVol=1024; void loop() { // every 10 ms, check for adjustment if (chgMsec > 10) { // more regular updates for actual changes seems better. float vol1=analogRead(15)/10.23; vol1=(int)vol1; if(lastVol!=vol1) { audioShield.volume(vol1); lastVol=vol1; } chgMsec = 0; } }
[ "github@robsfreespace.com" ]
github@robsfreespace.com
c0e5cf02704238b7dea268b3c13f87b9c55319dc
545ba4058210418e3d5d1b9222aca61d1b87540e
/Compressonator/Applications/CompressonatorGUI/Common/objectcontroller.cpp
dbd70b583837a9d13c5fdaf1e695c6ba8d72320c
[ "MIT" ]
permissive
danchanakya/Compressonator
715441e935d553a4ae124867b92abc4859317be4
202972022b2085487351918fc43bf5bdc2653e42
refs/heads/master
2021-01-18T03:35:24.659808
2016-06-10T17:58:39
2016-06-10T17:58:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,789
cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // updated object create and views #include "objectcontroller.h" #include "qdebug.h" class ObjectControllerPrivate { ObjectController *q_ptr; Q_DECLARE_PUBLIC(ObjectController) public: void addClassProperties(const QMetaObject *metaObject, bool subGroup); void updateClassProperties(const QMetaObject *metaObject, bool recursive); void saveExpandedState(); void restoreExpandedState(); void slotValueChanged(QtProperty *property, const QVariant &value); int enumToInt(const QMetaEnum &metaEnum, int enumValue) const; int intToEnum(const QMetaEnum &metaEnum, int intValue) const; int flagToInt(const QMetaEnum &metaEnum, int flagValue) const; int intToFlag(const QMetaEnum &metaEnum, int intValue) const; bool isSubValue(int value, int subValue) const; bool isPowerOf2(int value) const; QObject *m_object; QMap<const QMetaObject *, QtProperty *> m_classToProperty; QMap<QtProperty *, const QMetaObject *> m_propertyToClass; QMap<QtProperty *, int> m_propertyToIndex; QMap<const QMetaObject *, QMap<int, QtVariantProperty *> > m_classToIndexToProperty; QMap<QtProperty *, bool> m_propertyToExpanded; QList<QtProperty *> m_topLevelProperties; QtAbstractPropertyBrowser *m_browser; QtVariantPropertyManager *m_manager; QtVariantPropertyManager *m_readOnlyManager; bool m_subGroup; }; int ObjectControllerPrivate::enumToInt(const QMetaEnum &metaEnum, int enumValue) const { QMap<int, int> valueMap; // dont show multiple enum values which have the same values int pos = 0; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value)) { if (value == enumValue) return pos; valueMap[value] = pos++; } } return -1; } int ObjectControllerPrivate::intToEnum(const QMetaEnum &metaEnum, int intValue) const { QMap<int, bool> valueMap; // dont show multiple enum values which have the same values QList<int> values; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value)) { valueMap[value] = true; values.append(value); } } if (intValue >= values.count()) return -1; return values.at(intValue); } bool ObjectControllerPrivate::isSubValue(int value, int subValue) const { if (value == subValue) return true; int i = 0; while (subValue) { if (!(value & (1 << i))) { if (subValue & 1) return false; } i++; subValue = subValue >> 1; } return true; } bool ObjectControllerPrivate::isPowerOf2(int value) const { while (value) { if (value & 1) { return value == 1; } value = value >> 1; } return false; } int ObjectControllerPrivate::flagToInt(const QMetaEnum &metaEnum, int flagValue) const { if (!flagValue) return 0; int intValue = 0; QMap<int, int> valueMap; // dont show multiple enum values which have the same values int pos = 0; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value) && isPowerOf2(value)) { if (isSubValue(flagValue, value)) intValue |= (1 << pos); valueMap[value] = pos++; } } return intValue; } int ObjectControllerPrivate::intToFlag(const QMetaEnum &metaEnum, int intValue) const { QMap<int, bool> valueMap; // dont show multiple enum values which have the same values QList<int> values; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value) && isPowerOf2(value)) { valueMap[value] = true; values.append(value); } } int flagValue = 0; int temp = intValue; int i = 0; while (temp) { if (i >= values.count()) return -1; if (temp & 1) flagValue |= values.at(i); i++; temp = temp >> 1; } return flagValue; } void ObjectControllerPrivate::updateClassProperties(const QMetaObject *metaObject, bool recursive) { if (!metaObject) return; if (recursive) updateClassProperties(metaObject->superClass(), recursive); QtProperty *classProperty = m_classToProperty.value(metaObject); if (!classProperty) return; for (int idx = metaObject->propertyOffset(); idx < metaObject->propertyCount(); idx++) { QMetaProperty metaProperty = metaObject->property(idx); if (metaProperty.isReadable()) { if (m_classToIndexToProperty.contains(metaObject) && m_classToIndexToProperty[metaObject].contains(idx)) { QtVariantProperty *subProperty = m_classToIndexToProperty[metaObject][idx]; if (metaProperty.isEnumType()) { if (metaProperty.isFlagType()) subProperty->setValue(flagToInt(metaProperty.enumerator(), metaProperty.read(m_object).toInt())); else subProperty->setValue(enumToInt(metaProperty.enumerator(), metaProperty.read(m_object).toInt())); } else { subProperty->setValue(metaProperty.read(m_object)); } } } } } void ObjectControllerPrivate::addClassProperties(const QMetaObject *inmetaObject, bool subGroup) { if (!inmetaObject) return; // Collect a list of all sub classes in the object QList< const QMetaObject *> metaObjectsList; metaObjectsList.clear(); metaObjectsList << inmetaObject; const QMetaObject *tmpObj = inmetaObject->superClass(); metaObjectsList << tmpObj; while (tmpObj) { tmpObj = tmpObj->superClass(); if (tmpObj) metaObjectsList << tmpObj; } const QMetaObject *metaObject; for (int i = 0; i < metaObjectsList.count(); i++) { metaObject = metaObjectsList[i]; QtProperty *classProperty = m_classToProperty.value(metaObject); if (!classProperty) { QString className = QLatin1String(metaObject->className()); // Note: Skip class QObject from the property views if (className == QLatin1String("QObject")) return; // Process Class name into a user friendly view // Strip prefix C_ and process all _ to spaces className.replace(QString("C_"), QString("")); className.replace(QString("_"), QString(" ")); classProperty = m_manager->addProperty(QtVariantPropertyManager::groupTypeId(), className); m_classToProperty[metaObject] = classProperty; m_propertyToClass[classProperty] = metaObject; for (int idx = metaObject->propertyOffset(); idx < metaObject->propertyCount(); idx++) { QMetaProperty metaProperty = metaObject->property(idx); int type = metaProperty.userType(); QtVariantProperty *subProperty = 0; // Note: Get the var member name and check if we want it to be writable (Enabled) QString memberVarName = QLatin1String(metaProperty.name()); bool b_SetEnabled = true; // Special case for enabling or disabling editing QString ememberVarName = "e" + QLatin1String(metaProperty.name()); QByteArray array = ememberVarName.toLocal8Bit(); char* buffer = array.data(); QVariant set = m_object->property(buffer); if (set.type() == QVariant::Bool) { b_SetEnabled = (bool &)set; } // qDebug() << "Member Name :" << memberVarName; // Note: process the first char if it contains _ then the var is read only and remove the _ char if (memberVarName.at(0) == "_") { b_SetEnabled = false; memberVarName.remove(0, 1); } // after that replace all occurance of _ with space char for display memberVarName.replace(QString("_"), QString(" ")); if (!metaProperty.isReadable()) { subProperty = m_readOnlyManager->addProperty(QVariant::String, memberVarName); subProperty->setValue(QLatin1String("< Non Readable >")); } else if (metaProperty.isEnumType()) { if (metaProperty.isFlagType()) { subProperty = m_manager->addProperty(QtVariantPropertyManager::flagTypeId(), memberVarName); QMetaEnum metaEnum = metaProperty.enumerator(); QMap<int, bool> valueMap; QStringList flagNames; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value) && isPowerOf2(value)) { valueMap[value] = true; flagNames.append(QLatin1String(metaEnum.key(i))); } subProperty->setAttribute(QLatin1String("flagNames"), flagNames); subProperty->setValue(flagToInt(metaEnum, metaProperty.read(m_object).toInt())); } } else { subProperty = m_manager->addProperty(QtVariantPropertyManager::enumTypeId(), memberVarName); QMetaEnum metaEnum = metaProperty.enumerator(); QMap<int, bool> valueMap; // dont show multiple enum values which have the same values QStringList enumNames; for (int i = 0; i < metaEnum.keyCount(); i++) { int value = metaEnum.value(i); if (!valueMap.contains(value)) { valueMap[value] = true; enumNames.append(QLatin1String(metaEnum.key(i))); } } subProperty->setAttribute(QLatin1String("enumNames"), enumNames); subProperty->setValue(enumToInt(metaEnum, metaProperty.read(m_object).toInt())); } } else if (m_manager->isPropertyTypeSupported(type)) { if (!metaProperty.isWritable()) subProperty = m_readOnlyManager->addProperty(type, memberVarName + QLatin1String(" (Non Writable)")); if (!metaProperty.isDesignable()) subProperty = m_readOnlyManager->addProperty(type, memberVarName + QLatin1String(" (Non Designable)")); else subProperty = m_manager->addProperty(type, memberVarName); subProperty->setValue(metaProperty.read(m_object)); } else { subProperty = m_readOnlyManager->addProperty(QVariant::String, memberVarName); subProperty->setValue(QLatin1String("< Unknown Type >")); b_SetEnabled = false; } // Notes: QtVariantProperty *priority = variantManager->addProperty(QVariant::Int, "Priority"); if (subProperty) subProperty->setEnabled(b_SetEnabled); m_propertyToIndex[subProperty] = idx; m_classToIndexToProperty[metaObject][idx] = subProperty; if (subGroup) classProperty->addSubProperty(subProperty); else m_browser->addProperty(subProperty); } } else { updateClassProperties(metaObject, false); } m_topLevelProperties.append(classProperty); if (subGroup) m_browser->addProperty(classProperty); } // Loop i } void ObjectControllerPrivate::saveExpandedState() { } void ObjectControllerPrivate::restoreExpandedState() { } void ObjectControllerPrivate::slotValueChanged(QtProperty *property, const QVariant &value) { if (!m_propertyToIndex.contains(property)) return; int idx = m_propertyToIndex.value(property); const QMetaObject *metaObject = m_object->metaObject(); QMetaProperty metaProperty = metaObject->property(idx); if (metaProperty.isEnumType()) { if (metaProperty.isFlagType()) metaProperty.write(m_object, intToFlag(metaProperty.enumerator(), value.toInt())); else metaProperty.write(m_object, intToEnum(metaProperty.enumerator(), value.toInt())); } else { metaProperty.write(m_object, value); } updateClassProperties(metaObject, true); } /////////////////// QtProperty *ObjectController::getProperty(QString propertyName) { if (m_use_treeView) { QList<QtBrowserItem *> topLevelItems = d_ptr->m_browser->topLevelItems(); QList<QtBrowserItem *>::iterator i; for (i = topLevelItems.begin(); i != topLevelItems.end(); ++i) { if ((*i)) { QtProperty *rootprop = (*i)->property(); QString rootName = rootprop->propertyName(); //qDebug() << "Root PropertyName: " << rootName; if (propertyName.compare(rootName) == 0) { return rootprop; } QList<QtBrowserItem *> children = (*i)->children(); QList<QtBrowserItem *>::iterator j; for (j = children.begin(); j != children.end(); ++j) { if ((*j)) { QtProperty *prop = (*j)->property(); QString propName = prop->propertyName(); //qDebug() << "Child PropertyName: " << propName; if (propertyName.compare(propName) == 0) { return prop; } } } } } } return nullptr; } QtTreePropertyBrowser *ObjectController::getTreeBrowser() { return (QtTreePropertyBrowser *)d_ptr->m_browser; } ObjectController::ObjectController(QWidget *parent, bool use_treeView, bool ReadOnly) : QWidget(parent) { m_use_treeView = use_treeView; m_ReadOnly = ReadOnly; d_ptr = new ObjectControllerPrivate; d_ptr->q_ptr = this; d_ptr->m_object = 0; QScrollArea *scroll = new QScrollArea(this); scroll->setWidgetResizable(true); QVBoxLayout *layout = new QVBoxLayout(this); if (use_treeView) { QtTreePropertyBrowser *browser = new QtTreePropertyBrowser(this); browser->setRootIsDecorated(false); d_ptr->m_browser = browser; } else { d_ptr->m_browser = new QtGroupBoxPropertyBrowser(this); } layout->setMargin(0); layout->addWidget(scroll); scroll->setWidget(d_ptr->m_browser); d_ptr->m_readOnlyManager = new QtVariantPropertyManager(this); d_ptr->m_manager = new QtVariantPropertyManager(this); QtVariantEditorFactory *factory = new QtVariantEditorFactory(this); if (ReadOnly) d_ptr->m_browser->setFactoryForManager(d_ptr->m_readOnlyManager, factory); else d_ptr->m_browser->setFactoryForManager(d_ptr->m_manager, factory); connect(d_ptr->m_manager, SIGNAL(valueChanged(QtProperty *, const QVariant &)), this, SLOT(slotValueChanged(QtProperty *, const QVariant &))); } ObjectController::~ObjectController() { if (d_ptr) { delete d_ptr; d_ptr = NULL; } } void ObjectController::setObject(QObject *object, bool subGroup, bool forceRefresh) { if ((d_ptr->m_object == object) && (!forceRefresh)) return; if (d_ptr->m_object) { d_ptr->saveExpandedState(); QListIterator<QtProperty *> it(d_ptr->m_topLevelProperties); while (it.hasNext()) { d_ptr->m_browser->removeProperty(it.next()); } d_ptr->m_topLevelProperties.clear(); } d_ptr->m_object = object; if (!d_ptr->m_object) return; d_ptr->addClassProperties(d_ptr->m_object->metaObject(), subGroup); d_ptr->restoreExpandedState(); } QObject *ObjectController::object() const { return d_ptr->m_object; } #include "moc_objectcontroller.cpp"
[ "navin.patel@amd.com" ]
navin.patel@amd.com
00faf6895c1ae0a8623ad9d95f4c08bbcc66a84a
413a1d85f164ab38ef876452ac3c363f9df058c4
/wiki_app/venv/lib/python3.5/site-packages/lucene-8.1.1-py3.5-linux-x86_64.egg/lucene/include/org/apache/lucene/search/uhighlight/FieldHighlighter.h
9942f51b0b8ecb2632b68abc3d7f29411fcc9f0d
[]
no_license
prateek68/Wikipedia-Online-Content-Comparison
18d53e3456e2d7aa6eb67629c2ea1c79b7d8be4d
77d54b99881558b3195190740ba1be7f8328392b
refs/heads/master
2020-12-26T11:58:18.903011
2020-02-02T09:55:37
2020-02-02T09:55:37
237,495,848
1
2
null
null
null
null
UTF-8
C++
false
false
3,066
h
#ifndef org_apache_lucene_search_uhighlight_FieldHighlighter_H #define org_apache_lucene_search_uhighlight_FieldHighlighter_H #include "java/lang/Object.h" namespace java { namespace io { class IOException; } namespace text { class BreakIterator; } namespace lang { class String; class Class; } } namespace org { namespace apache { namespace lucene { namespace index { class LeafReader; } namespace search { namespace uhighlight { class PassageFormatter; class UnifiedHighlighter$OffsetSource; class PassageScorer; class FieldOffsetStrategy; } } } } } template<class T> class JArray; namespace org { namespace apache { namespace lucene { namespace search { namespace uhighlight { class FieldHighlighter : public ::java::lang::Object { public: enum { mid_init$_0356987da203cab8, mid_getField_a59eabb26a802fa9, mid_getOffsetSource_5b3770419eff268a, mid_highlightFieldForDoc_8857ee6e893fc1e7, mid_highlightOffsetsEnums_9b11d9f5afd8b0fd, mid_getSummaryPassagesNoHighlight_e9dda1e290641ad5, max_mid }; static ::java::lang::Class *class$; static jmethodID *mids$; static bool live$; static jclass initializeClass(bool); explicit FieldHighlighter(jobject obj) : ::java::lang::Object(obj) { if (obj != NULL && mids$ == NULL) env->getClass(initializeClass); } FieldHighlighter(const FieldHighlighter& obj) : ::java::lang::Object(obj) {} FieldHighlighter(const ::java::lang::String &, const ::org::apache::lucene::search::uhighlight::FieldOffsetStrategy &, const ::java::text::BreakIterator &, const ::org::apache::lucene::search::uhighlight::PassageScorer &, jint, jint, const ::org::apache::lucene::search::uhighlight::PassageFormatter &); ::java::lang::String getField() const; ::org::apache::lucene::search::uhighlight::UnifiedHighlighter$OffsetSource getOffsetSource() const; ::java::lang::Object highlightFieldForDoc(const ::org::apache::lucene::index::LeafReader &, jint, const ::java::lang::String &) const; }; } } } } } #include <Python.h> namespace org { namespace apache { namespace lucene { namespace search { namespace uhighlight { extern PyType_Def PY_TYPE_DEF(FieldHighlighter); extern PyTypeObject *PY_TYPE(FieldHighlighter); class t_FieldHighlighter { public: PyObject_HEAD FieldHighlighter object; static PyObject *wrap_Object(const FieldHighlighter&); static PyObject *wrap_jobject(const jobject&); static void install(PyObject *module); static void initialize(PyObject *module); }; } } } } } #endif
[ "prateek16068@iiitd.ac.in" ]
prateek16068@iiitd.ac.in
9566a4baee48084c18f7a24bf19832abdf77360e
d13384eb8025ba0c0830fabec28104813b5a474d
/RayTracer/Texture.cpp
319ff43d1dc6588482263dede7884a48c2fceaed
[]
no_license
devgoose/RayTracer
f61fcd04f027080ad5cdc17c5705e310ab9aa2e1
d9b369047aa910057fd5065079aebec0c965cbab
refs/heads/main
2023-02-14T17:09:10.542168
2021-01-17T10:05:25
2021-01-17T10:05:25
308,991,187
0
0
null
null
null
null
UTF-8
C++
false
false
2,334
cpp
#include "Texture.h" #include <iostream> #include <fstream> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include "Color.h" Texture::Texture() { height = 0; width = 0; } Texture::Texture(std::string filename) { load(filename); } Texture::~Texture() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { delete texture[i][j]; } } } Color* Texture::getColorAtCoord(int i, int j) const { return texture[i][j]; } bool Texture::load(std::string filename) { std::ifstream fin; fin.open(filename); if (!fin.is_open()) { std::cout << "Error opening " << filename << " to load texture.\n"; return false; } std::string header; int w, h; float max_value; fin >> header; if (!fin || header.compare("P3")) { std::cout << "Error on " + filename + " header.\n"; return false; } fin >> w >> h >> max_value; if (!fin || w < 0 || h < 0 || max_value < 0) { std::cout << "Error with height/width/pixel maximum value in " + filename << std::endl; return false; } // Header successfully read. Now read colors height = h; width = w; std::string line; int line_number = 0; // Get file size for progress bar struct stat stat_buf; stat(filename.c_str(), &stat_buf); long size = stat_buf.st_size; for (int i = 0; i < height; i++) { std::vector<Color*> row; for (int j = 0; j < width; j++) { float r, g, b; Color* c; fin >> r >> g >> b; if (fin) { c = new Color(r / max_value, g / max_value, b / max_value); } else { // std::cout << "Error parsing " << filename << " on line " << line_number << std::endl; // return false; c = new Color(); } row.push_back(c); line_number++; } texture.push_back(row); /////////////// // PROGRESS BAR // TODO: PUT IN UTIL //////////////// int bar_size = 25; float percentage = (float)i / (float)height; printf("\rProgress reading %s: ", filename.c_str()); for (int k = 0; k < bar_size; k++) { if (k <= percentage * bar_size) { // output a block character printf("%c", 219); } else { printf("-"); } } fflush(stdout); } std::cout << std::endl; fin.close(); return true; }
[ "walte735@umn.edu" ]
walte735@umn.edu
f8828c3afaf3c67026ae4e58cc19fc2631c29bc7
0e5bee86480046fa5ece33e8a6cb0ee6ffddf381
/Homework3/NYUCodebase/main.cpp
77b907de3f17c9f647ef9442c22b797e41ac8fe3
[]
no_license
bk1613/gamedesign
c51605fca555f79c9f48d789581cc0b45f4b8dcb
5fba505b038ed5250e3fd7321cdcc9af9d32a956
refs/heads/master
2021-05-05T14:51:07.028541
2018-05-09T17:48:24
2018-05-09T17:48:24
118,501,147
0
0
null
null
null
null
UTF-8
C++
false
false
13,093
cpp
#ifdef _WINDOWS #include <GL/glew.h> #endif #include <SDL.h> #include <SDL_opengl.h> #include <SDL_image.h> #include "Matrix.h" #include "ShaderProgram.h" //STB_image loads images #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <vector> #include <algorithm> #ifdef _WINDOWS #define RESOURCE_FOLDER "" #else #define RESOURCE_FOLDER "NYUCodebase.app/Contents/Resources/" #endif SDL_Window* displayWindow; using namespace std; GLuint LoadTexture(const char *filePath) { int w, h, comp; unsigned char* image = stbi_load(filePath, &w, &h, &comp, STBI_rgb_alpha); if (image == NULL) { std::cout << "Unable to load image. Make sure the path is correct\n"; assert(false); } GLuint retTexture; glGenTextures(1, &retTexture); glBindTexture(GL_TEXTURE_2D, retTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); stbi_image_free(image); return retTexture; } class SheetSprite { public: SheetSprite() {} SheetSprite(unsigned int te, float givenU, float givenV, float givenWidth, float givenHeight, float givenSize) : size(givenSize), textureID(te),u(givenU), v(givenV), width(givenWidth), height(givenHeight) {} void Draw(ShaderProgram *program); float size; unsigned int textureID; float u; float v; float width; float height; }; void SheetSprite::Draw(ShaderProgram *program) { glBindTexture(GL_TEXTURE_2D, textureID); GLfloat textCoords[] = { u, v + height, u + width, v, u, v, u + width, v, u, v + height, u + width, v + height }; float aspect = width / height; float vertices[] = { -0.5f * size * aspect, -0.5f * size, 0.5f * size * aspect, 0.5f * size, -0.5f * size * aspect, 0.5f * size, 0.5f * size * aspect, 0.5f * size, -0.5f * size * aspect, -0.5f * size, 0.5f * size * aspect, -0.5f * size, }; glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program->positionAttribute); glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, textCoords); glEnableVertexAttribArray(program->texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program->positionAttribute); glDisableVertexAttribArray(program->texCoordAttribute); } void DrawText(ShaderProgram *program, int fontTexture, string text, float size, float spacing) { float texture_size = 1.0 / 16.0f; vector<float> vertexData; vector<float> texCoordData; for (int i = 0; i < text.size(); i++) { int spriteIndex = (int)text[i]; float texture_x = (float)(spriteIndex % 16) / 16.0f; float texture_y = (float)(spriteIndex / 16) / 16.0f; vertexData.insert(vertexData.end(), { ((size + spacing) * i) + (-0.5f * size), 0.5f * size, ((size + spacing) * i) + (-0.5f * size), -0.5f * size, ((size + spacing) * i) + (0.5f * size), 0.5f * size, ((size + spacing) * i) + (0.5f * size), -0.5f * size, ((size + spacing) * i) + (0.5f * size), 0.5f * size, ((size + spacing) * i) + (-0.5f * size), -0.5f * size, }); texCoordData.insert(texCoordData.end(), { texture_x, texture_y, texture_x, texture_y + texture_size, texture_x + texture_size, texture_y , texture_x + texture_size, texture_y + texture_size, texture_x + texture_size, texture_y , texture_x, texture_y + texture_size, }); } glBindTexture(GL_TEXTURE_2D, fontTexture); glUseProgram(program->programID); glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertexData.data()); glEnableVertexAttribArray(program->positionAttribute); glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordData.data()); glEnableVertexAttribArray(program->texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, text.size() * 6); glDisableVertexAttribArray(program->positionAttribute); glDisableVertexAttribArray(program->texCoordAttribute); } class Entity { public: Entity() {} float pistolpos_x; float pistolpos_y; float pistolvelocity_y; float dir_x = sin(0.785398); float dir_y = 1.0f; float position_x; float position_y; float shippositionX = 0.0f; float timeAlive = 0.0f; SheetSprite sprite; }; class Gamestate { public: vector<Entity> entities; vector<Entity> bullets; int numEnemies = 0; int score = 0; bool gamestop = false; }; bool BoxBoxCollision(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) { if (y1 + h1 / 2.0f < y2 - h2 / 2.0f || y1 - h1 / 2.0f > y2 + h2 / 2.0f || x1 - w1 / 2.0f > x2 + w2 / 2.0f || x1 + w1 / 2.0f < x2 - w2 / 2.0f) { return false; } else { return true; } } bool shouldREMOVEBullet(Entity bullet) { if (bullet.timeAlive > 0.5) { return true; } else { return false; } } Gamestate pistol; Gamestate enemyentit; Gamestate state; Entity playerpos; void Update(float elapsed) { for (int i = 0; i < enemyentit.entities.size(); i++) { enemyentit.entities[i].position_x += enemyentit.entities[i].dir_x * 3.0f * elapsed; if (!((enemyentit.entities[i].position_x - 0.5) < -3.50)) { enemyentit.entities[i].dir_x = -enemyentit.entities[i].dir_x; } if (!((enemyentit.entities[i].position_x + 0.5) > 3.50)) { enemyentit.entities[i].dir_x = -enemyentit.entities[i].dir_x; } } pistol.bullets.erase(remove_if(pistol.bullets.begin(), pistol.bullets.end(), shouldREMOVEBullet), pistol.bullets.end()); for (int i = 0; i < pistol.bullets.size(); i++) { pistol.bullets[i].pistolpos_y += pistol.bullets[i].pistolvelocity_y * elapsed; Entity backpos; for (int j = 0; j < enemyentit.entities.size(); j++) { if (BoxBoxCollision(enemyentit.entities[j].position_x, enemyentit.entities[j].position_y, 0.35, 0.35, pistol.bullets[i].pistolpos_x, pistol.bullets[i].pistolpos_y, 0.025*2, 0.085*2)){ pistol.bullets[i].pistolpos_x = 10.0; // backpos.shippositionX; enemyentit.entities[j].position_x = 4.76;; state.numEnemies--; state.score += 50; } } } const Uint8 *keys = SDL_GetKeyboardState(NULL); if (keys[SDL_SCANCODE_RIGHT]) { if (!((playerpos.shippositionX + 0.5) > 3.55)) { playerpos.shippositionX += 2.25f * elapsed; } } else if (keys[SDL_SCANCODE_LEFT]) { if (!((playerpos.shippositionX - 0.5) < -3.55)) { playerpos.shippositionX -= 2.25f * elapsed; } } } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO);// | SDL_INIT_JOYSTICK); displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif SDL_Event event; bool done = false; glViewport(0, 0, 640, 360); ShaderProgram programuntextured; programuntextured.Load(RESOURCE_FOLDER "vertex.glsl", RESOURCE_FOLDER "fragment.glsl"); Matrix projectionMatrixuntext; Matrix modelMatrixuntext; Matrix viewMatrixuntext; programuntextured.SetModelMatrix(modelMatrixuntext); projectionMatrixuntext.SetOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f); glUseProgram(programuntextured.programID); //textured ShaderProgram programtextured; programtextured.Load(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl"); GLuint player = LoadTexture(RESOURCE_FOLDER"playerShip1_red.png"); //GLuint explosion = LoadTexture(RESOURCE_FOLDER"explosion.png"); GLuint spriteSheetTexture = LoadTexture("sheet.png"); GLuint text = LoadTexture("font1.png"); Entity entity; for (int i = 0; i < 5; i++) { Entity enemy; for (int j = 0; j < 10; j++) { enemy.sprite = SheetSprite(spriteSheetTexture, 423.0f/1024.0f, 728.0f/1024.0f, 93.0f/1024.0f, 84.0f/1024.0f, 0.35); enemy.position_x = j * 0.5f - 3.0f; enemy.position_y = i * 0.4f - .15f; state.numEnemies += 1; enemyentit.entities.push_back(enemy); } } Matrix projectionMatrix; Matrix modelMatrix; Matrix modelMatrix2; Matrix modelMatrixtext; Matrix viewMatrix; projectionMatrix.SetOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f); enum GameMode { TITLE_SCREEN, GAME }; GameMode mode = TITLE_SCREEN; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(programtextured.programID); float lastFrameTicks = 0.0f; bool begingame = false; float accumulator = 0.0f; programtextured.SetProjectionMatrix(projectionMatrix); programtextured.SetViewMatrix(viewMatrix); programuntextured.SetProjectionMatrix(projectionMatrixuntext); programuntextured.SetViewMatrix(viewMatrixuntext); //End Setup //Running program while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { // check if window close done = true; } else if (event.type == SDL_KEYDOWN) { //Press enter key to begin game if (event.key.keysym.scancode == SDL_SCANCODE_RETURN) { if (mode == TITLE_SCREEN) { mode = GAME; lastFrameTicks = (float)SDL_GetTicks() / 1000.0f; } } else if (event.key.keysym.scancode == SDL_SCANCODE_SPACE) { Entity newbullt; newbullt.pistolpos_x = playerpos.shippositionX; newbullt.pistolpos_y = -1.6; newbullt.pistolvelocity_y = 2.05f; newbullt.timeAlive = 0.0f; pistol.bullets.push_back(newbullt); } } } glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.4f, 0.3f, 2.25f, 1.0f); switch (mode) { case TITLE_SCREEN: modelMatrixtext.Identity(); modelMatrixtext.Translate(-3.0f, 1.0f, 0.0f); programtextured.SetModelMatrix(modelMatrixtext); DrawText(&programtextured, text, "Welcome to Space Invaders", ((3.5 / 25.0f) * 2.0f), -0.03f); modelMatrixtext.Identity(); modelMatrixtext.Translate(-1.16f, -1.0f, 0.0f); programtextured.SetModelMatrix(modelMatrixtext); DrawText(&programtextured, text, "Press Enter", ((3.0 / 25.0f) * 2.0f), -0.05f); break; case GAME: float ticks = (float)SDL_GetTicks() / 1000.0f; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; Entity bullet; shouldREMOVEBullet(bullet); Update(elapsed); //pistol for (int b = 0; b < pistol.bullets.size(); b++) { modelMatrixuntext.Identity(); modelMatrixuntext.Translate(pistol.bullets[b].pistolpos_x, pistol.bullets[b].pistolpos_y, 0.0f); programuntextured.SetModelMatrix(modelMatrixuntext); programuntextured.SetProjectionMatrix(projectionMatrixuntext); programuntextured.SetViewMatrix(viewMatrixuntext); float verticespistol[] = { -0.025, -0.085, 0.025, -0.085, 0.025, 0.085, -0.025, -0.085, 0.025, 0.085, -0.025, 0.085 }; glVertexAttribPointer(programuntextured.positionAttribute, 2, GL_FLOAT, false, 0, verticespistol); glEnableVertexAttribArray(programuntextured.positionAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(programuntextured.positionAttribute); } //enemy ships for (int i = 0; i < enemyentit.entities.size(); i++) { modelMatrix2.Identity(); modelMatrix2.Translate(enemyentit.entities[i].position_x, enemyentit.entities[i].position_y, 0.0f); programtextured.SetModelMatrix(modelMatrix2); enemyentit.entities[i].sprite.Draw(&programtextured); } //player ship modelMatrix.Identity(); modelMatrix.Translate(playerpos.shippositionX, -1.65f, 0.0f); programtextured.SetModelMatrix(modelMatrix); programtextured.SetProjectionMatrix(projectionMatrix); programtextured.SetViewMatrix(viewMatrix); glBindTexture(GL_TEXTURE_2D, player); float verticesship[] = { -0.25, -0.25, 0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, 0.25 }; glVertexAttribPointer(programtextured.positionAttribute, 2, GL_FLOAT, false, 0, verticesship); glEnableVertexAttribArray(programtextured.positionAttribute); float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 }; glVertexAttribPointer(programtextured.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(programtextured.texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(programtextured.positionAttribute); glDisableVertexAttribArray(programtextured.texCoordAttribute); if (state.numEnemies == 0 || state.gamestop) { enemyentit.entities.clear(); mode = TITLE_SCREEN; } modelMatrixtext.Identity(); modelMatrixtext.Translate(-2.2f, 1.9f, 0.0f); programtextured.SetModelMatrix(modelMatrixtext); DrawText(&programtextured, text, to_string(state.score), ((3.5 / 25.0f) * 2.0f), -0.08f); break; } //End Drawing SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
[ "bk1613@nyu.edu" ]
bk1613@nyu.edu
2f38b9f06d19a238c7933254ab4063dbe84ef2ec
fc9ec32670150cce44432b6b43dca6ae7e9a56bc
/codeforces/401/C.cpp
d93af94afbaa805ff995beaf4b1722377e1af9f5
[]
no_license
ArthurEmidio/programming-problems
e3efc16ad826a6f4b43277b72ef90189aec868c7
16a8c3883649efaf1ab0475036f017638bfe343f
refs/heads/master
2020-12-04T12:37:06.643514
2017-06-27T07:49:10
2017-06-27T07:49:10
65,958,563
2
0
null
null
null
null
UTF-8
C++
false
false
1,802
cpp
#include <bits/stdc++.h> using namespace std; #define oo 0x3f3f3f3f3f3f3f3f #define EPS 1e-6 #define PI 3.14159265358979323846 #define ff first #define ss second #define mp(i,j) make_pair(i,j) typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; int main() { ios_base::sync_with_stdio(false); int n, m; scanf("%d %d", &n, &m); vector<vector<int>> M(n, vector<int>(m, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &M[i][j]); } } vector<ii> ranges; for (int i = 0; i < m; i++) { int j = 0; while (j < n) { while (j+1 < n && M[j][i] > M[j+1][i]) j++; if (j+1 == n) break; int k = j; j++; while (j < n && M[j][i] >= M[j-1][i]) j++; // k to j-1 ranges.push_back(ii(k+1, j)); } } sort(ranges.begin(), ranges.end(), [](const ii &p1, const ii &p2) { return p1.ff == p2.ff ? (p1.ss > p2.ss) : (p1.ff < p2.ff); }); vector<ii> ranges2; for (int i = 0; i < ranges.size();) { int j = i+1; int r = ranges[i].ss; while (j < ranges.size() && ranges[i].ss >= ranges[j].ss) r = max(r, ranges[j++].ss); ranges2.push_back(ii(ranges[i].ff, r)); i = j; } int k; scanf("%d", &k); for (int i = 0; i < k; i++) { int l, r; scanf("%d %d", &l, &r); auto it = upper_bound(ranges2.begin(), ranges2.end(), ii(l, INT_MAX)); bool ans = l == r; if (!ranges2.empty() && it != ranges2.begin()) { it = prev(it); ii rg = *it; if (rg.ff <= l && rg.ss >= r) ans = true; } printf("%s\n", ans ? "Yes" : "No"); } return 0; }
[ "arthur.500@gmail.com" ]
arthur.500@gmail.com
65a9c7b5dfff691b17db4528f19c37fddd972cdd
f29b09b1b428ff25731cbdfaa499c18102f36d5e
/examples/example_face_detect/main.cc
2fffd3a6bdb7f60bcb4f4995066e57b4bf1624ed
[ "BSD-3-Clause" ]
permissive
foss-for-synopsys-dwc-arc-processors/embarc_mli
ee4c052ec97e242706dd14cee4f6cb27421c23a1
b364bc137463a076a4fd9bed38b2143644c23c3a
refs/heads/mli_dev
2023-04-13T13:39:48.458305
2022-11-07T13:30:32
2022-11-08T19:59:49
170,473,341
31
8
NOASSERTION
2023-03-25T01:18:02
2019-02-13T08:50:37
C++
UTF-8
C++
false
false
6,252
cc
/* * Copyright 2021, Synopsys, Inc. * All rights reserved. * * This source code is licensed under the BSD-3-Clause license found in * the LICENSE file in the root directory of this source tree. * */ #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <memory> #include "bmp_file_io.h" #include "face_detect_module.h" using mli_fd::fd_module; using mli_fd::point; constexpr uint32_t kDetectionsMemBudget = 1024; // Draw a key point mark defined by coordinates on the output RGB image //===================================================================== static inline void draw_a_keypoint_rgb(point coord, uint8_t* output, const int32_t x_res, const int32_t y_res) { const uint8_t val_r = 0xFF; const uint8_t val_g = 0x00; const uint8_t val_b = 0x00; const int channels = 3; coord.row = std::min(coord.row, y_res - 1); coord.clmn = std::min(coord.clmn, x_res - 1); int idx = (coord.row * x_res + coord.clmn) * channels; output[idx++] = val_r; output[idx++] = val_g; output[idx++] = val_b; } // Draw a frame defined by corner coordinates on the output RGB image //===================================================================== static inline void draw_a_frame_rgb(point top_left, point bot_right, uint8_t* output, const int32_t x_res, const int32_t y_res) { const uint8_t val_r = 0xFF; const uint8_t val_g = 0x00; const uint8_t val_b = 0x00; const int channels = 3; top_left.row = std::min(top_left.row, y_res - 1); top_left.clmn = std::min(top_left.clmn, x_res - 1); bot_right.row = std::min(bot_right.row, y_res - 1); bot_right.clmn = std::min(bot_right.clmn, x_res - 1); int idx = (top_left.row * x_res + top_left.clmn) * channels; for (int i = 0; i <= bot_right.clmn - top_left.clmn; i++) { output[idx++] = val_r; output[idx++] = val_g; output[idx++] = val_b; } idx = (bot_right.row * x_res + top_left.clmn) * channels; for (int i = 0; i <= bot_right.clmn - top_left.clmn; i++) { output[idx++] = val_r; output[idx++] = val_g; output[idx++] = val_b; } idx = (top_left.row * x_res + top_left.clmn) * channels; for (int i = 0; i < bot_right.row - top_left.row; i++, idx += x_res * channels) { output[idx + 0] = val_r; output[idx + 1] = val_g; output[idx + 2] = val_b; } idx = (top_left.row * x_res + bot_right.clmn) * channels; for (int i = 0; i < bot_right.row - top_left.row; i++, idx += x_res * channels) { output[idx + 0] = val_r; output[idx + 1] = val_g; output[idx + 2] = val_b; } } //===================================================================== // Main function //===================================================================== int main(int argc, char *argv[]) { std::unique_ptr<uint8_t[]> input_image_data; // empty const char* input_path = NULL; // Checking the command line if (argc != 2) { printf("Missing command line argument: input filename\n"); return -1; } input_path = argv[1]; // Reading the input data static_assert(fd_module::kInChannels == 3, "kInChannels != 3: RGB input processing is only supported"); const int img_width = fd_module::kInSpatialDimSize; const int img_height = fd_module::kInSpatialDimSize; input_image_data.reset(bmp_rgb_read(input_path, img_width, img_width)); if (!input_image_data) { printf("Failed to read input image\n"); return -1; } // Invoking detector to write result into statically allocated memory const uint32_t max_detections = kDetectionsMemBudget / fd_module::get_single_detection_mem_size(); static int8_t detections_mem[kDetectionsMemBudget]; static fd_module detector; // Dynamic? auto detections = detector.invoke(input_image_data.get(), detections_mem, sizeof(detections_mem)); if (detections.detections_num >= max_detections) { printf("WARNING: Static Detections Buffer is full. Consider to increase it.\n"); } else if (detections.detections_num <= 0) { printf("No detections in input image.\n"); } printf("Pre_process ticks: %lld\n", detector.get_prof_ticks(fd_module::prof_tick_id::kProfPreProcess)); printf("Model ticks: %lld\n", detector.get_prof_ticks(fd_module::prof_tick_id::kProfModel)); printf("Post_process ticks: %lld\n", detector.get_prof_ticks(fd_module::prof_tick_id::kProfPostProcess)); printf("Total ticks: %lld\n", detector.get_prof_ticks(fd_module::prof_tick_id::kProfTotal)); for (int det_idx = 0; det_idx < detections.detections_num; ++det_idx) { const auto bbox_top_left = fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordBboxTopLeft); const auto bbox_bot_right = fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordBboxBotRight); const float bbox_score = fd_module::get_score(detections, det_idx); printf(" Found a face at ([X:%d, Y:%d]; [X:%d, Y:%d]) with (%f) score\n", bbox_top_left.clmn, bbox_top_left.row, bbox_bot_right.clmn, bbox_bot_right.row, bbox_score); draw_a_frame_rgb(bbox_top_left, bbox_bot_right, input_image_data.get(), img_width, img_height); draw_a_keypoint_rgb(fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordLeftEye), input_image_data.get(), img_width, img_height); draw_a_keypoint_rgb(fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordRightEye), input_image_data.get(), img_width, img_height); draw_a_keypoint_rgb(fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordNose), input_image_data.get(), img_width, img_height); draw_a_keypoint_rgb(fd_module::get_coordinate(detections, det_idx, fd_module::coord_id::kCoordMouth), input_image_data.get(), img_width, img_height); } bmp_rgb_write("result.bmp", input_image_data.get(), img_width, img_height); printf("Done. See result in \"result.bmp\" file.\n"); return 0; }
[ "47519863+dzakhar@users.noreply.github.com" ]
47519863+dzakhar@users.noreply.github.com
4e974d2acff1664db94b2f60e7b5dd1ff481f83e
86798d4b8ccaa9ac4b66b3e86f87fec62df70180
/DS & Algo Implementation/Data Structure/Kadane/Med.cpp
80204be7c93164e7d9d8a827ed4a08bb4bebed4a
[]
no_license
sakiib/competitive-programming-code-library
03675e4c9646bd0d65f08b146310abfd4b36f1c4
e25d7f50932fb2659bbe3673daf846eb5e7c5428
refs/heads/master
2022-12-04T16:11:18.307005
2022-12-03T14:25:49
2022-12-03T14:25:49
208,120,580
5
1
null
null
null
null
UTF-8
C++
false
false
2,060
cpp
#include <bits/stdc++.h> using namespace std; #define endl "\n" int n; int a[ 305 ][ 305 ]; int sum[ 305 ][ 305 ][ 20 ]; void calc( ) { for( int i = 1; i <= n; i++ ) { for( int j = 1; j <= n; j++ ) { for( int k = 1; k <= 15; k++ ) { sum[i][j][k] += sum[i][j-1][k]; } } } for( int i = 1; i <= n; i++ ) { for( int j = 1; j <= n; j++ ) { for( int k = 1; k <= 15; k++ ) { sum[i][j][k] += sum[i-1][j][k]; } } } /** /// this is sum off all numbers less than eq k , without just kon number koto bar ase. for( int i = 1; i <= n; i++ ) { for( int j = 1; j <= n; j++ ) { for( int k = 1; k <= 15; k++ ) { sum[i][j][k] += sum[i][j][k-1]; } } }*/ } int getSum( int x1 , int y1 , int x2 , int y2 , int key ) { /// LL , UR return sum[x2][y2][key] - sum[x2][y1-1][key] - sum[x1-1][y2][key] + sum[x1-1][y1-1][key]; } int main( int argc , char const *argv[] ) { ios_base::sync_with_stdio( false ); cin.tie( nullptr ); cin >> n; memset( sum , 0 , sizeof( sum ) ); for( int i = 1; i <= n; i++ ) { for( int j = 1; j <= n; j++ ) { cin >> a[i][j]; sum[i][j][a[i][j]]++; } } calc( ); int q; cin >> q; while( q-- ) { int x1 , y1 , x2 , y2; cin >> x1 >> y1 >> x2 >> y2; int ans = 0; for( int i = 1; i <= 10; i++ ) { if( getSum( x1 , y1 , x2 , y2 , i ) > 0 ) ans++; } cout << ans << endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
bf32cd1922d320ed4f9abb422e8b7d27d77bb3d7
2d9aa45d7195ae522a01af34744daaa184fb6204
/list-4/Theremin/Theremin.ino
b8c330c24bd4f07965529314f4d71cb6614c9d24
[]
no_license
mbuszka/university_embedded-systems
800ce8a7683ba71fbba50c15f55d0bd5b2d2f3b1
7b439021f7c19c69f5bd3ca091446f3bcd6e9a0b
refs/heads/master
2021-01-12T18:14:49.266526
2017-03-01T21:20:36
2017-03-01T21:20:36
71,348,630
0
1
null
2016-11-23T18:24:22
2016-10-19T11:05:33
Arduino
UTF-8
C++
false
false
1,347
ino
#include <Stopwatch.h> #include <Debouncer.h> #define NORMAL 0 #define PLAYING 1 #define RECORDING 2 #define SAMPLES 300 int outPin = 13; void setup() { pinMode(outPin, OUTPUT); Serial.begin(9600); } Debouncer playButton(2, 20); Debouncer recButton(3, 20); Stopwatch sw; unsigned long data[SAMPLES]; int currentSample = 0; int state = NORMAL; int play = 0; int record = 0; unsigned long frequency = 5000; void loop() { play = playButton.debouncedRead() == HIGH; record = recButton.debouncedRead() == HIGH; Serial.print(play); Serial.print(record); Serial.println(state); int read = analogRead(A1); // Serial.prin5885tln(read); frequency = map(read, 500, 950, 50, 5000 ); switch (state) { case NORMAL : if (play) { state = PLAYING; currentSample = 0; } else if (record) { state = RECORDING; currentSample = 0; } else { tone(outPin, frequency); } break; case PLAYING : tone(outPin, data[currentSample]); currentSample ++; if (currentSample >= SAMPLES) { state = NORMAL; } break; case RECORDING : tone(outPin, frequency); data[currentSample] = frequency; currentSample++; if (currentSample >= SAMPLES) { state = NORMAL; } break; } delay(10); }
[ "maciej@buszka.eu" ]
maciej@buszka.eu
1f1318c57aceac7b7a9adc55a0e8e8e56f27fce2
c9cd39d5d477028967adbdb890a0f965c6f0d312
/Samuel/pointlights/v2 experiments/pointlights/pointlights.ino
67d2fa60d40e378f8645e2dc77a4f8693d92c163
[]
no_license
ivarlundin/M2-interactivity
d66a7763c3b01e52861919825a7778341b2b16b0
6881996da07afb5033604540eb0aee7bfd04ef82
refs/heads/master
2023-01-05T22:51:44.560587
2020-10-08T12:30:40
2020-10-08T12:30:40
297,627,036
0
0
null
null
null
null
UTF-8
C++
false
false
9,118
ino
//Version 2 - Adding behaviour enum ledStates {START, INCREASE, DECREASE, STAY, WAVE, OFF, ON, INCREASEAGAIN, HALFSINE, OFF2, FADEOUT}; // Here we make nicknames for the different states our program supports. enum ledStates ledState; // We define 'ledState' as type ledStates' enum ledStates previousLedState = ledState; unsigned long startMillis; //some global variables available anywhere in the program unsigned long currentMillis; //Global variables int brightness = 0; // our main variable for setting the brightness of the LED float velocity = 1.0; // the speed at which we change the brightness. int ledPin = 9; // we use pin 9 for PWM //Variables for controlling patterns int maxLength; int chargeState; //255 is 100 percent int holdChargeState; //255 is 100 percent int pauseTime; //255 is 100 percent //State int globalState = 0; void setup() { // put your setup code here, to run once: pinMode(ledPin, OUTPUT); // set ledPin as an output. Serial.begin(9600); // initiate the Serial monitor so we can use the Serial Plotter to graph our patterns //Sensor pinMode(A0, INPUT); } void loop() { //Read sensor value int sensorValue = analogRead(A0); sensorValue = map(sensorValue, 0, 1023, 0, 100); if (sensorValue > 100) { //Set max value sensorValue = 100; } //Map sensor value to conditions and state if (sensorValue > 80) { //100 globalState = 1; } else if (sensorValue > 55) { //75 globalState = 2; } else if (sensorValue > 45) { //50 globalState = 3; } else if (sensorValue > 20) { //25 globalState = 4; } else { //0 globalState = 10; } //States if (globalState == 0) { // 75 percent //Define variables maxLength = 50; chargeState = 0; //255 is 100 percent holdChargeState = 0; //255 is 100 percent pauseTime = 0; //255 is 100 percent compose2(); //Composing function delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); //store the current time since the program started } else if (globalState == 1) { // 100 //Define variables maxLength = 100; chargeState = 255; //255 is 100 percent holdChargeState = 1000; //255 is 100 percent pauseTime = 1000; //255 is 100 percent compose2(); //Composing function delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); //store the current time since the program started } else if (globalState == 2) { // 75 //Define variables maxLength = 100; chargeState = 130; //255 is 100 percent holdChargeState = 1200; //255 is 100 percent pauseTime = 1000; //255 is 100 percent compose(); //Composing function delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); //store the current time since the program started } else if (globalState == 3) { // 50 //Define variables maxLength = 100; chargeState = 60; //255 is 100 percent holdChargeState = 800; //255 is 100 percent pauseTime = 1000; //255 is 100 percent compose(); //Composing function delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); //store the current time since the program started } else if (globalState == 4) { //25 //Define variables maxLength = 100; chargeState = 15; //255 is 100 percent holdChargeState = 400; //255 is 100 percent pauseTime = 1000; //255 is 100 percent compose(); //Composing function delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); //store the current time since the program started } else if (globalState == 5) { // 75 globalState = 0; } else if (globalState == 10) { // 75 globalState = 0; delay(10); analogWrite(ledPin, brightness); currentMillis = millis(); } } void compose() { switch (ledState){ case START: plot("START", brightness); brightness = 255; if (currentMillis - startMillis >= maxLength){ changeState(DECREASE); } break; case INCREASE: //brightness = increase_brightness(brightness, 18); brightness = expInc_brightness(brightness, 20); plot("INCREASING", brightness); if (brightness > 250){ //ledState = WAVE; changeState(OFF); } break; case DECREASE: //brightness = decrease_brightness(brightness, 20); brightness = expDec_brightness(brightness, maxLength/10); plot("DECREASING", brightness); if (brightness <= chargeState){ changeState(OFF2); } break; case INCREASEAGAIN: brightness = increase_brightness(brightness, 20); plot("INCREASING", brightness); if (brightness >= 130){ //ledState = WAVE; changeState(OFF); } break; case WAVE: plot("WAVE", brightness); brightness = 180; brightness = sinewave(1000,256,0); // you can tweak the parameters of the sinewave analogWrite(ledPin, brightness); if (currentMillis - startMillis >= 5000){ //change state after 5 secs by comparing the time elapsed since we last change state changeState(START); } break; case STAY: plot("STAY", brightness); brightness = brightness; break; case ON: plot("ON", brightness); brightness = 255; break; case OFF: plot("OFF", brightness); brightness = 0; if (currentMillis - startMillis >= pauseTime){ changeState(START); //globalState++; } break; case OFF2: plot("OFF", brightness); brightness = chargeState; if (currentMillis - startMillis >= holdChargeState){ changeState(FADEOUT); } break; case FADEOUT: //brightness = decrease_brightness(brightness, 20); brightness = expDec_brightness(brightness, maxLength/5);; plot("DECREASING", brightness); if (brightness <= 0){ changeState(OFF); } break; } } void compose2() { switch (ledState){ case INCREASE: brightness = increase_brightness(brightness, 5); //brightness = expInc_brightness(brightness, 20); plot("INCREASING", brightness); if (brightness > 250){ //ledState = WAVE; changeState(DECREASE); } break; case DECREASE: brightness = decrease_brightness(brightness, 20); //brightness = expDec_brightness(brightness, maxLength/10); plot("DECREASING", brightness); if (brightness <= 0){ changeState(INCREASE); } break; } } //Helper functions void changeState(ledStates newState){ // call to change state, will keep track of time since last state startMillis = millis(); ledState = newState; } void plot(char *state, int brightness){ // use this function to plot a graph. // it will normalize the auto-scaling plotter Serial.print(state); Serial.print(", "); Serial.print(brightness); Serial.println(", 0, 300"); } int increase_brightness (int brightness, float velocity){ return brightness = brightness + 1 * velocity; } int expInc_brightness (int brightness, float velocity){ int output = brightness + brightness/velocity + 1; if (output >= 255) { return 255; } else { return output; } } int decrease_brightness (int brightness, float velocity){ int output = brightness = brightness - 1 * velocity; if (brightness > 0) { return output; } else { return 0; } } int expDec_brightness (int brightness, float velocity){ int output = brightness = brightness - brightness/velocity - 1; if (brightness > 0) { return output; } else { return 0; } } int sinewave(float duration, float amplitude, int offset){ // Generate a sine oscillation, return a number. // In case you are using this for analogWrite, make sure the amplitude does not exceed 256 float period = millis()/duration; // Duration in ms determines the wavelength. float midpoint = amplitude / 2; // set the midpoint of the wave at half the amplitude so there are no negative numbers int value = midpoint + midpoint * sin ( period * 2.0 * PI ); value = value + offset; //offset allows you to move the wave up and down on the Y-axis. Should not exceed the value of amplitude to prevent clipping. return value; } int halSine(float duration, float amplitude, int offset){ // Generate a sine oscillation, return a number. // In case you are using this for analogWrite, make sure the amplitude does not exceed 256 float period = millis()/duration; // Duration in ms determines the wavelength. float midpoint = amplitude / 2; // set the midpoint of the wave at half the amplitude so there are no negative numbers int value = midpoint + midpoint * sin ( period * 2.0 * PI ); value = value + offset; //offset allows you to move the wave up and down on the Y-axis. Should not exceed the value of amplitude to prevent clipping. return value; }
[ "60586489+CaptainSamSE@users.noreply.github.com" ]
60586489+CaptainSamSE@users.noreply.github.com
1605310e8de55d10bba92dae2df40a2f1eafdec6
91a125fd3209e0f5818d8862debad601bb79bc8a
/Source/Scene.cpp
c11024ad1f58ee889d2b6c9d2da03a52892b5303
[ "MIT" ]
permissive
dimutch833/Rasterizer
61d4224efca51197242e9869e6cb7ac757caada1
76673ec0ab9eb472e1bb097a2b98effe8e5668e6
refs/heads/master
2020-09-23T06:29:14.751961
2019-08-15T10:04:11
2019-08-15T10:04:11
225,428,097
2
0
MIT
2019-12-02T17:10:47
2019-12-02T17:10:46
null
UTF-8
C++
false
false
588
cpp
#include "Scene.h" #include "Maths.h" Scene::Scene() { BuildScene(); } std::vector<Object>& Scene::GetObjects() { return objects; } void Scene::AddObject(Object& object) { objects.push_back(std::move(object)); } void Scene::Update(float dt) { for (Object& object : objects) { //object.SetPosition(Vector3f(3.0f * sin(timer.GetTotal()), 0.0f, 0.0f)); object.Rotate(Vector3f(0.f, 15.0f * dt, 0.f)); } } Camera& Scene::GetCamera() { return camera; } void Scene::BuildScene() { camera.SetTransform(Transform(Vector3f(0.0f, 0.5f, 0.0f), Vector3f(-10.0f, 0.0f, 0.0f))); }
[ "trantr.be@gmail.com" ]
trantr.be@gmail.com
8455ce9dc2f56f8d9ce3c65eebfab607018f40d5
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/ash/wm/always_on_top_controller.h
c899dda0a961c1ae13686a3c5b434c196275e664
[ "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
1,177
h
// Copyright (c) 2012 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 ASH_WM_ALWAYS_ON_TOP_CONTROLLER_H_ #define ASH_WM_ALWAYS_ON_TOP_CONTROLLER_H_ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "ui/aura/window_observer.h" namespace aura { class Window; } namespace ash { class AlwaysOnTopController : public aura::WindowObserver { public: AlwaysOnTopController(); virtual ~AlwaysOnTopController(); void SetAlwaysOnTopContainer(aura::Window* always_on_top_container); aura::Window* GetContainer(aura::Window* window) const; private: virtual void OnWindowAdded(aura::Window* child) OVERRIDE; virtual void OnWillRemoveWindow(aura::Window* child) OVERRIDE; virtual void OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) OVERRIDE; virtual void OnWindowDestroyed(aura::Window* window) OVERRIDE; aura::Window* always_on_top_container_; DISALLOW_COPY_AND_ASSIGN(AlwaysOnTopController); }; } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
450e7050b69ddbccbf2484b9d2e4f65e4d6797f5
d6491bb4c5f8b505e3bbc4b517b04646783728be
/analyzer/rootana/src/unit_test/tut.h
12a0e93402437afea40bf71cbb78dddc211cae24
[]
no_license
alcap-org/AlcapDAQ
7abb402c2f7f1c4c97c1d61a88cbd8c1c6e129f3
269f698bd80a6f57314e1497c15b484f15516cce
refs/heads/R15b
2023-05-11T19:28:41.593446
2019-06-21T17:31:22
2019-06-21T17:31:22
19,924,789
9
1
null
2020-03-18T20:41:34
2014-05-19T00:44:07
C
UTF-8
C++
false
false
22,496
h
#ifndef TUT_H_GUARD #define TUT_H_GUARD #include <iostream> #include <map> #include <vector> #include <string> #include <sstream> #include <stdexcept> #include <typeinfo> #if defined(TUT_USE_SEH) #include <windows.h> #include <winbase.h> #endif /** * Template Unit Tests Framework for C++. * http://tut.dozen.ru * * @author dozen, tut@dozen.ru */ namespace tut { /** * Exception to be throwed when attempted to execute * missed test by number. */ struct no_such_test : public std::logic_error { no_such_test() : std::logic_error("no such test"){}; }; /** * No such test and passed test number is higher than * any test number in current group. Used in one-by-one * test running when upper bound is not known. */ struct beyond_last_test : public no_such_test { beyond_last_test(){}; }; /** * Group not found exception. */ struct no_such_group : public std::logic_error { no_such_group(const std::string& grp) : std::logic_error(grp){}; }; /** * Internal exception to be throwed when * no more tests left in group or journal. */ struct no_more_tests { no_more_tests(){}; }; /** * Internal exception to be throwed when * test constructor has failed. */ struct bad_ctor : public std::logic_error { bad_ctor(const std::string& msg) : std::logic_error(msg){}; }; /** * Exception to be throwed when ensure() fails or fail() called. */ class failure : public std::logic_error { public: failure(const std::string& msg) : std::logic_error(msg){}; }; /** * Exception to be throwed when test desctructor throwed an exception. */ class warning : public std::logic_error { public: warning(const std::string& msg) : std::logic_error(msg){}; }; /** * Exception to be throwed when test issued SEH (Win32) */ class seh : public std::logic_error { public: seh(const std::string& msg) : std::logic_error(msg){}; }; /** * Return type of runned test/test group. * * For test: contains result of test and, possible, message * for failure or exception. */ struct test_result { /** * Test group name. */ std::string group; /** * Test number in group. */ int test; /** * ok - test finished successfully * fail - test failed with ensure() or fail() methods * ex - test throwed an exceptions * warn - test finished successfully, but test destructor throwed * term - test forced test application to terminate abnormally */ typedef enum { ok, fail, ex, warn, term, ex_ctor } result_type; result_type result; /** * Exception message for failed test. */ std::string message; std::string exception_typeid; /** * Default constructor. */ test_result() : test(0),result(ok) { } /** * Constructor. */ test_result( const std::string& grp,int pos,result_type res) : group(grp),test(pos),result(res) { } /** * Constructor with exception. */ test_result( const std::string& grp,int pos, result_type res, const std::exception& ex) : group(grp),test(pos),result(res), message(ex.what()),exception_typeid(typeid(ex).name()) { } }; /** * Interface. * Test group operations. */ struct group_base { virtual ~group_base(){}; // Finalization for group. virtual void group_completed() = 0; // execute tests iteratively virtual void rewind() = 0; virtual test_result run_next() = 0; // execute one test virtual test_result run_test(int n) = 0; }; /** * Test runner callback interface. * Can be implemented by caller to update * tests results in real-time. User can implement * any of callback methods, and leave unused * in default implementation. */ struct callback { /** * Virtual destructor is a must for subclassed types. */ virtual ~callback(){}; /** * Called when new test run started. */ virtual void run_started(){}; /** * Called when a test finished. * @param tr Test results. */ virtual void test_completed(const test_result& /*tr*/){}; /** * Called when all tests in run completed. */ virtual void run_completed(){}; }; /** * Typedef for runner::list_groups() */ typedef std::vector<std::string> groupnames; /** * Test runner. */ class test_runner { protected: typedef std::map<std::string,group_base*> groups; typedef groups::iterator iterator; typedef groups::const_iterator const_iterator; groups groups_; callback default_callback_; callback* callback_; public: /** * Constructor */ test_runner() : callback_(&default_callback_) { } /** * Stores another group for getting by name. */ void register_group(const std::string& name,group_base* gr) { if( gr == 0 ) { throw std::invalid_argument("group shall be non-null"); } groups::iterator found = groups_.find(name); if( found != groups_.end() ) { std::string msg("attempt to add already existent group "+name); // this exception terminates application so we use cerr also std::cerr << msg << std::endl; throw std::logic_error(msg); } groups_[name] = gr; } /** * Stores callback object. */ void set_callback(callback* cb) { callback_ = cb==0? &default_callback_:cb; } /** * Returns callback object. */ callback& get_callback() const { return *callback_; } /** * Returns list of known test groups. */ const groupnames list_groups() const { groupnames ret; const_iterator i = groups_.begin(); const_iterator e = groups_.end(); while( i != e ) { ret.push_back(i->first); ++i; } return ret; } /** * Runs all tests in all groups. * @param callback Callback object if exists; null otherwise */ void run_tests() const { callback_->run_started(); const_iterator i = groups_.begin(); const_iterator e = groups_.end(); while( i != e ) { try { run_all_tests_in_group_(i); } catch( const no_more_tests& ) { // ok i->second->group_completed(); } ++i; } callback_->run_completed(); } /** * Runs all tests in specified group. */ void run_tests(const std::string& group_name) const { callback_->run_started(); const_iterator i = groups_.find(group_name); if( i == groups_.end() ) { throw no_such_group(group_name); } try { run_all_tests_in_group_(i); } catch( const no_more_tests& ) { // ok i->second->group_completed(); } callback_->run_completed(); } /** * Runs one test in specified group. */ test_result run_test(const std::string& group_name,int n) const { callback_->run_started(); const_iterator i = groups_.find(group_name); if( i == groups_.end() ) { throw no_such_group(group_name); } try { test_result tr = i->second->run_test(n); callback_->test_completed(tr); i->second->group_completed(); callback_->run_completed(); return tr; } catch( const beyond_last_test& ) { callback_->run_completed(); throw; } catch( const no_such_test& ) { callback_->run_completed(); throw; } } private: void run_all_tests_in_group_(const_iterator i) const { i->second->rewind(); for( ;; ) { test_result tr = i->second->run_next(); callback_->test_completed(tr); if( tr.result == test_result::ex_ctor ) { throw no_more_tests(); } } } }; /** * Singleton for test_runner implementation. * Instance with name runner_singleton shall be implemented * by user. */ class test_runner_singleton { public: static test_runner& get() { static test_runner tr; return tr; } }; extern test_runner_singleton runner; /** * Test object. Contains data test run upon and default test method * implementation. Inherited from Data to allow tests to * access test data as members. */ template <class Data> class test_object : public Data { public: /** * Default constructor */ test_object(){}; /** * The flag is set to true by default (dummy) test. * Used to detect usused test numbers and avoid unnecessary * test object creation which may be time-consuming depending * on operations described in Data::Data() and Data::~Data(). * TODO: replace with throwing special exception from default test. */ bool called_method_was_a_dummy_test_; /** * Default do-nothing test. */ template <int n> void test() { called_method_was_a_dummy_test_ = true; } }; namespace { /** * Tests provided condition. * Throws if false. */ void ensure(bool cond) { if( !cond ) throw failure(""); } /** * Tests provided condition. * Throws if false. */ template<typename T> void ensure(const T msg,bool cond) { if( !cond ) throw failure(msg); } /** * Tests two objects for being equal. * Throws if false. * * NB: both T and Q must have operator << defined somewhere, or * client code will not compile at all! */ template <class T,class Q> void ensure_equals(const char* msg,const Q& actual,const T& expected) { if( expected != actual ) { std::stringstream ss; ss << (msg?msg:"") << (msg?": ":"") << "expected " << expected << " actual " << actual; throw failure(ss.str().c_str()); } } template <class T,class Q> void ensure_equals(const Q& actual,const T& expected) { ensure_equals<>(0,actual,expected); } /** * Tests first object to be less than than second. * Throws if false. * * NB: both T and Q must have operator << defined somewhere, or * client code will not compile at all! */ template <class T,class Q> void ensure_lessthan(const char* msg,const Q& lesser,const T& greater) { if ( ! (lesser<greater) ) { std::stringstream ss; ss << (msg?msg:"") << (msg?": ":"") << "expected " << lesser << " < " << greater; throw failure(ss.str().c_str()); } } template <class T,class Q> void ensure_lessthan(const Q& lesser,const T& greater) { ensure_lessthan<>(0,lesser,greater); } /** * Tests first object to be greater than second. * Throws if false. * * NB: both T and Q must have operator << defined somewhere, or * client code will not compile at all! */ template <class T,class Q> void ensure_greaterthan(const char* msg,const Q& greater,const T& lesser) { if ( ! (greater>lesser) ) { std::stringstream ss; ss << (msg?msg:"") << (msg?": ":"") << "expected " << greater << " > " << lesser; throw failure(ss.str().c_str()); } } template <class T,class Q> void ensure_greaterthan(const Q& greater,const T& lesser) { ensure_greaterthan<>(0,greater,lesser); } /** * Tests two objects for being at most in given distance one from another. * Borders are excluded. * Throws if false. * * NB: T must have operator << defined somewhere, or * client code will not compile at all! Also, T shall have * operators + and -, and be comparable. */ template <class T> void ensure_distance(const char* msg,const T& actual,const T& expected,const T& distance) { if( expected-distance >= actual || expected+distance <= actual ) { std::stringstream ss; ss << (msg?msg:"") << (msg?": ":"") << "expected [" << expected-distance << ";" << expected+distance << "] actual " << actual; throw failure(ss.str().c_str()); } } template <class T> void ensure_distance(const T& actual,const T& expected,const T& distance) { ensure_distance<>(0,actual,expected,distance); } /** * Unconditionally fails with message. */ void fail(const char* msg="") { throw failure(msg); } } /** * Walks through test tree and stores address of each * test method in group. Instantiation stops at 0. */ template <class Test,class Group,int n> struct tests_registerer { static void reg(Group& group) { group.reg(n,&Test::template test<n>); tests_registerer<Test,Group,n-1>::reg(group); } }; template<class Test,class Group> struct tests_registerer<Test,Group,0> { static void reg(Group&){}; }; /** * Test group; used to recreate test object instance for * each new test since we have to have reinitialized * Data base class. */ template <class Data,int MaxTestsInGroup = 50> class test_group : public group_base { const char* name_; typedef void (test_object<Data>::*testmethod)(); typedef std::map<int,testmethod> tests; typedef typename tests::iterator tests_iterator; typedef typename tests::const_iterator tests_const_iterator; typedef typename tests::const_reverse_iterator tests_const_reverse_iterator; typedef typename tests::size_type size_type; typedef void (*groupfinalization)(); tests tests_; tests_iterator current_test_; groupfinalization group_finalization_; /** * Exception-in-destructor-safe smart-pointer class. */ template <class T> class safe_holder { T* p_; bool permit_throw_in_dtor; safe_holder(const safe_holder&); safe_holder& operator = (const safe_holder&); public: safe_holder() : p_(0),permit_throw_in_dtor(false) { } ~safe_holder() { release(); } T* operator -> () const { return p_; }; T* get() const { return p_; }; /** * Tell ptr it can throw from destructor. Right way is to * use std::uncaught_exception(), but some compilers lack * correct implementation of the function. */ void permit_throw(){ permit_throw_in_dtor = true; } /** * Specially treats exceptions in test object destructor; * if test itself failed, exceptions in destructor * are ignored; if test was successful and destructor failed, * warning exception throwed. */ void release() { try { if( delete_obj() == false ) { throw warning("destructor of test object raised an SEH exception"); } } catch( const std::exception& ex ) { if( permit_throw_in_dtor ) { std::string msg = "destructor of test object raised exception: "; msg += ex.what(); throw warning(msg); } } catch( ... ) { if( permit_throw_in_dtor ) { throw warning("destructor of test object raised an exception"); } } } /** * Re-init holder to get brand new object. */ void reset() { release(); permit_throw_in_dtor = false; p_ = new T(); } bool delete_obj() { #if defined(TUT_USE_SEH) __try { #endif T* p = p_; p_ = 0; delete p; #if defined(TUT_USE_SEH) } __except(handle_seh_(::GetExceptionCode())) { if( permit_throw_in_dtor ) { return false; } } #endif return true; } }; public: typedef test_object<Data> object; /** * Creates and registers test group with specified name. */ test_group(const char* name, groupfinalization final = NULL) : name_(name), group_finalization_(final) { // register itself runner.get().register_group(name_,this); // register all tests tests_registerer<object,test_group,MaxTestsInGroup>::reg(*this); }; /** * This constructor is used in self-test run only. */ test_group(const char* name, test_runner& another_runner) : name_(name), group_finalization_(NULL) { // register itself another_runner.register_group(name_,this); // register all tests tests_registerer<test_object<Data>, test_group,MaxTestsInGroup>::reg(*this); }; /** * Registers test method under given number. */ void reg(int n,testmethod tm) { tests_[n] = tm; } /** * Reset test position before first test. */ void rewind() { current_test_ = tests_.begin(); } /** * Runs next test. */ test_result run_next() { if( current_test_ == tests_.end() ) { throw no_more_tests(); } // find next user-specialized test safe_holder<object> obj; while( current_test_ != tests_.end() ) { try { return run_test_(current_test_++,obj); } catch( const no_such_test& ) { continue; } } throw no_more_tests(); } /** * Runs one test by position. */ test_result run_test(int n) { // beyond tests is special case to discover upper limit if( tests_.rbegin() == tests_.rend() ) throw beyond_last_test(); if( tests_.rbegin()->first < n ) throw beyond_last_test(); // withing scope; check if given test exists tests_iterator ti = tests_.find(n); if( ti == tests_.end() ) throw no_such_test(); safe_holder<object> obj; return run_test_(ti,obj); } void group_completed() { if (group_finalization_ != NULL) group_finalization_(); } private: /** * VC allows only one exception handling type per function, * so I have to split the method */ test_result run_test_(const tests_iterator& ti,safe_holder<object>& obj) { try { if( run_test_seh_(ti->second,obj) == false ) throw seh("seh"); } catch(const no_such_test&) { throw; } catch(const warning& ex) { // test ok, but destructor failed test_result tr(name_,ti->first,test_result::warn,ex); return tr; } catch(const failure& ex) { // test failed because of ensure() or similar method test_result tr(name_,ti->first,test_result::fail,ex); return tr; } catch(const seh& ex) { // test failed with sigsegv, divide by zero, etc test_result tr(name_,ti->first,test_result::term,ex); return tr; } catch(const bad_ctor& ex) { // test failed because test ctor failed; stop the whole group test_result tr(name_,ti->first,test_result::ex_ctor,ex); return tr; } catch(const std::exception& ex) { // test failed with std::exception test_result tr(name_,ti->first,test_result::ex,ex); return tr; } catch(...) { // test failed with unknown exception test_result tr(name_,ti->first,test_result::ex); return tr; } // test passed test_result tr(name_,ti->first,test_result::ok); return tr; } /** * Runs one under SEH if platform supports it. */ bool run_test_seh_(testmethod tm,safe_holder<object>& obj) { #if defined(TUT_USE_SEH) __try { #endif if( obj.get() == 0 ) { reset_holder_(obj); } obj->called_method_was_a_dummy_test_ = false; #if defined(TUT_USE_SEH) __try { #endif (obj.get()->*tm)(); #if defined(TUT_USE_SEH) } __except(handle_seh_(::GetExceptionCode())) { // throw seh("SEH"); return false; } #endif if( obj->called_method_was_a_dummy_test_ ) { // do not call obj.release(); reuse object throw no_such_test(); } obj.permit_throw(); obj.release(); #if defined(TUT_USE_SEH) } __except(handle_seh_(::GetExceptionCode())) { return false; } #endif return true; } void reset_holder_(safe_holder<object>& obj) { try { obj.reset(); } catch(const std::exception& ex) { throw bad_ctor(ex.what()); } catch(...) { throw bad_ctor("test constructor has generated an exception; group execution is terminated"); } } }; #if defined(TUT_USE_SEH) /** * Decides should we execute handler or ignore SE. */ inline int handle_seh_(DWORD excode) { switch(excode) { case EXCEPTION_ACCESS_VIOLATION: case EXCEPTION_DATATYPE_MISALIGNMENT: case EXCEPTION_BREAKPOINT: case EXCEPTION_SINGLE_STEP: case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: case EXCEPTION_FLT_DENORMAL_OPERAND: case EXCEPTION_FLT_DIVIDE_BY_ZERO: case EXCEPTION_FLT_INEXACT_RESULT: case EXCEPTION_FLT_INVALID_OPERATION: case EXCEPTION_FLT_OVERFLOW: case EXCEPTION_FLT_STACK_CHECK: case EXCEPTION_FLT_UNDERFLOW: case EXCEPTION_INT_DIVIDE_BY_ZERO: case EXCEPTION_INT_OVERFLOW: case EXCEPTION_PRIV_INSTRUCTION: case EXCEPTION_IN_PAGE_ERROR: case EXCEPTION_ILLEGAL_INSTRUCTION: case EXCEPTION_NONCONTINUABLE_EXCEPTION: case EXCEPTION_STACK_OVERFLOW: case EXCEPTION_INVALID_DISPOSITION: case EXCEPTION_GUARD_PAGE: case EXCEPTION_INVALID_HANDLE: return EXCEPTION_EXECUTE_HANDLER; }; return EXCEPTION_CONTINUE_SEARCH; } #endif } #endif
[ "p.litchfield@ucl.ac.uk" ]
p.litchfield@ucl.ac.uk
ff1f7e67dca46faa03f6dedda559bf379ebecc5b
cd5b84e469437b5eea3c44bfcb4eaafc93694d9a
/Code/functions.hpp
d8aef0918d60873eddfb7f771eed145ffec65fdb
[]
no_license
florent-escribe/cplusplus-eval
7534688250ff363d4af3d44923e62902cd79af8e
98fa9ffab2bd243a8ac21e72adb00a282a6ef0e1
refs/heads/master
2022-04-14T04:09:45.562058
2020-04-01T13:30:37
2020-04-01T13:30:37
232,187,376
0
0
null
null
null
null
UTF-8
C++
false
false
2,488
hpp
#include <iostream> using namespace std; // Dans Date.cpp class Date { int day; int month; int year; public : Date (); Date (int d, int m, int y); void print_date (); string write_date (); }; Date text_to_date (string date); //Dans Status.cpp class Status { string tab_stati [5] = {"open", "closed", "in progress", "forgotten long ago", "friendly"}; //ou alors une fonction status valide, dans le genre public : string sta; Status (); Status (string status_in); void print_status (); string write_status (); }; class Priority { //attention, il faudra pouvoir changer sta depuis task, donc soit en public, soit donner l'autorisation string tab_priorities [5] = {"no problem", "think about it", "kinda pressing but ok", "get to work now", "urgent"}; public : string prio; //c'est plus pratique en public pour y accéder facilement, pas besoin de le protéger Priority (string priority_in); //potentiellement inutile Priority (); void print_priority (); string write_priority (); }; class Task { int id; string title; string descr; public : Date date_creation; Date date_end; Priority priority; Status status; int progress; string sub_task; string comments; Task (int id_in, string title_in, string descr_in, Date date_debut = Date(), Date date_fin = Date(), Priority prio = Priority(), Status sta = Status(), int prog = 0, string sub_ta = "", string com = ""); int get_task_id (); string get_title (); string get_descr (); void print_task (); string write (); }; //Dans User_interface : string demanderGeneral (string question); int demanderId (); Date demanderDate (); void print_com (string com); //3 fois la meme chose, c'est juste l'attribut testé qui change. void show_id (int id); void show_priority (Priority prio); void show_status (Status sta); //dans le fichier "fichier_texte.cpp" void write_task (Task task); int get_id (); //donne l'id de la prochaine task Task text_to_task (string text); void change_end_date (int id); void change_priority (int id); void change_status (int id); void change_progress (int id); void change_sub_task (int id); void change_com (int id); void delete_task (int id); bool exist_task (int id); bool est_dedans (int x, int* t, int len);
[ "florent.escribe@gmail.com" ]
florent.escribe@gmail.com
d7eb699fe8d3861c6921217dfb091e021b3caf09
73c9d36fc02fa2f42e2a272c8d2b78a156ff050d
/Code/mqtt_test_1/mqtt_test_1.ino
2eaaba7b2cd7bcce060cf22201ec94f3c6911a3c
[]
no_license
sauravshandilya/i_hack-2018
62013a439eba304b8136e4cf3ce71d0e21c0251f
698ff3ff96073e1f142035c5d9ff9ee57681b4c2
refs/heads/master
2021-05-09T13:59:23.126122
2018-01-27T14:02:44
2018-01-27T14:02:44
119,051,341
0
0
null
null
null
null
UTF-8
C++
false
false
4,259
ino
#include <SPI.h> #include <WiFi.h> #include <PubSubClient.h> #include <Wire.h> #include "Adafruit_TMP006.h" Adafruit_TMP006 tmp006(0x41); // start with a diferent i2c address! #define WIFI_AP "ERTS LAB 304" #define WIFI_PASSWORD "balstre403" #define TOKEN "VU7ITc9VzIqaZDcnv8kE" char thingsboardServer[] = "192.168.0.107"; void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Received message for topic "); Serial.print(topic); Serial.print("with length "); Serial.println(length); Serial.println("Message:"); Serial.write(payload, length); Serial.println(); } WiFiClient wifiClient; PubSubClient client(thingsboardServer, 1883, callback, wifiClient); //SoftwareSerial soft(2, 3); // RX, TX int status = WL_IDLE_STATUS; unsigned long lastSend; void setup() { // initialize serial for debugging Serial.begin(115200); InitWiFi(); //client.setServer(thingsboardServer, 1883 ); lastSend = 0; if (! tmp006.begin()) { Serial.println("No sensor found"); while (1); Serial.println("Temperature Sensor OK"); } } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); } void InitWiFi() { // initialize serial for ESP module //soft.begin(9600); Serial.println("Connecting to AP ..."); // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(WIFI_AP); // Connect to WPA/WPA2 network status = WiFi.begin(WIFI_AP, WIFI_PASSWORD); delay(500); } Serial.println("Connected to AP"); printWifiStatus(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Connecting to Thingsboard node ..."); // Attempt to connect (device_name, access_token, password) if ( client.connect("Temp_sensor_CC3200", TOKEN, NULL) ) { Serial.println( "[DONE]" ); } else { Serial.print( "[FAILED] [ rc = " ); //Serial.print( client.state() ); Serial.println( " : retrying in 5 seconds]" ); // Wait 5 seconds before retrying delay( 5000 ); } } } void getAndSendTemperatureAndHumidityData() { // Grab temperature measurements and print them. float objt = tmp006.readObjTempC(); Serial.print("Object Temperature: "); Serial.print(objt); Serial.println("*C"); Serial.print("Temperature: "); Serial.print(objt); Serial.print(" *C "); String temperature = String(objt); // Just debug messages Serial.print( "Sending temperature and humidity : [" ); Serial.print( temperature ); Serial.print( "," ); //Serial.print( humidity ); Serial.print( "] -> " ); // Prepare a JSON payload string String payload = "{"; payload += "\"temperature\":"; payload += temperature; //payload += ","; //payload += "\"humidity\":"; //payload += humidity; payload += "}"; // Send payload char attributes[100]; payload.toCharArray( attributes, 100 ); client.publish( "v1/devices/me/telemetry", attributes ); Serial.println( attributes ); } void loop() { status = WiFi.status(); if ( status != WL_CONNECTED) { while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(WIFI_AP); // Connect to WPA/WPA2 network status = WiFi.begin(WIFI_AP, WIFI_PASSWORD); delay(500); } Serial.println("Connected to AP"); } if ( !client.connected() ) { reconnect(); } //if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds // getAndSendTemperatureAndHumidityData(); // lastSend = millis(); bool abc = client.subscribe("v1/devices/me/rpc/request/+"); bool rc = client.subscribe("v1/devices/me/attributes"); Serial.println("subscribed"); Serial.println(rc); Serial.println(abc); getAndSendTemperatureAndHumidityData(); delay(1000); //client.loop(); }
[ "sauravs.iitb@gmail.com" ]
sauravs.iitb@gmail.com
8bcf4ce109ed279c2285f4ee541162b8d69770f4
217dc5e7628ffa689134c9001085d272aca5d22d
/copy/Project/Tuffy_Travel_02/tuffytravel.cpp
33133c0760d98acb97358d340bb8e699f07ccbe0
[ "MIT" ]
permissive
markjcasas/CPSC121
167c59cbc654f622eace478d362a555a2a1a0121
5fa87edbc7d9a8d278aea182c34342402454a444
refs/heads/master
2021-06-14T01:12:31.011610
2019-12-22T04:30:18
2019-12-22T04:30:18
254,465,752
0
0
null
2020-04-09T19:55:42
2020-04-09T19:55:41
null
UTF-8
C++
false
false
690
cpp
#include "route.hpp" #include <iostream> int main() { int t; Route r[3]; std::cout << "Welcome to TuffyTravel!" << '\n'; std::cout << '\n'; for (int h = 0; h < 3; h++) { std::cout << "Route "; std::cout << h + 1 << ":" << '\n'; r[h] = create_route(); } std::cout << "Please enter the time you wish to leave: "; std::cin >> t; std::cout << '\n'; Route pick; pick = best_route(r, 3, t); std::cout << "You should probably take the " << pick.name(); std::cout << " that leaves at " << pick.departure_time(); std::cout << " and arrives at " << pick. arrival_time(); std::cout << " which fits your preferred time to leave, " << t << '\n'; return 0; }
[ "zpeskin@csu.fullerton.edu" ]
zpeskin@csu.fullerton.edu
6b3d84f21e10e1122e12c3776c75fb540537b058
fad392b7b1533103a0ddcc18e059fcd2e85c0fda
/build/px4_msgs/rosidl_generator_cpp/px4_msgs/msg/airspeed_wind.hpp
84e2038f0ebc50e5d6ad2025cf41d5a39396d910
[]
no_license
adamdai/px4_ros_com_ros2
bee6ef27559a3a157d10c250a45818a5c75f2eff
bcd7a1bd13c318d69994a64215f256b9ec7ae2bb
refs/heads/master
2023-07-24T18:09:24.817561
2021-08-23T21:47:18
2021-08-23T21:47:18
399,255,215
0
0
null
null
null
null
UTF-8
C++
false
false
345
hpp
// generated from rosidl_generator_cpp/resource/idl.hpp.em // generated code does not contain a copyright notice #ifndef PX4_MSGS__MSG__AIRSPEED_WIND_HPP_ #define PX4_MSGS__MSG__AIRSPEED_WIND_HPP_ #include "px4_msgs/msg/airspeed_wind__struct.hpp" #include "px4_msgs/msg/airspeed_wind__traits.hpp" #endif // PX4_MSGS__MSG__AIRSPEED_WIND_HPP_
[ "adamdai97@gmail.com" ]
adamdai97@gmail.com
a00030d7f0ab1fc371cc89b388666ac328369ff3
2212262b764bd9904bc1cbc9bd6f00a5fa9c1431
/src/AppInfo.h
46958f93ad2e1274d322b9d543f0522643ee3d5f
[]
no_license
tylerreisinger/vulkan_wrapper
5e937b624a2dcedbd44ff1c81e2e12cf613e7cbb
44febb05816bb28efebf277f8f1727c0f4aa6f94
refs/heads/master
2020-03-26T09:59:55.712150
2018-08-14T22:03:25
2018-08-14T22:03:25
144,776,361
0
0
null
null
null
null
UTF-8
C++
false
false
817
h
#ifndef APPINFO_H_ #define APPINFO_H_ #include <vulkan/vulkan.h> #include <string> #include "Version.h" class AppInfo { public: AppInfo(); ~AppInfo() = default; AppInfo(const AppInfo& other) = default; AppInfo(AppInfo&& other) noexcept = default; AppInfo& operator =(const AppInfo& other) = default; AppInfo& operator =(AppInfo&& other) noexcept = default; AppInfo& with_app_name(std::string name); AppInfo& with_engine_name(std::string name); AppInfo& with_app_version(Version version); AppInfo& with_engine_version(Version version); AppInfo& with_vulkan_version(Version version); const VkApplicationInfo& raw_value() const { return m_app_info; } private: VkApplicationInfo m_app_info; std::string m_app_name; std::string m_engine_name; }; #endif
[ "reisinger.tyler@gmail.com" ]
reisinger.tyler@gmail.com
158ab70688da56ddfb10c000552c9b01a95bfcda
88ea7cbd4f302133faa6c59b0596416f551c2735
/SumoBot/QRDs/qrd/qrd2.ino/qrd2.ino.ino
57512b7bc4dccb1c57e80b8378eb2b50011fcb54
[]
no_license
adamaghili/Gojira
7f19faa5f35476362bc4a5111a23dc7b7e28b887
53f116768f0567b129754b1880c6f7800c861590
refs/heads/master
2021-01-23T03:03:56.824929
2017-03-24T07:27:56
2017-03-24T07:27:56
86,042,246
0
0
null
2017-03-24T07:59:07
2017-03-24T07:59:07
null
UTF-8
C++
false
false
1,160
ino
const unsigned int QrdPin0 = A0; const unsigned int QrdPin1 = A1; const unsigned int QrdThreshold1 = 800; const unsigned int QrdThreshold2 = 750; // must change, probs dynamically in a setup routine unsigned int QrdValue0; unsigned int QrdValue1; void setup() { pinMode(QrdPin0, INPUT); pinMode(QrdPin1, INPUT); Serial.begin(9600); Serial.println("+-------------------------------------------+"); Serial.println("| QRD Sensor Readings |"); Serial.println("+-------------------------------------------+"); } void loop() { QrdValue0 = analogRead(QrdPin0); QrdValue1 = analogRead(QrdPin1); Serial.println("Qrd 0"); Serial.println(QrdValue0); if (QrdValue0 < QrdThreshold1) { Serial.println("Qrd0 is reading white!!!"); } else { Serial.print("Qrd0 is reading black!!!"); } Serial.println("Qrd 1"); Serial.println(QrdValue1); if (QrdValue1 < QrdThreshold1) { Serial.println("Qrd1 is reading white!!!"); } else { Serial.print("Qrd1 is reading black!!!"); } Serial.print("\n"); Serial.println("---------------------------------------------"); delay(1000); }
[ "agostd@mcmaster.ca" ]
agostd@mcmaster.ca
1c0164fe123e25a3fd46ec3861e1b52c456e7385
71f88b70aec1c1b3224e18f0c31abf64fb1332bf
/codeFiles/BianYuanDib.h
3ea3bf32c71d87b7e275175724243095b0df76c6
[]
no_license
llllllfff233/VCPictureProcessing
6efc53de8b6b9af2f89f8cb609213b6e1a379739
d6990ab023aebe4b17555972a16690208f08dcb2
refs/heads/master
2021-05-21T00:44:27.666030
2017-11-19T14:04:01
2017-11-19T14:04:01
null
0
0
null
null
null
null
GB18030
C++
false
false
3,368
h
#pragma once class BianYuanDib:public CObject { private: CDib *dib; /*经过平滑后的图像变模糊的根本原因是受到了平均或积分运算,因此可以对其进行逆运算(如微分运算),就可以使图像变得清晰。 用差分运算时图像的第一行或者第一列经常无法求得,可以用旁边的值近似代替。 边缘锐化这里的算子和都是0,而平滑是1. */ public: void GetDib(CDib *dib); void ZongXiang();//进行纵向微分,用差分代替微分,f(i,j)-f(i,j-1),实际上等于(f(i,j)-f(i,j-1))/1 void HengXiang();//进行横向微分,(f(i,j)-f(i-1,j))/1 void ShuangXiang();//双向微分,sqrt(pow(f(i,j)-f(i-1,j),2)+pow(f(i,j)-f(i,j-1),2)) void MenXianRuiHua(byte t);//门限锐化,门限阈值判断基本上不破坏内部,又能增强边缘亮度 void GuDingRuiHua();//固定锐化,反正都是测试函数,就不写那么完善了,给边缘一个固定的灰度值 //可以给边缘固定一个值,也可以给背景固定一个值,这里是边缘 void ErZhiRuiHua();//二值锐化,用一个阈值,梯度大于就255,小于就0 /* 边缘沿边缘走向变化平缓,沿垂直边缘方向变换剧烈,从这个意义上说,提取边缘的算法就是检出符合边缘特性的边缘像素的数学算子。 书上的0度、90度、135度边缘算子等,将所有模板用于像素上输出值最大的点就是改点的边缘方向;如果所有方向都接近0就说明没有边缘;如果所有方向输出值都接近相等,则改点没有可靠的边缘方向。 由于我们不能预知边缘的方向,所以要用不具备空间方向性的算子和具有旋转不变的线性微分算子。 卷积可以简单的看成一个加权求和的过程,模板矩阵叫做卷积核,卷积核中各元素叫卷积系数,卷积行、列必须是奇数,大多数是3x3的;图像的边缘要么忽略,要么复制旁边像素 */ void Robert();//罗伯特算子边缘检测,对噪声敏感,边缘定位准;利用两个对角进行差分,形状是X,旋转也是一样的,具有旋转不变性 LPBYTE Templat(int temph,int tempw,int tempx,int tempy,float main,float* fpArray);//最后一个是模板系数 //Sobel算子,水平+垂直=十字形的,或者X行的旋转都是不变的,具有旋转不变性 // void Sobel();//Sobel算子,效果会亮很多,具有一定的噪声抑制能力,用于提取边缘,下面减上面,左边减右边,这里只是实现了水平和垂直,取水平或者竖直中像素值较大的,并没有按照前面理论说的要取微分 void Prewitt();//跟Sobel一样,只是算子的权重不一样,输出水平和垂直边缘检测中的最大值 void Krisch();//8个算子,代表8个有向方向,从指向正上,顺时针旋转,8个方向输出较大值。 /*边缘处图像一阶偏导数取得最大值,二阶偏导数会通过零点(由正到负或者由负到正)。 旋转前后的偏导数的平方和具有旋转不变性,看看书就会动。 高斯拉普拉斯将高斯滤波器和拉普拉斯锐化滤波器结合起来,先平滑噪声,再进行边缘检测,对孤立点敏感。本来是一个3x3的滤波,这里采用的是5x5的 */ void Guasslaplacian();//高斯拉普拉斯算子, };
[ "noreply@github.com" ]
noreply@github.com
476f84721cd593407c3ed554aa0d2e2407081110
142fa62460b4929a08ee2cc0c9244f00bfd96df4
/CppCodes/CodeForces/E/166E-again.cpp
0591d675ac7fe188cad01dd2807c90dc37a76823
[ "MIT" ]
permissive
yashaggarwal03/coding-creed-origins
e0114118befa6e5129596e0f072daa7ed0c25d24
391a517bc84e0b7af301547e3bd3f7f46fb7ac4a
refs/heads/dev
2022-12-28T02:07:19.382336
2020-10-07T16:49:44
2020-10-07T16:49:44
302,100,331
0
0
MIT
2020-10-07T16:49:46
2020-10-07T16:45:22
null
UTF-8
C++
false
false
796
cpp
#include <bits/stdc++.h> using namespace std; #define si(x) scanf("%d",&x) #define sf(x) scanf("%f",&x) #define pi(x) printf("%d\n",x) #define pf(x) printf("%.4f\n",x) #define ll long long int #define sll(x) scanf("%I64d",&x); #define pll(x) printf("%-I64d\n",x); // ll *a; int main(int argc, char const *argv[]) { /* code */ /* Soln soln */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin>>n; ll a[3]; a[0] = 1; a[1] = 0; a[2] = 0; int i=2; for(int j=2; j<=n; j++){ a[i] = 2*a[i-1]+3*a[i-2]; a[i] = a[i]%1000000007; a[i-2] = a[i-1]; a[i-1] = a[i]; } cout<<a[2]<<"\n"; // if(!a)delete[] a; return 0; }
[ "fahim.farhan@outlook.com" ]
fahim.farhan@outlook.com
f356394ec5f5ba17bad466141f7f62c6b69f61d2
c88ef4c2dbd1f36fd6cc76b9daf60f971ce50080
/CH5 String/5.7/main.cc
7dca90882f2934485c4ce5a7022899e0f8512005
[]
no_license
Z-maple/CodeInterviewGuide
97cf7c4430bcb4fb69d6cb19510d702b85b2cdfd
7c531cb9d728849b43547de33d751263fe22c562
refs/heads/master
2022-02-13T23:46:35.916994
2019-08-26T16:13:45
2019-08-26T16:13:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,310
cc
///字符串的统计字符串 #include <iostream> #include <string> using namespace std; string num2str(int i){ string ret; while(i){ int lsb = i%10; ret = (char)(lsb + '0') + ret; i /= 10; } return ret; } string func(string &s){ string ret; if(s.size() == 0) return ret; char prev = s[0]; int num = 1; for(int i = 1; i < s.size(); ++i){ if(s[i] == prev){ num++; } else{ ret += prev; ret += '_'; ret += num2str(num); ret += '_'; prev = s[i]; num = 1; } } if(num != 0){ ret += prev; ret += '_'; ret += num2str(num); } return ret; } char func2(string &s, int n){ char prev; string ret; int i = 0; int num = 0; while(i < s.size()){ int tmp = 0; prev = s[i]; i += 2; while(i < s.size() && s[i] >= '0' && s[i] <= '9'){ tmp *= 10; tmp += (s[i] - '0'); ++i; } num += tmp; ++i; if(num >= n) return prev; } } int main(){ string s("aaabbadddffc"); string ret = func(s); string s2("a_1_b_100"); char ret2 = func2(s2, 50); cout<<ret2<<endl; }
[ "gaomingye2010@163.com" ]
gaomingye2010@163.com
3793ca9c24b951772e4612c9d1bf243367eec8f4
0eb3b07d641f4310ce7e4fdf92f895b7c91ea932
/EGame/src/EGameManager.cpp
1ba616416cb87e4a456722d47f026baddfb2f7aa
[]
no_license
PiangGG/E3D
fb52822b665c53c44203e0324c1af06ab5f9306c
4e78d69299c6469e6ab9377b1e540b323385cbf1
refs/heads/master
2023-01-19T06:57:52.965787
2020-11-22T07:14:10
2020-11-22T07:14:10
312,483,532
0
0
null
null
null
null
GB18030
C++
false
false
11,206
cpp
#include "EGameManager.h" #include "EBullet.h" #include "ETank.h" #include "EPlayerController.h" #include "ESceneManager.h" #include "EAITank.h" namespace E3D { const EString Bullet_Ball = "BallBullet.mesh"; const EString Bullet_Rocket = "RocketBullet.mesh"; const EVector3D InitPosition(-20.0f, 1.0f, 15.0f); const EVector3D RandomPos[3] = { EVector3D(10, 1.5f, 10), EVector3D(45, 1.5f, -5), EVector3D(-20, 1.5f, 45)}; //-------------------------------------------------------------------------- EGameManager::EGameManager(ESceneManager *scene) : mScene(scene), mBlockSize(0.0f), mX(0), mZ(0), mTerrainMesh(NULL), mCurrentEnemyNumber(0), mMaxEnemyNumber(0), mVisibleEnemyNumber(3) { mMainPlayer = new EPlayerController(this); mMainPlayer->setPosition(InitPosition); EBullet *bullet = new EBullet(NULL, "RocketBullet.mesh", this); bullet->setVisible(false); bullet = new EBullet(NULL, "BallBullet.mesh", this); bullet->setVisible(false); } //-------------------------------------------------------------------------- EGameManager::~EGameManager() { SafeDelete(mMainPlayer); for (BulletIter itr = mBullets.begin(); itr != mBullets.end(); ++itr) SafeDelete(*itr); for (TankIter itr = mTanks.begin(); itr != mTanks.end(); ++itr) SafeDelete(*itr); mBullets.clear(); mTanks.clear(); } //-------------------------------------------------------------------------- void EGameManager::startGame(EInt maxEnemyNumber) { // 清理当前的子弹和坦克 for(BulletIter itr = mBullets.begin(); itr != mBullets.end(); ++itr) (*itr)->mCurrentLive = (*itr)->mMaxLive + 1; for (TankIter itr = mTanks.begin(); itr != mTanks.end(); ++itr) (*itr)->mCurrentLive = (*itr)->mMaxLive + 1; mMaxEnemyNumber = maxEnemyNumber; mCurrentEnemyNumber = 0; } //-------------------------------------------------------------------------- EBool EGameManager::finishGame() const { return mCurrentEnemyNumber == mMaxEnemyNumber; } //-------------------------------------------------------------------------- EBullet* EGameManager::createBullet(ETank *owner) { EString meshname = (owner->getBulletTye() == BULLET_ROCKET ? Bullet_Rocket : Bullet_Ball); EBullet *bullet = new EBullet(owner, meshname, this); if (meshname == Bullet_Ball) bullet->setScale(EVector3D(1.5f, 1.5f, 1.5f)); mBullets.push_back(bullet); return bullet; } //-------------------------------------------------------------------------- void EGameManager::destroyBullet(EBullet *bullet) { // 这里直接设置当前生命值比最大生命值大, update的时候自动删除 bullet->mCurrentLive = bullet->mMaxLive + 1; } //-------------------------------------------------------------------------- ETank *EGameManager::createAITank(const EVector3D &pos) { static EInt ID = 0; EString name = "AI#" + IntToString(ID++); ETank *tank = new EAITank(name, "Tank1", this); tank->setPosition(pos); mTanks.push_back(tank); return tank; } //-------------------------------------------------------------------------- void EGameManager::update() { if (isGameBegin() && !finishGame()) { // 不足最大显示那么创建 if ((EInt)mTanks.size() < mVisibleEnemyNumber) { EInt curNum = (EInt)mTanks.size(); for (EInt i = 0; i < mVisibleEnemyNumber - curNum; i++) { if(mCurrentEnemyNumber + (EInt)mTanks.size() < mMaxEnemyNumber) createAITank(RandomPos[RandomInt(0, 2)]); } } // 更新子弹, 如果子弹存活, 那么就更新, 否则将其删除 for (TankIter itr = mTanks.begin(); itr != mTanks.end();) { if ((*itr)->isAlive()) { (*itr)->update(); ++itr; } else { mCurrentEnemyNumber++; SafeDelete(*itr); mTanks.erase(itr++); } } } // 更新子弹, 如果子弹存活, 那么就更新, 否则将其删除 for (BulletIter itr = mBullets.begin(); itr != mBullets.end();) { if ((*itr)->isAlive()) { (*itr)->update(); ++itr; } else { SafeDelete(*itr); mBullets.erase(itr++); } } mMainPlayer->update(); } void EGameManager::changeMap(const EString& mapName) { // 删除场景 SafeDelete(mMainPlayer); for (BulletIter itr = mBullets.begin(); itr != mBullets.end(); ++itr) SafeDelete(*itr); for (TankIter itr = mTanks.begin(); itr != mTanks.end(); ++itr) SafeDelete(*itr); mBullets.clear(); mTanks.clear(); mCollisionValue.clear(); mCollisionMeshs.clear(); // 敌人置于0 mCurrentEnemyNumber = 0; // 清理实际的模型 mScene->clearMesh(); // 新建角色 mMainPlayer = new EPlayerController(this); mMainPlayer->setPosition(InitPosition); // 加载场景 loadMap(mapName); } //-------------------------------------------------------------------------- EString getBlock(const EString &line, char ltip, char rtip) { EInt beg = line.find(ltip); EInt end = line.rfind(rtip); return line.substr(beg + 1, end - beg - 1); } EVector3D getPos(const EString &line) { // <Position X="-49.649979" Y="4.247236" Z="-5.005510" /> EInt xb = line.find("X"); EInt yb = line.find("Y"); EInt zb = line.find("Z"); EInt end = line.find("/"); EString xs = line.substr(xb + 3, yb - 5 - xb); EString ys = line.substr(yb + 3, zb - 5 - yb); EString zs = line.substr(zb + 3, end - zb - 5); return EVector3D(StringToFloat(xs), StringToFloat(ys), StringToFloat(zs)); } void getXZ(const EString& line, EInt &x, EInt &z, EFloat &blockSize) { // <Grid X="15" Z="14" Size="10" /> EInt xb = line.find("X"); EInt zb = line.find("Z"); EInt sb = line.find("Size"); EInt end = line.find("/"); EString xs = line.substr(xb + 3, zb - 5 - xb); EString zs = line.substr(zb + 3, sb - 5 - zb); EString ss = line.substr(sb + 6, end - sb - 8); x = StringToFloat(xs); z = StringToFloat(zs); blockSize = StringToFloat(ss); } void getValue(const EString& line, EInt &x, EInt &z, EInt &value) { // <Map X="6" Z="2" Value="0" /> EInt xb = line.find("X"); EInt zb = line.find("Z"); EInt sb = line.find("Value"); EInt end = line.find("/"); EString xs = line.substr(xb + 3, zb - 5 - xb); EString zs = line.substr(zb + 3, sb - 5 - zb); EString ss = line.substr(sb + 7, end - sb - 9); x = StringToFloat(xs); z = StringToFloat(zs); value = StringToFloat(ss); } //-------------------------------------------------------------------------- EBool EGameManager::loadMap(const EString& mapName) { mCurMap = mapName; Log("Loading map #%s...", mapName.c_str()); mCollisionValue.clear(); mCollisionMeshs.clear(); std::ifstream in; in.open(GetPath(mapName).c_str()); if (in.bad()) { in.close(); return false; } char line[256]; while (in.good()) { EString info; in.getline(line, 256); info = Trim(line); int beg = 0, end = -1; if (info.find("Config") != -1) { // <Config Name="map001"> EString mapName = getBlock(info, '\"', '\"'); // <Mesh>Terr_Forest_1</Mesh> in.getline(line, 256); info = Trim(line); EString meshName = getBlock(info, '>', '<') + ".mesh"; // <Grid X="15" Z="14" Size="10" /> in.getline(line, 256); getXZ(line, mX, mZ, mBlockSize); mXL = mX * mBlockSize; mZL = mZ * mBlockSize; mHXL = mXL / 2.0f; mHZL = mZL / 2.0f; // 初始化碰撞位置数据 for (EInt i = 0; i <= mZ; i++) { mCollisionValue.push_back(std::vector<EInt>(mX + 1, 0)); mCollisionMeshs.push_back(std::vector<EMesh*>(mX + 1, 0)); } // </Config> in.getline(line, 256); mTerrainMesh = mScene->createMesh(mapName, meshName); mTerrainMesh->setCullFlag(false); } in.getline(line, 256); info = Trim(line); if (info.find("Nodes") != -1) { in.getline(line, 256); info = Trim(line); while (info.find("Node") != -1) { int i = info.find("</Nodes>"); if (i != -1) break; // <Node Name="Tree_3#120"> EString nodeName = getBlock(info, '\"', '\"'); // <Mesh>Tree_3</Mesh> in.getline(line, 256); info = Trim(line); EString meshName = getBlock(info, '>', '<') + ".mesh"; // <Position X="-49.649979" Y="4.247236" Z="-5.005510" /> in.getline(line, 256); info = Trim(line); EVector3D pos = getPos(info); EMesh *object = mScene->createMesh(nodeName, meshName); object->setPosition(pos); // <Map X="6" Z="2" Value="0" /> in.getline(line, 256); EInt x, z, value; getValue(line, x, z, value); if (value >= mCollisionValue[z][x]) { mCollisionValue[z][x] = value; mCollisionMeshs[z][x] = object; } // </Node> in.getline(line, 256); in.getline(line, 256); info = Trim(line); } } } in.close(); Log("Map Load Successed!"); return true; } //-------------------------------------------------------------------------- EBool EGameManager::canGo(EFloat x, EFloat z) { // 超出边界 if (x <= -mHXL || x >= mHXL || z <= -mHZL || z >= mHZL) return false; EInt xoff = (EInt)((x + mHXL) / mBlockSize); EInt zoff = (EInt)((z + mHZL) / mBlockSize); if (mCollisionValue[xoff][zoff] > 0) return false; return true; } //-------------------------------------------------------------------------- void EGameManager::getLogicXZ(EFloat x, EFloat z, EInt &outX, EInt &outZ) { // 超出边界 if (x <= -mHXL || x >= mHXL || z <= -mHZL || z >= mHZL) { outX = outZ = -1; } else { outX = (EInt)((x + mHXL) / mBlockSize); outZ = (EInt)((z + mHZL) / mBlockSize); } } //-------------------------------------------------------------------------- EMesh* EGameManager::checkObject(EFloat x, EFloat z) { // 超出边界 if (x <= -mHXL || x >= mHXL || z <= -mHZL || z >= mHZL) return mTerrainMesh; EInt xoff = (EInt)((x + mHXL) / mBlockSize); EInt zoff = (EInt)((z + mHZL) / mBlockSize); if (mCollisionValue[xoff][zoff] > 0) return mCollisionMeshs[xoff][zoff]; else return NULL; } //-------------------------------------------------------------------------- ETank* EGameManager::checkTank(EFloat x, EFloat y, EFloat z) { // 首先检查主角 if (mMainPlayer->getTank()->intersect(EVector3D(x, y, z))) return mMainPlayer->getTank(); for (TankIter itr = mTanks.begin(); itr != mTanks.end(); ++itr) { if ((*itr)->intersect(EVector3D(x, y, z))) return *itr; } return NULL; } //-------------------------------------------------------------------------- void EGameManager::playSound(SOUND_YYPE sound, EBool loop) { const static EString Background = "Background.wav"; const static EString Fire = "Fire.wav"; const static EString Explode = "Explosion.wav"; EInt flag = /*SND_NOSTOP | */SND_ASYNC; if (loop) flag |= SND_LOOP; EString soundName = Background; switch(sound) { case SOUND_BACKGROUND: soundName = Background; break; case SOUND_FIRE: soundName = Fire; break; case SOUND_EXPLODE: soundName = Explode; break; }; ::sndPlaySound(GetPath(soundName).c_str(), flag); } //-------------------------------------------------------------------------- }
[ "974805475@qq.com" ]
974805475@qq.com
72572b4e5aadeb39d2ae110cef81f40cb04f2379
5f4d46c8034f71657cb02b474ec4b6fad3d49012
/C++/try/第一次练习/buAC/buAC/源.cpp
0a48e9d8ce0a63649ec7cd610ad0c3ad34b7054d
[]
no_license
GaryCao97/CodeWarehouse
516c3da660070a574be40e34e290345c54fef692
d6290d0f115c8dd350844bfe697abc07998a9f4c
refs/heads/master
2020-03-31T19:52:02.786213
2018-10-12T08:29:46
2018-10-12T08:29:46
152,515,319
0
1
null
null
null
null
UTF-8
C++
false
false
783
cpp
#include<iostream> using namespace std; const int len = 100; int proSum(int startPro[len], int endPro[len], int length, int startTime, int theSum = 0){ int maxEnd = 0; for (int y = 0; y < length; y++){ maxEnd = maxEnd>endPro[y] ? maxEnd : endPro[y]; } start: int flag = 0; for (int x = 0; x < length; x++){ if (startPro[x] == startTime){ flag = x; } } if (flag != 0){ theSum++; startTime = endPro[flag]; goto start; } else if (flag == 0 && startTime < maxEnd){ startTime++; goto start; } return theSum; } int main(){ int n; int timeStart[len], timeEnd[len]; scanf_s("%d", &n); while (n != 0){ for (int i = 0; i < n; i++) scanf_s("%d %d", &timeStart[i], &timeEnd[i]); printf_s("%d", proSum(timeStart, timeEnd, n, 0)); scanf_s("%d", &n); } }
[ "gary_cao97@163.com" ]
gary_cao97@163.com
7dde7bfefb51fcc6b0375f5c79a7f4fd2713bbb8
7d5f7991bddc05ddea44f39351a3a8beb92caa82
/Membre.h
a6ac57899257998cc1cbd64af915aefe677d6465
[]
no_license
Julien29121998/BE-Bestioles-CPP
527ad6d71c2f1c6ec553d52e86cdb3801198d0ef
50c90100b717644a1ce243922f80f12489238ca6
refs/heads/master
2023-01-14T10:17:14.984981
2020-11-18T17:53:42
2020-11-18T17:53:42
261,451,940
0
0
null
null
null
null
UTF-8
C++
false
false
1,957
h
#ifndef _MEMBRE_H_ #define _MEMBRE_H_ #include "UImg.h" #include "DBestiole.h" #include <iostream> class Milieu; using namespace std; /**Un membre de Bestiole: Application de Décorateur*/ class Membre: public DBestiole { private : DBestiole* mybestiole;//Bestiole décorée par le décorateur membre public : /**Constructeur de Membre*/ Membre(DBestiole* dbestiole); /**Destructeur de Membre*/ virtual ~Membre(); /**Agir*/ virtual void action( Milieu & monMilieu) override; /**Dessiner la bestiole*/ virtual void draw( UImg & support ) override; /**Bouger la bestiole*/ virtual void bouge( Milieu& monMilieu, double coef, paire_t objectif) override; /**Détecter une autre bestiole*/ virtual bool jeTeVois( const DBestiole* b ) const override; /**Initialiser les coordonnées de la bestiole*/ virtual void initCoords( int xLim, int yLim ) override; /**Renvoyer la visibilité de la bestiole*/ virtual double getVisibilite() const override; /**Obtenir la resitance de la bestiole*/ virtual double getResist() const override; /**Essayer de cloner la bestiole*/ virtual DBestiole* randomCloning() const override; /**Faire vieillir la bestiole*/ virtual bool vieillir() override; /**Copier la bestiole*/ virtual DBestiole* copy() override; /**Définir la couche externe de décorateur de la bestiole*/ virtual void setExterne(DBestiole* p) override; /**Récupérer les coordonnées de la bestiole*/ virtual paire_t getCoords() const override; /**Tuer la bestiole*/ virtual void killMe() override; /**Redéfinir les coordonnées de la bestiole*/ virtual void setCoords(paire_t coords) override; /**Obtenir le type de la bestiole*/ virtual string getType() const override; /**Définir le type de la bestiole*/ virtual void setType(string type) override; }; #endif
[ "benardjr@gmail.com" ]
benardjr@gmail.com
6e0f485b34a32e45abcafe767b7888f3419ad428
4e5d07a9eb881defd7923a4575809259522bd25f
/codeforces/educational/101/c.cpp
8ed2b91f2066539e9e299c1230aa99ec2842683a
[]
no_license
kt117/ProCom
c81e6c55c3f4b329c79755f43e8154e297328174
c5547429560100728cf15a8a8a696aa8c6c0317b
refs/heads/master
2022-05-06T15:41:01.639231
2022-04-09T17:23:21
2022-04-09T17:23:21
254,284,537
1
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> P; const ll MOD = 1e9+7; const ll INF = 1e18; #define rep(i,m,n) for(ll i = (m); i <= (n); i++) #define zep(i,m,n) for(ll i = (m); i < (n); i++) #define rrep(i,m,n) for(ll i = (m); i >= (n); i--) #define print(x) cout << (x) << endl; #define printa(x,m,n) for(int i = (m); i <= n; i++){cout << (x[i]) << " ";} cout<<endl; int main(){ cin.tie(0); ios::sync_with_stdio(false); ll t; cin >> t; while(t--){ ll n, k; cin >> n >> k; ll h[n]; zep(i, 0, n)cin >> h[i]; ll u = h[0]; ll l = h[0]; bool ans = true; zep(i, 1, n){ l = max(h[i], l - (k - 1)); u = min(h[i] + k - 1, u + k - 1); if(u < l){ ans = false; break; } } if(h[n - 1] < l || u < h[n - 1])ans = false; print(ans? "YES" : "NO") } return 0; }
[ "k.tohyama17@gmail.com" ]
k.tohyama17@gmail.com
7c66e3d08718d049ad00b3de430ea87f30f28133
d8dde07d7c9cf75f7f18a91ab1dd74a4a261a9e7
/contest/poj/shen10000/2487/8950447_AC_110MS_172K.cpp
16effd6320102dd295ec4e610f2929d92e2cd870
[]
no_license
tiankonguse/ACM
349109d3804e5b1a1de109ec48a2cb3b0dceaafc
ef70b8794c560cb87a6ba8f267e0cc5e9d06c31b
refs/heads/master
2022-10-09T19:58:38.805515
2022-09-30T06:59:53
2022-09-30T06:59:53
8,998,504
82
51
null
2020-11-09T05:17:09
2013-03-25T04:04:26
C++
UTF-8
C++
false
false
491
cpp
#include<stdio.h> #include<string.h> #include<stdlib.h> int str[1002]; int cmp(void const *a,void const *b) { return (*(int*)b-*(int*)a); } int main() { int n,j,i,num,p; scanf("%d",&n); for(i=0;i<n;i++) {printf("Scenario #%d:\n",i+1); scanf("%d%d",&num,&p); for(j=0;j<p;j++)scanf("%d",&str[j]); qsort(str,p,sizeof(int),cmp); for(j=0;j<p;j++) { num-=str[j]; if(num<=0)break; } if(j>=p)printf("impossible\n\n"); else printf("%d\n\n",j+1); } getchar();getchar(); return 0; }
[ "i@tiankonguse.com" ]
i@tiankonguse.com
3e6b44090f130657e7bf4a9922647c4b2dfd8031
a17a93045a02d5d70297ecb7ca899dd48c25dd3d
/Stone Engine/StoneEngine-Core/main.cpp
d3698e1e3435b0503fc1f53132303721dfdb3094
[]
no_license
StoneLabs/stone-engine
c2bea8f84e62c456388f113a3b2ec5db9e7b11ab
969b523d133bf7d1ad02670d70be7ff02212d28e
refs/heads/master
2022-06-30T03:59:44.885225
2017-07-26T18:44:23
2017-07-26T18:44:23
261,752,234
0
0
null
null
null
null
UTF-8
C++
false
false
3,613
cpp
#include "src/utils/timer.h" #include "src/graphics/buffers/Buffer.h" #include "src/graphics/buffers/IndexBuffer.h" #include "src/graphics/buffers/VertexArray.h" #include "src/graphics/layers/Group.h" #include "src/graphics/layers/TileLayer.h" #include "src/graphics/rendering/BatchRenderer2D.h" #include "src/graphics/rendering/Renderable2D.h" #include "src/graphics/rendering/Renderer2D.h" #include "src/graphics/rendering/SimpleRenderer2D.h" #include "src/graphics/rendering/Sprite.h" #include "src/graphics/rendering/StaticSprite.h" #include "src/graphics/rendering/Texture.h" #include "src/graphics/rendering/Label.h" #include "src/graphics/Shader.h" #include "src/graphics/window.h" #include "src/math/maths.h" #include "src/resource/ResourceLoader.h" #include <chrono> #include <iostream> #include <vector> #define WINDOW_INIT_WIDTH 960 #define WINDOW_INIT_HEIGHT 540 #include <stdio.h> /* defines FILENAME_MAX */ #ifdef WIN32 or WIN64 #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif int main(int argc, char *args) { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return errno; } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ std::cout << "The current working directory is " << cCurrentPath << std::endl; using namespace std; using namespace std::chrono; using namespace seng; using namespace seng::math; using namespace seng::graphics; using namespace seng::resource; Window window(WINDOW_INIT_WIDTH, WINDOW_INIT_HEIGHT, "Stone Engine - Test"); std::cout << window.getVersion() << std::endl << std::endl; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); Shader* sceneShader = new Shader("./res/basic.vs", "./res/basic.fs"); TileLayer scene(sceneShader); Texture *textures[] = { new Texture("./res/test1.png"), new Texture("./res/test2.png"), new Texture("./res/test3.png") }; Font *font = new Font("fonts/SourceSansPro-Light.otf", 20); #pragma region Sprites for (float y = -9.0f; y < 9.0f; y ++) { for (float x = -16.0f; x < 16.0f; x++) { if (rand() % 4 == 0) { scene.add(new Sprite(x, y, 0.9f, 0.9f, (rand() % 0xff + 1) | 0xffff0000)); } else scene.add(new Sprite(x, y, 0.9f, 0.9f, textures[rand() % 3])); } } #pragma endregion Being generated #pragma region FPS Counter Group *topleft = new Group(Matrix4f::translation(Vector3f(-16, 8, 0))); Label *fps = new Label("FPS: ", 0.5f, 0.2f, font, 0xffffffff); topleft->add(new Sprite(0, 0, 6, 2, 0xcc222222)); topleft->add(fps); scene.add(topleft); #pragma endregion Cool Font FPS GLint texIDs[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; sceneShader->enable(); sceneShader->setUniform1iv("textures", texIDs, 10); double MouseX = window.getWidth() / 2, MouseY = window.getHeight() / 2; Timer time; float timer = 0; unsigned short frames = 0; while (!window.closed()) { window.clear(); if (window.isMouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) window.getCursorPosition(MouseX, MouseY); if (window.isKeyPressed(GLFW_KEY_SPACE)) std::cout << "Key pressed!" << std::endl; if (window.isKeyReleased(GLFW_KEY_SPACE)) std::cout << "Key released!" << std::endl; scene.render(); sceneShader->setUniform2f("lightPos", Vector2f((float)MouseX / window.getWidth() * 2 - 1, -((float)MouseY / window.getHeight() * 2 - 1))); window.update(); frames++; if (time.elapsed() - timer > 1.0f) { timer += 1.0f; //printf("FPS: %d\n", frames); fps->text = "FPS: " + std::to_string(frames); frames = 0; } } return 0; }
[ "levyehrstein@googlemail.com" ]
levyehrstein@googlemail.com
af308b32a2c8d1c1e8f867b7c951e50daa35d7e0
42f9220fe969e13d0c9ecffdf19305029e68d40a
/bethe-xxz/iso-deviated.h
0ee3741bbab4bb94335b83f6d5be60b174a35cb5
[ "MIT" ]
permissive
robhagemans/bethe-solver
0eb9cb1c5af1de0faf52197c7f4c95d768594168
77b217c6cc23842b284ecd2d7b01fe28310cc32e
refs/heads/master
2021-01-17T12:20:49.692478
2020-09-05T15:19:13
2020-09-05T15:19:13
24,987,052
0
0
null
null
null
null
UTF-8
C++
false
false
4,199
h
#ifndef ISO_DEVIATED_H #define ISO_DEVIATED_H #include <math.h> #include <vector> #include <complex> #include <iostream> using namespace std; #include "strip.h" #include "iso-state.h" /** exceptions **/ extern const char* exc_NoCanDo; extern const char* exc_WrongPairWidth; extern const char* exc_Deprecated; /** XXXDeviatedState **/ class XXXDeviatedState : public XXX_State { public: // stores imaginary deviation FullStrip<REAL> deviance; // stores real deviation FullStrip<REAL> aberration; public: // maximum number of iteratons in deviance solution static int max_iter_deviance; // precision to be reached in deviance iteration static REAL deviance_precision; // how bad 'convergence' may become before we call it quits static REAL solve_bailout; // damping for deviance iteration static REAL damping_deviance; // damping for solveSymmetric() static REAL damping_symmetric; // deviance as set in constructor. can't be zero, that would give non-finite results. const static REAL start_deviance; // epsilon in the check for deviance=-0.5. NOTE that this need not be very small, as we don't really get 'near-collapses' const static REAL epsilon_collapse; // below which the norm would give a non-finite result if we would use the complex roots (i.e. we should use the string equations for the norm) const static REAL epsilon_deviation_norm; // how close roots may come to i/2 before we consider it to be exactly that for the calculation of energies const static REAL epsilon_energy; protected: // hold this value in iteration (rapidity) Strip<short int> hold; FullStrip<short int> hold_deviation; public: // we can currently only construct an XXXDeviatedState from a State XXXDeviatedState (const State& original); virtual ~XXXDeviatedState () {}; // iterate rapidities, taking deviance into account virtual void iterate (void); // solve for rapidities and deviance virtual bool solve(void); // norm of state virtual REAL norm(void) const; // roots of the bethe equation, with deviance for twostrings virtual vector< complex<REAL> > roots (void) const; // one root virtual complex<REAL> root (const int j, const int alpha, const int a) const; /// Gaudin's matrix -- used by norm() and newton() // Square<complex<REAL> > matrixGaudin (void); // we cannot calculate form factors with a deviated state as right state (lambda); use the converse form factor virtual REAL longitudinalFormFactor (const State& state_mu) const; virtual REAL transverseFormFactor (const State& state_mu) const; virtual REAL plusFormFactor (const State& state_mu) const; // deviation from string hypothesis virtual REAL stringDeviation (void) const; // magnitude of deviance virtual REAL devianceMagnitude(void) const; // is this an odd symmetric state? bool oddSymmetric(void) const; protected: // calculate energy and set energy field virtual REAL calculateEnergy (void) const; // steps in iteration: get an iteration of the rapidity virtual long double newRapidity (const int j, const int alpha) const; // steps in iteration: get a value for deviance and iteration virtual bool getNewDeviances (FullStrip<REAL>& new_deviance, FullStrip<REAL>& new_aberration, const int j, const int alpha) const; // solve some classes of symmetric states bool solveSymmetric(void); bool solveSingular(void); // these are needed by norm() // d small theta/d lambda virtual complex<long double> thetaDerivative (const complex<long double> rap, const int length) const; // scattering derivative term (d big theta / d lambda) virtual complex<long double> scatteringDerivative (const int j, const int alpha, const int a, const int k, const int beta, const int b) const; virtual complex<long double> scatteringDerivativeLeftDev (const int j, const int alpha, const int a, const int length_k, const int k, const int beta) const; virtual complex<long double> scatteringDerivativeRightDev (const int undev_j, const int j, const int alpha, const int k, const int beta, const int b) const; virtual long double scatteringDerivativeNoDev (const int undev_j, const int j, const int alpha, const int undev_k, const int k, const int beta) const; }; #endif
[ "robhagemans@users.noreply.github.com" ]
robhagemans@users.noreply.github.com
b2ed78e1de89f00b33300ca8ecfbf4adf3925ffd
9b882c3dfaa41e62b15fb635599ef6780f2c8379
/chrome/browser/extensions/forced_extensions/installation_reporter.h
dac43592de45e1e73454fc4e3972371a40f0598c
[ "BSD-3-Clause" ]
permissive
cqtangsong/chromium
1e042e2f49d9cb194790674805afcc1308a08f81
e73c1f260913f418bf5886b996b02dae372cfffa
refs/heads/master
2023-01-14T07:34:05.166609
2020-03-12T03:07:32
2020-03-12T03:07:32
246,735,752
2
0
BSD-3-Clause
2020-03-12T03:32:44
2020-03-12T03:32:43
null
UTF-8
C++
false
false
10,318
h
// Copyright 2018 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_EXTENSIONS_FORCED_EXTENSIONS_INSTALLATION_REPORTER_H_ #define CHROME_BROWSER_EXTENSIONS_FORCED_EXTENSIONS_INSTALLATION_REPORTER_H_ #include <map> #include <utility> #include "base/macros.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "base/optional.h" #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/install/crx_install_error.h" #include "extensions/browser/install/sandboxed_unpacker_failure_reason.h" #include "extensions/browser/updater/extension_downloader_delegate.h" #include "extensions/common/extension_id.h" namespace content { class BrowserContext; } // namespace content namespace extensions { // Helper class to save and retrieve extension installation stage and failure // reasons. class InstallationReporter : public KeyedService { public: // Stage of extension installing process. Typically forced extensions from // policies should go through all stages in this order, other extensions skip // CREATED stage. // Note: enum used for UMA. Do NOT reorder or remove entries. Don't forget to // update enums.xml (name: ExtensionInstallationStage) when adding new // entries. enum class Stage { // Extension found in ForceInstall policy and added to // ExtensionManagement::settings_by_id_. CREATED = 0, // TODO(crbug.com/989526): stages from NOTIFIED_FROM_MANAGEMENT to // SEEN_BY_EXTERNAL_PROVIDER are temporary ones for investigation. Remove // then after investigation will complete and we'll be confident in // extension handling between CREATED and PENDING. // ExtensionManagement class is about to pass extension with // INSTALLATION_FORCED mode to its observers. NOTIFIED_FROM_MANAGEMENT = 5, // ExtensionManagement class is about to pass extension with other mode to // its observers. NOTIFIED_FROM_MANAGEMENT_NOT_FORCED = 6, // ExternalPolicyLoader with FORCED type fetches extension from // ExtensionManagement. SEEN_BY_POLICY_LOADER = 7, // ExternalProviderImpl receives extension. SEEN_BY_EXTERNAL_PROVIDER = 8, // Extension added to PendingExtensionManager. PENDING = 1, // Extension added to ExtensionDownloader. DOWNLOADING = 2, // Extension archive downloaded and is about to be unpacked/checked/etc. INSTALLING = 3, // Extension installation finished (either successfully or not). COMPLETE = 4, // Magic constant used by the histogram macros. // Always update it to the max value. kMaxValue = SEEN_BY_EXTERNAL_PROVIDER, }; // Enum used for UMA. Do NOT reorder or remove entries. Don't forget to // update enums.xml (name: ExtensionInstallationFailureReason) when adding new // entries. enum class FailureReason { // Reason for the failure is not reported. Typically this should not happen, // because if we know that we need to install an extension, it should // immediately switch to CREATED stage leading to IN_PROGRESS failure // reason, not UNKNOWN. UNKNOWN = 0, // Invalid id of the extension. INVALID_ID = 1, // Error during parsing extension individual settings. MALFORMED_EXTENSION_SETTINGS = 2, // The extension is marked as replaced by ARC app. REPLACED_BY_ARC_APP = 3, // Malformed extension dictionary for the extension. MALFORMED_EXTENSION_DICT = 4, // The extension format from extension dict is not supported. NOT_SUPPORTED_EXTENSION_DICT = 5, // Invalid file path in the extension dict. MALFORMED_EXTENSION_DICT_FILE_PATH = 6, // Invalid version in the extension dict. MALFORMED_EXTENSION_DICT_VERSION = 7, // Invalid updated URL in the extension dict. MALFORMED_EXTENSION_DICT_UPDATE_URL = 8, // The extension doesn't support browser locale. LOCALE_NOT_SUPPORTED = 9, // The extension marked as it shouldn't be installed. NOT_PERFORMING_NEW_INSTALL = 10, // Profile is older than supported by the extension. TOO_OLD_PROFILE = 11, // The extension can't be installed for enterprise. DO_NOT_INSTALL_FOR_ENTERPRISE = 12, // The extension is already installed. ALREADY_INSTALLED = 13, // The download of the crx failed. CRX_FETCH_FAILED = 14, // Failed to fetch the manifest for this extension. MANIFEST_FETCH_FAILED = 15, // The manifest couldn't be parsed. MANIFEST_INVALID = 16, // The manifest was fetched and parsed, and there are no updates for this // extension. NO_UPDATE = 17, // The crx was downloaded, but failed to install. // Corresponds to CrxInstallErrorType. CRX_INSTALL_ERROR_DECLINED = 18, CRX_INSTALL_ERROR_SANDBOXED_UNPACKER_FAILURE = 19, CRX_INSTALL_ERROR_OTHER = 20, // Extensions without update url should receive a default one, but somewhy // this didn't work. Internal error, should never happen. NO_UPDATE_URL = 21, // Extension failed to add to PendingExtensionManager. PENDING_ADD_FAILED = 22, // ExtensionDownloader refuses to start downloading this extensions // (possible reasons: invalid ID/URL). DOWNLOADER_ADD_FAILED = 23, // Extension (at the moment of check) is not installed nor some installation // error reported, so extension is being installed now, stuck in some stage // or some failure was not reported. See enum Stage for more details. // This option is a failure only in the sense that we failed to install // extension in required time. IN_PROGRESS = 24, // The download of the crx failed. CRX_FETCH_URL_EMPTY = 25, // The download of the crx failed. CRX_FETCH_URL_INVALID = 26, // Magic constant used by the histogram macros. // Always update it to the max value. kMaxValue = CRX_FETCH_URL_INVALID, }; // Contains information about extension installation: failure reason, if any // reported, specific details in case of CRX install error, current // installation stage if known. struct InstallationData { InstallationData(); InstallationData(const InstallationData&); base::Optional<extensions::InstallationReporter::Stage> install_stage; base::Optional<extensions::ExtensionDownloaderDelegate::Stage> downloading_stage; base::Optional<extensions::ExtensionDownloaderDelegate::CacheStatus> downloading_cache_status; base::Optional<extensions::InstallationReporter::FailureReason> failure_reason; base::Optional<extensions::CrxInstallErrorDetail> install_error_detail; // Network error codes when failure_reason is CRX_FETCH_FAILED or // MANIFEST_FETCH_FAILED. base::Optional<int> network_error_code; base::Optional<int> response_code; // Number of fetch tries made when failure reason is CRX_FETCH_FAILED or // MANIFEST_FETCH_FAILED. base::Optional<int> fetch_tries; // Unpack failure reason in case of // CRX_INSTALL_ERROR_SANDBOXED_UNPACKER_FAILURE. base::Optional<extensions::SandboxedUnpackerFailureReason> unpacker_failure_reason; // Type of extension, assigned when CRX installation error detail is // DISALLOWED_BY_POLICY. base::Optional<Manifest::Type> extension_type; }; class Observer : public base::CheckedObserver { public: ~Observer() override; virtual void OnExtensionInstallationFailed(const ExtensionId& id, FailureReason reason) {} // Called when any change happens. For production please use more specific // methods (create one if necessary). virtual void OnExtensionDataChangedForTesting( const ExtensionId& id, const content::BrowserContext* context, const InstallationData& data) {} }; explicit InstallationReporter(const content::BrowserContext* context); ~InstallationReporter() override; // Convenience function to get the InstallationReporter for a BrowserContext. static InstallationReporter* Get(content::BrowserContext* context); // Remembers failure reason and in-progress stages in memory. void ReportInstallationStage(const ExtensionId& id, Stage stage); void ReportFetchError( const ExtensionId& id, FailureReason reason, const ExtensionDownloaderDelegate::FailureData& failure_data); void ReportFailure(const ExtensionId& id, FailureReason reason); void ReportDownloadingStage(const ExtensionId& id, ExtensionDownloaderDelegate::Stage stage); void ReportDownloadingCacheStatus( const ExtensionId& id, ExtensionDownloaderDelegate::CacheStatus cache_status); // Assigns the extension type. See InstallationData::extension_type for more // details. void ReportExtensionTypeForPolicyDisallowedExtension( const ExtensionId& id, Manifest::Type extension_type); void ReportCrxInstallError(const ExtensionId& id, FailureReason reason, CrxInstallErrorDetail crx_install_error); void ReportSandboxedUnpackerFailureReason( const ExtensionId& id, SandboxedUnpackerFailureReason unpacker_failure_reason); // Retrieves known information for installation of extension |id|. // Returns empty data if not found. InstallationData Get(const ExtensionId& id); static std::string GetFormattedInstallationData(const InstallationData& data); // Clears all collected failures and stages. void Clear(); void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); private: // Helper function to report installation failures to the observers. void NotifyObserversOfFailure(const ExtensionId& id, FailureReason reason, const InstallationData& data); const content::BrowserContext* browser_context_; std::map<ExtensionId, InstallationReporter::InstallationData> installation_data_map_; base::ObserverList<Observer> observers_; DISALLOW_COPY_AND_ASSIGN(InstallationReporter); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_FORCED_EXTENSIONS_INSTALLATION_REPORTER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a8bb743db19fd5567845b9bf894a548892c32a3b
26ba18f15532023552cf9523feb84a317b47beb0
/JUCE/modules/juce_core/logging/juce_Logger.cpp
06b75e0c4ef96980506f8e384a5de57e4b00ea34
[ "MIT", "GPL-1.0-or-later", "GPL-3.0-only", "ISC", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
permissive
Ultraschall/ultraschall-soundboard
d3fdaf92061f9eacc65351b7b4bc937311f9e7fc
8a7a538831d8dbf7689b47611d218560762ae869
refs/heads/main
2021-12-14T20:19:24.170519
2021-03-17T22:34:11
2021-03-17T22:34:11
27,304,678
27
3
MIT
2021-02-16T20:49:08
2014-11-29T14:36:19
C++
UTF-8
C++
false
false
1,952
cpp
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { Logger::Logger() {} Logger::~Logger() { // You're deleting this logger while it's still being used! // Always call Logger::setCurrentLogger (nullptr) before deleting the active logger. jassert (currentLogger != this); } Logger* Logger::currentLogger = nullptr; void Logger::setCurrentLogger (Logger* const newLogger) noexcept { currentLogger = newLogger; } Logger* Logger::getCurrentLogger() noexcept { return currentLogger; } void Logger::writeToLog (const String& message) { if (currentLogger != nullptr) currentLogger->logMessage (message); else outputDebugString (message); } #if JUCE_LOG_ASSERTIONS || JUCE_DEBUG void JUCE_API JUCE_CALLTYPE logAssertion (const char* const filename, const int lineNum) noexcept { String m ("JUCE Assertion failure in "); m << File::createFileWithoutCheckingPath (filename).getFileName() << ':' << lineNum; #if JUCE_LOG_ASSERTIONS Logger::writeToLog (m); #else DBG (m); #endif } #endif } // namespace juce
[ "daniel@lindenfelser.de" ]
daniel@lindenfelser.de
18f43e50db8472e5d0a9ece5cb82e3c2e796de6a
83b8a9e0ba13a792f44fca455ba01043b9a81c78
/BOJ_2019_06/BOJ_2019_06/0627_BOJ_14939.cpp
602d00f58907c238c97dcb17e8f9cee6f98287a1
[]
no_license
BoGyuPark/VS_BOJ
0799a0c62fd72a6fc1e6f7e34fc539a742c0782b
965973600dedbd5f3032c3adb4b117cc43c62a8f
refs/heads/master
2020-04-14T12:45:53.930735
2019-12-04T03:06:44
2019-12-04T03:06:44
163,849,994
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,407
cpp
#include<iostream> using namespace std; int map[10][10], cpy[10][10], sel[11], cnt, ans; int dx[] = { 0,0,-1,1 }; int dy[] = { 1,-1,0,0 }; void cpyMap() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { map[i][j] = cpy[i][j]; } } } void switching(int r, int c) { map[r][c] = (map[r][c] + 1) % 2; for (int i = 0; i < 4; i++) { int nx = r + dx[i], ny = c + dy[i]; if (nx < 0 || ny < 0 || nx >= 10 || ny >= 10) continue; map[nx][ny] = (map[nx][ny] + 1) % 2; } } bool cal_cnt() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 10; j++) { if (map[i][j] == 1) { switching(i + 1, j); cnt++; } } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (map[i][j] == 1) { return false; } } } return true; } void dfs(int index) { if (index == 10) { cnt = 0; for (int j = 0; j < 10; j++) { if (sel[j] == 1) { switching(0, j); cnt++; } } if (cal_cnt()) { if (ans > cnt) ans = cnt; } cpyMap(); return; } for (int i = 0; i < 2; i++) { sel[index] = i; dfs(index + 1); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) { char t; cin >> t; int value = (t == '#' ? 0 : 1); //0 : ²¨Áü, 1:ÄÑÁü cpy[i][j] = map[i][j] = value; } ans = 987654321; dfs(0); if (ans == 987654321) ans = -1; cout << ans; }
[ "shaing123@naver.com" ]
shaing123@naver.com
a508d7d63e7de74da20c7f18434571d04e8fb083
a0eec09e34faea8be09cf9af7df7448dfe87d343
/nfbe/cc/layers/video_frame_provider_client_impl.cc
9cd347010a9d53e91e177c17f1bcde0b82b6b5d3
[ "BSD-3-Clause" ]
permissive
bopopescu/SmartTV-SeriesL
4a7b882d676ba6ff46cdc5813dd9ce22b70e8fe7
4b073cd59812cd4702dc318a17fc6ff91ed3cf5b
refs/heads/master
2021-09-15T00:34:40.911285
2018-03-03T16:06:24
2018-03-03T16:06:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,294
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/layers/video_frame_provider_client_impl.h" #include "base/trace_event/trace_event.h" #include "cc/base/math_util.h" #include "cc/layers/video_layer_impl.h" #include "media/base/video_frame.h" namespace cc { // static scoped_refptr<VideoFrameProviderClientImpl> VideoFrameProviderClientImpl::Create(VideoFrameProvider* provider, VideoFrameControllerClient* client) { return make_scoped_refptr(new VideoFrameProviderClientImpl(provider, client)); } VideoFrameProviderClientImpl::VideoFrameProviderClientImpl( VideoFrameProvider* provider, VideoFrameControllerClient* client) : provider_(provider), client_(client), active_video_layer_(nullptr), stopped_(false), rendering_(false), needs_put_current_frame_(false) #if defined(VIDEO_HOLE) , needs_clear_(false) #endif { // This only happens during a commit on the compositor thread while the main // thread is blocked. That makes this a thread-safe call to set the video // frame provider client that does not require a lock. The same is true of // the call to Stop(). provider_->SetVideoFrameProviderClient(this); // This matrix is the default transformation for stream textures, and flips // on the Y axis. stream_texture_matrix_ = gfx::Transform( 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); } VideoFrameProviderClientImpl::~VideoFrameProviderClientImpl() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(stopped_); } VideoLayerImpl* VideoFrameProviderClientImpl::ActiveVideoLayer() const { DCHECK(thread_checker_.CalledOnValidThread()); return active_video_layer_; } void VideoFrameProviderClientImpl::SetActiveVideoLayer( VideoLayerImpl* video_layer) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(video_layer); #if defined(VIDEO_HOLE) // To throttle drawing video hole frame if (!active_video_layer_ || (active_video_layer_ && !active_video_layer_->IsSameVideoHoleFrame(*video_layer))) { needs_clear_ = true; } #endif active_video_layer_ = video_layer; } void VideoFrameProviderClientImpl::Stop() { DCHECK(thread_checker_.CalledOnValidThread()); // It's called when the main thread is blocked, so lock isn't needed. if (provider_) { provider_->SetVideoFrameProviderClient(nullptr); provider_ = nullptr; } if (rendering_) StopRendering(); active_video_layer_ = nullptr; stopped_ = true; } bool VideoFrameProviderClientImpl::Stopped() const { DCHECK(thread_checker_.CalledOnValidThread()); return stopped_; } scoped_refptr<media::VideoFrame> VideoFrameProviderClientImpl::AcquireLockAndCurrentFrame() { DCHECK(thread_checker_.CalledOnValidThread()); provider_lock_.Acquire(); // Balanced by call to ReleaseLock(). if (!provider_) return nullptr; return provider_->GetCurrentFrame(); } void VideoFrameProviderClientImpl::PutCurrentFrame() { DCHECK(thread_checker_.CalledOnValidThread()); provider_lock_.AssertAcquired(); provider_->PutCurrentFrame(); needs_put_current_frame_ = false; } void VideoFrameProviderClientImpl::ReleaseLock() { DCHECK(thread_checker_.CalledOnValidThread()); provider_lock_.AssertAcquired(); provider_lock_.Release(); } bool VideoFrameProviderClientImpl::HasCurrentFrame() { base::AutoLock locker(provider_lock_); return provider_ && provider_->HasCurrentFrame(); } const gfx::Transform& VideoFrameProviderClientImpl::StreamTextureMatrix() const { DCHECK(thread_checker_.CalledOnValidThread()); return stream_texture_matrix_; } void VideoFrameProviderClientImpl::StopUsingProvider() { { // Block the provider from shutting down until this client is done // using the frame. base::AutoLock locker(provider_lock_); provider_ = nullptr; } if (rendering_) StopRendering(); } void VideoFrameProviderClientImpl::StartRendering() { DCHECK(thread_checker_.CalledOnValidThread()); TRACE_EVENT0("cc", "VideoFrameProviderClientImpl::StartRendering"); DCHECK(!rendering_); DCHECK(!stopped_); rendering_ = true; client_->AddVideoFrameController(this); } void VideoFrameProviderClientImpl::StopRendering() { DCHECK(thread_checker_.CalledOnValidThread()); TRACE_EVENT0("cc", "VideoFrameProviderClientImpl::StopRendering"); DCHECK(rendering_); DCHECK(!stopped_); client_->RemoveVideoFrameController(this); rendering_ = false; } void VideoFrameProviderClientImpl::DidReceiveFrame() { TRACE_EVENT1("cc", "VideoFrameProviderClientImpl::DidReceiveFrame", "active_video_layer", !!active_video_layer_); DCHECK(thread_checker_.CalledOnValidThread()); needs_put_current_frame_ = true; #if defined(VIDEO_HOLE) // Throttle drawing video hole frame if (active_video_layer_ && needs_clear_) { active_video_layer_->SetNeedsRedraw(); needs_clear_ = false; } #else if (active_video_layer_) active_video_layer_->SetNeedsRedraw(); #endif } void VideoFrameProviderClientImpl::OnBeginFrame(const BeginFrameArgs& args) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(rendering_); DCHECK(!stopped_); TRACE_EVENT0("cc", "VideoFrameProviderClientImpl::OnBeginFrame"); { base::AutoLock locker(provider_lock_); // We use frame_time + interval here because that is the estimated time at // which a frame returned during this phase will end up being displayed. if (!provider_ || !provider_->UpdateCurrentFrame(args.frame_time + args.interval, args.frame_time + 2 * args.interval)) { return; } } // Warning: Do not hold |provider_lock_| while calling this function, it may // lead to a reentrant call to HasCurrentFrame() above. DidReceiveFrame(); } void VideoFrameProviderClientImpl::DidDrawFrame() { DCHECK(thread_checker_.CalledOnValidThread()); { base::AutoLock locker(provider_lock_); if (provider_ && needs_put_current_frame_) provider_->PutCurrentFrame(); } needs_put_current_frame_ = false; } } // namespace cc
[ "opensource@hisense.com" ]
opensource@hisense.com
79b56ed070f8759c4946cc29c7a29fee496051a7
e5ebd9ed72b88bd2a977355d75687a9e308ab1f5
/engine/graphics/direct3d11/D3D11DepthStencilState.cpp
23aea57cb6f50fcc93307ff55a8f318641fadd1f
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
codingwatching/ouzel
d16a3c51df305072b4e69cf763f7ca0d5675bbda
07f09aefd3832801826441cd049b149c24a06b58
refs/heads/master
2023-07-17T09:30:48.703492
2021-08-26T03:54:28
2021-08-26T03:54:28
400,041,322
1
0
null
null
null
null
UTF-8
C++
false
false
5,238
cpp
// Ouzel by Elviss Strazdins #include "../../core/Setup.h" #if OUZEL_COMPILE_DIRECT3D11 #include "D3D11DepthStencilState.hpp" #include "D3D11RenderDevice.hpp" namespace ouzel::graphics::d3d11 { namespace { constexpr D3D11_COMPARISON_FUNC getCompareFunction(CompareFunction compareFunction) { switch (compareFunction) { case CompareFunction::never: return D3D11_COMPARISON_NEVER; case CompareFunction::less: return D3D11_COMPARISON_LESS; case CompareFunction::equal: return D3D11_COMPARISON_EQUAL; case CompareFunction::lessEqual: return D3D11_COMPARISON_LESS_EQUAL; case CompareFunction::greater: return D3D11_COMPARISON_GREATER; case CompareFunction::notEqual: return D3D11_COMPARISON_NOT_EQUAL; case CompareFunction::greaterEqual: return D3D11_COMPARISON_GREATER_EQUAL; case CompareFunction::always: return D3D11_COMPARISON_ALWAYS; default: throw std::runtime_error("Unsupported compare function"); } } constexpr D3D11_STENCIL_OP getStencilOperation(StencilOperation stencilOperation) { switch (stencilOperation) { case StencilOperation::keep: return D3D11_STENCIL_OP_KEEP; case StencilOperation::zero: return D3D11_STENCIL_OP_ZERO; case StencilOperation::replace: return D3D11_STENCIL_OP_REPLACE; case StencilOperation::incrementClamp: return D3D11_STENCIL_OP_INCR_SAT; case StencilOperation::decrementClamp: return D3D11_STENCIL_OP_DECR_SAT; case StencilOperation::invert: return D3D11_STENCIL_OP_INVERT; case StencilOperation::incrementWrap: return D3D11_STENCIL_OP_INCR; case StencilOperation::decrementWrap: return D3D11_STENCIL_OP_DECR; default: throw std::runtime_error("Unsupported stencil operation"); } } } DepthStencilState::DepthStencilState(RenderDevice& initRenderDevice, bool initDepthTest, bool initDepthWrite, CompareFunction initCompareFunction, bool initStencilEnabled, std::uint32_t initStencilReadMask, std::uint32_t initStencilWriteMask, StencilOperation initFrontFaceStencilFailureOperation, StencilOperation initFrontFaceStencilDepthFailureOperation, StencilOperation initFrontFaceStencilPassOperation, CompareFunction initFrontFaceStencilCompareFunction, StencilOperation initBackFaceStencilFailureOperation, StencilOperation initBackFaceStencilDepthFailureOperation, StencilOperation initBackFaceStencilPassOperation, CompareFunction initBackFaceStencilCompareFunction): RenderResource{initRenderDevice} { D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc; depthStencilStateDesc.DepthEnable = initDepthTest ? TRUE : FALSE; depthStencilStateDesc.DepthWriteMask = initDepthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; depthStencilStateDesc.DepthFunc = getCompareFunction(initCompareFunction); depthStencilStateDesc.StencilEnable = initStencilEnabled ? TRUE : FALSE; depthStencilStateDesc.StencilReadMask = static_cast<UINT8>(initStencilReadMask); depthStencilStateDesc.StencilWriteMask = static_cast<UINT8>(initStencilWriteMask); depthStencilStateDesc.FrontFace.StencilFailOp = getStencilOperation(initFrontFaceStencilFailureOperation); depthStencilStateDesc.FrontFace.StencilDepthFailOp = getStencilOperation(initFrontFaceStencilDepthFailureOperation); depthStencilStateDesc.FrontFace.StencilPassOp = getStencilOperation(initFrontFaceStencilPassOperation); depthStencilStateDesc.FrontFace.StencilFunc = getCompareFunction(initFrontFaceStencilCompareFunction); depthStencilStateDesc.BackFace.StencilFailOp = getStencilOperation(initBackFaceStencilFailureOperation); depthStencilStateDesc.BackFace.StencilDepthFailOp = getStencilOperation(initBackFaceStencilDepthFailureOperation); depthStencilStateDesc.BackFace.StencilPassOp = getStencilOperation(initBackFaceStencilPassOperation); depthStencilStateDesc.BackFace.StencilFunc = getCompareFunction(initBackFaceStencilCompareFunction); ID3D11DepthStencilState* newDepthStencilState; if (const auto hr = renderDevice.getDevice()->CreateDepthStencilState(&depthStencilStateDesc, &newDepthStencilState); FAILED(hr)) throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 depth stencil state"); depthStencilState = newDepthStencilState; } } #endif
[ "elviss@elviss.lv" ]
elviss@elviss.lv
5dc9e5c3bff550f02e7b6bafd0ddb56e06a4f4dc
dbf960db345e6232b195a4a7230a6e3d7dcdefd4
/lab3_question2.cpp
ce0b67ac47343f3dece3f44c278897b398490d34
[]
no_license
solarstorm123/C-142-assignments
0f8cd9b5f9b834d0059ad932a02391def481e6cd
5220d9cfab151e574b293c2db4057e36395eefb6
refs/heads/master
2021-05-11T12:55:51.118539
2018-04-10T12:51:07
2018-04-10T12:51:07
117,667,877
0
0
null
null
null
null
UTF-8
C++
false
false
3,131
cpp
#include<iostream> using namespace std; //data structure of node. struct node{ int data; //node has two components , one for storing data and other for linking it to other nodes. node*next; }; //data structure of linked list. class linkedList{ private: //can be accessed only through member functions. node*head; node*tail; public: //constructor i.e. initialization of head and tail. linkedList(){ head=NULL; tail=NULL; } int n=0; //will be used to count the number the nodes. void addNode(int a){ //function to add a node. node*temp=new node; if (head==NULL){ //for adding the first node. head=temp; tail=temp; temp->data=a; temp->next=NULL; } else{ //for adding subsequent nodes. node*temp=new node; temp->data=a; temp->next=head; tail->next=temp; tail=temp; } n++; //adds one to the value of n every time a node is added and similarly substract one in the following functions. } void insertAt(int pos, int data){ //insert node at any valid position. if (pos==n+1){ addNode(data); n++; } else if(pos>n+1){ cout<<"linked list does not have that many elements"; } else if(pos<=n && pos>0){ node*temp=new node; node*temp1=head; for(int x=1;x<pos-1;x++){ temp1=temp1->next; } temp->next=temp1->next; temp1->next=temp; temp->data=data; n++; } else{cout<<"invalid entry";} } void deleteNode(){ //delete the last node. node*temp=head; while(temp->next!=tail){ temp=temp->next; } tail=temp; temp=temp->next; delete temp; tail->next=head; n--; } void deleteNodeAt(int pos){ //delete node any given position if (pos<n){ node*temp=head; for(int x=1;x<pos-1;x++){ temp=temp->next; } node*temp1=temp->next; temp->next=temp1->next; delete temp1; n--; } else if (pos==n){ deleteNode(); n--; } else if (pos>n){ cout<<"invalid entry"; } } void countItems(){ cout<<"the number of elements are :"<<n<<endl; } void display(){ //displays the elements of linked list. node*temp=head; for (node* temp=head; temp!=tail; temp=temp->next){ cout << temp->data << "->"; } cout <<tail->data<<"-> NULL" << endl; } void displayCheck(int q){ //to check that the circular linked list is formed. node*temp=head; for(int i=0;i<q;i++){ cout<<temp->data<<"->"; temp=temp->next;} } }; int main(){ linkedList s; //create a linked list named s. for(int i=1;i<11;i++){ //adding elements to the node. s.addNode(i); } s.display(); //performing various functions defined above. s.deleteNode(); s.display(); s.deleteNodeAt(3); s.display(); s.countItems(); s.insertAt(3,45); s.display(); s.countItems(); s.displayCheck(45); return 0; }
[ "noreply@github.com" ]
noreply@github.com
1005223118e48258aa7ab79c9d14209c6fc78927
35f575c997f226e4662ae214735e29186e93d1bf
/dependencies/Ogre/src/Samples/DeferredShading/include/GBufferMaterialGenerator.h
3edbb59c24095dd1c766317adddca64f4b152f3f
[ "MIT", "Apache-2.0" ]
permissive
PTSD-3D/PTSD-Engine
b227aa52b9f948a7794c0075295e70d4a71c4353
2f523b8a7fd768c8e3cfd634e53d8c34b3b359ef
refs/heads/main
2023-05-04T03:25:26.093194
2021-05-27T21:10:25
2021-05-27T21:10:25
345,047,719
3
0
Apache-2.0
2021-05-27T21:10:26
2021-03-06T08:50:35
C++
UTF-8
C++
false
false
2,345
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #ifndef _GBUFFER_MATERIAL_GENERATOR_H_ #define _GBUFFER_MATERIAL_GENERATOR_H_ #include "MaterialGenerator.h" /** Class for generating materials for objects to render themselves to the GBuffer * @note This does not support all the possible rendering techniques out there. * in order to support more, either expand this class or make sure that objects * that will not get treated correctly will not have materials generated for them. */ class GBufferMaterialGenerator : public MaterialGenerator { public: //Constructor GBufferMaterialGenerator(); //The relevant options for objects that are rendered to the GBuffer enum GBufferPermutations { //(Regular) Textures GBP_NO_TEXTURES = 0x00000000, GBP_ONE_TEXTURE = 0x00000001, GBP_TWO_TEXTURES = 0x00000002, GBP_THREE_TEXTURES = 0x00000003, GBP_TEXTURE_MASK = 0x0000000F, //Material properties GBP_HAS_DIFFUSE_COLOUR = 0x00000010, //The number of texture coordinate sets GBP_NO_TEXCOORDS = 0x00000000, GBP_ONE_TEXCOORD = 0x00000100, GBP_TWO_TEXCOORDS = 0x00000200, GBP_TEXCOORD_MASK = 0x00000700, //Do we have a normal map GBP_NORMAL_MAP = 0x00000800, //Are we skinned? GBP_SKINNED = 0x00010000 }; //The mask of the flags that matter for generating the fragment shader static const Ogre::uint32 FS_MASK = 0x0000FFFF; //The mask of the flags that matter for generating the vertex shader static const Ogre::uint32 VS_MASK = 0x00FFFF00; //The mask of the flags that matter for generating the material static const Ogre::uint32 MAT_MASK = 0xFF00FFFF; }; #endif
[ "adralv01@ucm.es" ]
adralv01@ucm.es
a1168e07d3590550b97ab4e91d27948b59d7e6a1
197fc7304451f90168420be40e7bd24cf171af66
/fluidicmachinemodel/rules/conjunction.h
77322cb4940b7eb5b407b81cba61280be546c6e1
[]
no_license
ponxosio/FluidicMachineModel
c1779fd714c2517cdb9138b4fae6ba68bcf952b1
116bb0ba82eaaeeb3fc8cb91b4eda5ad44f614cc
refs/heads/master
2020-06-09T14:17:07.573899
2017-09-01T18:13:18
2017-09-01T18:13:18
76,034,525
0
0
null
2017-09-01T18:13:19
2016-12-09T12:43:01
C++
UTF-8
C++
false
false
903
h
#ifndef CONJUNCTION_H #define CONJUNCTION_H #include <memory> #include "fluidicmachinemodel/rules/predicate.h" #include "fluidicmachinemodel/fluidicmachinemodel_global.h" class CONJUCTION_EXPORT Conjunction : public Predicate { public: typedef enum BoolOperators_ { predicate_and, predicate_or } BoolOperators; Conjunction(std::shared_ptr<Predicate> left, BoolOperators op, std::shared_ptr<Predicate> right); virtual ~Conjunction(); virtual void fillTranslationStack(TranslationStack* stack); std::shared_ptr<Predicate> getLeftPredicate() { return left; } std::shared_ptr<Predicate> getRightPredicate() { return right; } inline BoolOperators getOperation() { return op; } protected: std::shared_ptr<Predicate> left; std::shared_ptr<Predicate> right; BoolOperators op; }; #endif // CONJUNCTION_H
[ "ponxosio@gmail.com" ]
ponxosio@gmail.com
25312bde5f1ecceee6156637cf156bbbb4d74a92
74018a669138e20a2f8c26a59109c665e91b771e
/Ursa/src/Ursa/Events/KeyEvent.h
9bdd8fa3f1a4b014a9c58d0cf20ed15f0bf177e6
[ "Apache-2.0" ]
permissive
quiniks/Ursa
099e9cceaa09d4582e68c6cfcd4f442507504870
4f6c7c153d9d4c2ccb4c42f06d2fa88910d15c8c
refs/heads/main
2021-08-06T12:03:50.283073
2021-01-08T17:54:39
2021-01-08T17:54:39
236,791,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
h
#pragma once #include "Ursa/Events/Event.h" namespace Ursa { class KeyEvent : public Event { public: inline int GetKeyCode() const { return m_KeyCode; } EVENT_CLASS_CATEGORY(EventCategory::EventCategoryKeyboard | EventCategory::EventCategoryInput) protected: KeyEvent(int keycode) : m_KeyCode(keycode) {} int m_KeyCode; }; class KeyPressedEvent : public KeyEvent { public: KeyPressedEvent(int keycode, int repeatCount) : KeyEvent(keycode), m_RepeatCount(repeatCount) {} inline int GetRepeatCount() const { return m_RepeatCount; } std::string ToString() const override { std::stringstream ss; ss << "KeyPressedEvent: " << m_KeyCode << " (" << m_RepeatCount << " repeats)"; return ss.str(); } EVENT_CLASS_TYPE(KeyPressed) private: int m_RepeatCount; }; class KeyReleasedEvent : public KeyEvent { public: KeyReleasedEvent(int keycode) : KeyEvent(keycode) {} std::string ToString() const override { std::stringstream ss; ss << "KeyReleasedEvent: " << m_KeyCode; return ss.str(); } EVENT_CLASS_TYPE(KeyReleased) }; class KeyTypedEvent : public KeyEvent { public: KeyTypedEvent(int keycode) : KeyEvent(keycode) {} std::string ToString() const override { std::stringstream ss; ss << "KeyTypedEvent: " << m_KeyCode; return ss.str(); } EVENT_CLASS_TYPE(KeyTyped) }; }
[ "samknight4321@gmail.com" ]
samknight4321@gmail.com
4dda6e86d89c2bf3118e73975587bf6c9c2d82bf
4966b3b6600596681af0d7506a2c0914b296abae
/ShaderParser/ShaderAnalysis.cpp
196b91d9b463ce63fe7e4b7ffc03ec391aefece1
[ "MIT" ]
permissive
djewsbury/XLE
4200c797e823e683cebb516958ebee5f45a02bf0
f7f63de2c620ed5d0b1292486eb894016932b74b
refs/heads/master
2023-07-03T14:26:38.517034
2023-06-30T03:22:03
2023-06-30T03:22:03
32,975,591
13
6
null
2015-03-27T08:35:02
2015-03-27T08:35:02
null
UTF-8
C++
false
false
15,510
cpp
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "ShaderAnalysis.h" #include "AutomaticSelectorFiltering.h" #include "../RenderCore/MinimalShaderSource.h" #include "../Assets/IFileSystem.h" #include "../Assets/AssetUtils.h" #include "../OSServices/Log.h" #include "../Formatters/TextFormatter.h" #include "../Utility/Streams/PreprocessorInterpreter.h" #include "../Formatters/FormatterUtils.h" #include "../Utility/StringFormat.h" #include <sstream> namespace ShaderSourceParser { template<typename CharType> static bool WhitespaceChar(CharType c) // (excluding new line) { return c==' ' || c=='\t' || c==0x0B || c==0x0C || c==0x85 || c==0xA0 || c==0x0; } static StringSection<> ParseIncludeDirective(StringSection<> src) { auto i = src.begin(); while (i != src.end() && WhitespaceChar(*i)) ++i; if (i != src.end() && (*i == '"' || *i == '<')) { char terminator = (*i == '"') ? '"' : '>'; ++i; auto resultStart = i; while (i != src.end() && *i != terminator) ++i; if (i == src.end()) return {}; // no terminator return MakeStringSection(resultStart, i); } return {}; // didn't understand } struct LineDetails { enum class LineType { Normal, EndsInBlockComment, EndsInTrailingLineComment }; StringSection<> _line; LineType _type; const char* _nextLineBegin = nullptr; const char* _firstNonCommentNonWhitespaceChar = nullptr; }; static LineDetails ParseLineDetails(StringSection<> src, LineDetails::LineType prevLineType) { // Note -- there's a bit of overlap between this behaviour and what we do in the "ConditionalProcessingTokenizer" class // in PredefinedCBLayout.cpp. It would be nice if we could combine the parsing together somehow bool inBlockComment = prevLineType == LineDetails::LineType::EndsInBlockComment; bool inLineComment = prevLineType == LineDetails::LineType::EndsInTrailingLineComment; auto i = src.begin(); auto firstNonCommentNonWhitespaceChar = src.end(); for (;;) { if (i == src.end() || *i == '\n' || *i == '\r') { // Hit the end of the line; return our result // Note that even when we're inside of a block comment we will return here LineDetails result; result._line = MakeStringSection(src.begin(), i); if (inBlockComment) { result._type = LineDetails::LineType::EndsInBlockComment; } else if (inLineComment) { if ((i - 1) >= src.begin() && *(i-1) == '\\') { result._type = LineDetails::LineType::EndsInTrailingLineComment; } else result._type = LineDetails::LineType::Normal; // line comment ends here, so we don't need to care about it for future lines } else { result._type = LineDetails::LineType::Normal; } result._firstNonCommentNonWhitespaceChar = std::min(i, firstNonCommentNonWhitespaceChar); // i currently points to the end of this line; we should // advance to the start of the next line if (i!=src.end()) { if (*i == '\n') { ++i; } else if (*i == '\r') { ++i; if (i < src.end() && *i == '\n') ++i; } } result._nextLineBegin = i; return result; } if (inBlockComment) { if (*i == '*') { if (i+1 < src.end() && *(i+1) == '/') { inBlockComment = false; i+=2; continue; } } } else if (!inLineComment) { // We cannot start a block comment inside of a line comment, so only // do this check when where not in a line comment if (*i == '/') { if (i+1 < src.end() && *(i+1) == '*') { inBlockComment = true; i+=2; continue; } else if (i+1 < src.end() && *(i+1) == '/') { inLineComment = true; i+=2; continue; } } // otherwise, this is real text, let's record it if (!WhitespaceChar(*i) && firstNonCommentNonWhitespaceChar == src.end()) { firstNonCommentNonWhitespaceChar = i; } } ++i; } } static bool HasNonWhiteSpace(StringSection<> input) { for (auto i:input) if (!WhitespaceChar(i) && i != '\n' && i != '\r') return true; return false; } RenderCore::SourceCodeWithRemapping ExpandIncludes( StringSection<> src, const std::string& srcName, const ::Assets::DirectorySearchRules& searchRules) { // Find the #include statements in the input and expand them out // Note; some limitations: // 1) not handling #pragma once -- every include gets included every time // 2) expanding out includes even when they are within a failed "#if" preprocessor statement // 3) some combinations of comments and preprocessor statements will be handled incorrectly. Comments are mostly // handled, but there are some less common cases (such as a block/line comment immediately after the "#include" that // can throw it off unsigned sourceLineIndex = 0; // (note zero based index for lines -- ie, line at the top of the file is line number 0) unsigned workingBlockStartLineIndex = 0; unsigned workingBlockLineCount = 0; StringSection<> workingBlock; std::stringstream outputStream; unsigned outputStreamLineCount = 0; RenderCore::SourceCodeWithRemapping result; LineDetails::LineType prevLineType = LineDetails::LineType::Normal; auto i = src.begin(); while (i != src.end()) { auto lineDetails = ParseLineDetails(MakeStringSection(i, src.end()), prevLineType); // Check if the first non-whitespace, non-commented character on the line // is a hash -- if so, there's a preprocessor directive to consider bool appendLineToWorkingBlock = true; { auto i2 = lineDetails._firstNonCommentNonWhitespaceChar; if (i2 != lineDetails._line.end() && *i2 == '#') { ++i2; // Note -- comments not supporting in these upcoming scans while (i2 != lineDetails._line.end() && WhitespaceChar(*i2)) ++i2; auto i3 = i2; while (i3 != lineDetails._line.end() && !WhitespaceChar(*i3) && *i3 != '"' && *i3 != '<') ++i3; // It is a valid preprocessor statement; check if it's an include if (XlEqStringI(MakeStringSection(i2, i3), "include")) { auto includeFile = ParseIncludeDirective(MakeStringSection(i3, lineDetails._line.end())); if (includeFile.IsEmpty()) Throw(Formatters::FormatException("Could not interpret #include directive", Formatters::StreamLocation{unsigned(i3-lineDetails._line.begin()), sourceLineIndex})); // Commit the working block to our output stream // We must also include the text that becomes before the #include on this line -- because it // could close a block comment that began on a previous line bool requiresPrefix = HasNonWhiteSpace(MakeStringSection(lineDetails._line._start, lineDetails._firstNonCommentNonWhitespaceChar)); if (!workingBlock.IsEmpty() || requiresPrefix) { result._lineMarkers.push_back( RenderCore::ILowLevelCompiler::SourceLineMarker { srcName, (!workingBlock.IsEmpty()) ? workingBlockStartLineIndex : sourceLineIndex, // (second case is for when there is only the prefix, and no working block outputStreamLineCount }); outputStream << workingBlock; outputStreamLineCount += workingBlockLineCount; if (requiresPrefix) { if (!workingBlock.IsEmpty()) { outputStream << MakeStringSection(workingBlock.end(), lineDetails._firstNonCommentNonWhitespaceChar) << std::endl; } else { outputStream << MakeStringSection(lineDetails._line.begin(), lineDetails._firstNonCommentNonWhitespaceChar) << std::endl; } ++outputStreamLineCount; } } workingBlockLineCount = 0; workingBlock = {}; appendLineToWorkingBlock = false; // (don't append this line, because we've just used it as an include */ // We must expand out this include... char resolvedFN[MaxPath]; searchRules.ResolveFile(resolvedFN, includeFile); auto subFile = ::Assets::MainFileSystem::OpenFileInterface(resolvedFN, "rb"); subFile->Seek(0, OSServices::FileSeekAnchor::End); auto subFileLength = subFile->TellP(); subFile->Seek(0); std::string buffer; buffer.resize(subFileLength); subFile->Read(AsPointer(buffer.begin()), subFileLength); auto expanded = ExpandIncludes( MakeStringSection(buffer), resolvedFN, ::Assets::DefaultDirectorySearchRules(resolvedFN)); if (!expanded._processedSource.empty()) { for (const auto&l:expanded._lineMarkers) result._lineMarkers.push_back( RenderCore::ILowLevelCompiler::SourceLineMarker { l._sourceName, l._sourceLine, outputStreamLineCount + l._processedSourceLine }); outputStream << expanded._processedSource; outputStreamLineCount += expanded._processedSourceLineCount; // Some expanded files might not end in a new line; so append one if needed if (!expanded._processedSource.empty() && *(expanded._processedSource.end()-1) != '\n' && *(expanded._processedSource.end()-1) != '\r') { outputStream << std::endl; outputStreamLineCount ++; } } // todo -- search for duplicates in the dependencies result._dependencies.insert( result._dependencies.end(), expanded._dependencies.begin(), expanded._dependencies.end()); result._dependencies.push_back({resolvedFN, subFile->GetSnapshot()}); } } } // either append to, or construct the working block -- if (appendLineToWorkingBlock) { if (!workingBlock.IsEmpty()) { workingBlock._end = lineDetails._nextLineBegin; } else { workingBlockStartLineIndex = sourceLineIndex; workingBlock = MakeStringSection(lineDetails._line.begin(), lineDetails._nextLineBegin); } // This condition is to avoid an issue counting lines if there is no newline at the end of the // file. The line count is actually the number of newlines in the text -- so if the final // line doesn't end in a new line, we don't count it. In the extreme case, for a file with // no new lines at all, we actually return a line count of 0 if (lineDetails._line.end() != lineDetails._nextLineBegin) ++workingBlockLineCount; } ++sourceLineIndex; prevLineType = lineDetails._type; i = lineDetails._nextLineBegin; } // Append the last fragment from the working block -- if (!workingBlock.IsEmpty()) { result._lineMarkers.push_back( RenderCore::ILowLevelCompiler::SourceLineMarker { srcName, workingBlockStartLineIndex, outputStreamLineCount }); outputStream << workingBlock; outputStreamLineCount += workingBlockLineCount; } result._processedSource = outputStream.str(); result._processedSourceLineCount = outputStreamLineCount; return result; } uint64_t ManualSelectorFiltering::GetHash() const { if (!_hash) GenerateHash(); return _hash; } void ManualSelectorFiltering::GenerateHash() const { _hash = HashCombine(_setValues.GetHash(), _setValues.GetParameterNamesHash()); for (const auto&r:_relevanceMap) _hash = Hash64(r.first, Hash64(r.second, _hash)); } ManualSelectorFiltering::ManualSelectorFiltering(Formatters::TextInputFormatter<>& formatter) { while (formatter.PeekNext() == Formatters::FormatterBlob::KeyedItem || formatter.PeekNext() == Formatters::FormatterBlob::Value) { if (formatter.PeekNext() == Formatters::FormatterBlob::Value) { // a selector name alone becomes a whitelist setting auto selectorName = RequireStringValue(formatter); _relevanceMap[selectorName.AsString()] = "1"; } else { auto selectorName = RequireKeyedItem(formatter); if (formatter.PeekNext() == Formatters::FormatterBlob::BeginElement) { RequireBeginElement(formatter); for (;;) { if (formatter.PeekNext() == Formatters::FormatterBlob::EndElement) break; auto filterType = RequireKeyedItem(formatter); auto value = RequireStringValue(formatter); if (XlEqStringI(filterType, "relevance")) { _relevanceMap[selectorName.AsString()] = value.AsString(); } else if (XlEqStringI(filterType, "set")) { _setValues.SetParameter(selectorName, value); } else { Throw(Formatters::FormatException("Expecting \"whitelist\", \"blacklist\" or \"set\"", formatter.GetLocation())); } } RequireEndElement(formatter); } else { auto value = RequireStringValue(formatter); _setValues.SetParameter(selectorName, value); } } } if (formatter.PeekNext() != Formatters::FormatterBlob::EndElement && formatter.PeekNext() != Formatters::FormatterBlob::None) Throw(Formatters::FormatException("Unexpected blob when deserializing selector filtering", formatter.GetLocation())); GenerateHash(); } void ManualSelectorFiltering::MergeIn(const ManualSelectorFiltering& src) { _setValues.MergeIn(src._setValues); for (const auto&i:src._relevanceMap) _relevanceMap[i.first] = i.second; GenerateHash(); } ManualSelectorFiltering::ManualSelectorFiltering() = default; ManualSelectorFiltering::~ManualSelectorFiltering() = default; ParameterBox FilterSelectors( IteratorRange<const ParameterBox* const*> selectors, const std::unordered_map<std::string, std::string>& manualRevelanceMap, IteratorRange<const SelectorFilteringRules**> automaticFiltering) { assert(!selectors.empty()); ParameterBox filteredBox = **selectors.begin(); for (auto i=selectors.begin()+1; i!=selectors.end(); ++i) filteredBox.MergeIn(**i); if (filteredBox.GetCount() == 0) return filteredBox; // We have to do the evaluation one at a time, updating the filteredBox as we go, // because of mutual relationships between selectors. For example, in construction // #if !defined(SEL_0) || !defined(SEL_1) // if both SEL_0 and SEL_1 are defined, we have to be careful not to consider both // irrelevant for (ptrdiff_t c=filteredBox.GetCount()-1; c>=0;) { auto evaluating = filteredBox.at(c); bool relevant = false; // If we're listed in the technique filtering relevance map, then we treat that as an override // of the automatic filtering auto relevanceI = manualRevelanceMap.find(evaluating->Name().AsString()); if (relevanceI != manualRevelanceMap.end()) { // Set a key called "value" to the new value we want to set ParameterBox pBoxValue; pBoxValue.SetParameter("value", evaluating->RawValue(), evaluating->Type()); const ParameterBox* boxes[] = { &pBoxValue, &filteredBox }; relevant = EvaluatePreprocessorExpression(relevanceI->second, MakeIteratorRange(boxes)); } else { const ParameterBox* env[] = { &filteredBox }; for (const auto*f:automaticFiltering) if ((relevant = f->IsRelevant(evaluating->Name(), evaluating->ValueAsString(), MakeIteratorRange(env)))) break; } if (!relevant) filteredBox.RemoveParameter(evaluating->HashName()); --c; // dec idx in either case } return filteredBox; } ParameterBox FilterSelectors( const ParameterBox& selectors, const ManualSelectorFiltering& manualFiltering, const SelectorFilteringRules& automaticFiltering) { const ParameterBox* boxes[] = { &manualFiltering.GetSetSelectors(), &selectors }; const SelectorFilteringRules* filtering[] = { &automaticFiltering }; return FilterSelectors(MakeIteratorRange(boxes), manualFiltering.GetRelevanceMap(), MakeIteratorRange(filtering)); } }
[ "djewsbury@gmail.com" ]
djewsbury@gmail.com
20e9f2af4d7cc85564451664cc93740f15015966
e62e37b1bb4fff2accbf238e59e709b92313237d
/gazebo_plugins/src/gazebo_ros_projector.cpp
fc4ef5fca93b137843afba114510c3704a53e414
[]
no_license
pohzhiee/gazebo_ros_pkgs
0dcc5f853c5418ab5d333b1963441096f676e539
65a1c3bbcdb886d70e11cb68d212101dc96ceda3
refs/heads/dashing
2020-07-23T03:32:46.546848
2019-09-25T02:25:09
2019-09-25T02:25:09
207,434,742
0
0
null
2019-09-25T02:25:10
2019-09-10T01:04:59
null
UTF-8
C++
false
false
3,432
cpp
// Copyright 2019 Open Source Robotics Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * \brief Switch for Gazebo Texture Projector * * \author Jared Duke * * \date 17 Jun 2010 */ #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <gazebo/transport/transport.hh> #include <gazebo_plugins/gazebo_ros_projector.hpp> #include <gazebo_ros/node.hpp> #include <std_msgs/msg/bool.hpp> #include <memory> #include <string> namespace gazebo_plugins { class GazeboRosProjectorPrivate { public: /// Callback for switching the projector on/off /// \param[in] msg Bool switch message void ToggleProjector(std_msgs::msg::Bool::SharedPtr msg); /// A pointer to the GazeboROS node. gazebo_ros::Node::SharedPtr ros_node_; /// Gazebo node used to talk to projector gazebo::transport::NodePtr gazebo_node_; /// Publisher for gazebo projector gazebo::transport::PublisherPtr projector_pub_; /// Subscriber to projector switch rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr toggle_sub_; }; GazeboRosProjector::GazeboRosProjector() : impl_(std::make_unique<GazeboRosProjectorPrivate>()) { } GazeboRosProjector::~GazeboRosProjector() { } void GazeboRosProjector::Load(gazebo::physics::ModelPtr _model, sdf::ElementPtr _sdf) { // Initialize ROS node impl_->ros_node_ = gazebo_ros::Node::Get(_sdf); // Create gazebo transport node impl_->gazebo_node_ = boost::make_shared<gazebo::transport::Node>(); impl_->gazebo_node_->Init(_model->GetWorld()->Name()); auto link_name = _sdf->Get<std::string>("projector_link", "projector_link").first; auto projector_name = _sdf->Get<std::string>("projector_name", "projector").first; // Setting projector topic auto name = "~/" + _model->GetName() + "/" + link_name + "/" + projector_name; // Create a Gazebo publisher to switch the projector impl_->projector_pub_ = impl_->gazebo_node_->Advertise<gazebo::msgs::Projector>(name); RCLCPP_INFO(impl_->ros_node_->get_logger(), "Controlling projector at [%s]", impl_->projector_pub_->GetTopic().c_str()); impl_->toggle_sub_ = impl_->ros_node_->create_subscription<std_msgs::msg::Bool>( "switch", rclcpp::QoS(rclcpp::KeepLast(1)), std::bind(&GazeboRosProjectorPrivate::ToggleProjector, impl_.get(), std::placeholders::_1)); RCLCPP_INFO(impl_->ros_node_->get_logger(), "Subscribed to [%s]", impl_->toggle_sub_->get_topic_name()); } void GazeboRosProjectorPrivate::ToggleProjector(const std_msgs::msg::Bool::SharedPtr switch_msg) { if (switch_msg->data) { RCLCPP_INFO(ros_node_->get_logger(), "Switching on projector"); } else { RCLCPP_INFO(ros_node_->get_logger(), "Switching off projector"); } gazebo::msgs::Projector msg; msg.set_name("texture_projector"); msg.set_enabled(switch_msg->data); projector_pub_->Publish(msg); } GZ_REGISTER_MODEL_PLUGIN(GazeboRosProjector) } // namespace gazebo_plugins
[ "louise@openrobotics.org" ]
louise@openrobotics.org
570e1e0eb7cff6c5fa4fd58ea0dd114e4acf81f1
264cc9ec8e4c34022a16e75d14c5343324bdc643
/dinamico.h
16ae8b419ddc2320c4bffb0b6026600fe65ea668
[ "MIT" ]
permissive
lsfcin/anikillerscin
dbc440a725566ee252a69e294d9ecc459bccc60a
8bbd1024fdf0d0b0bd815b2615faed02e1d07fe4
refs/heads/master
2021-08-22T16:55:07.035718
2017-11-30T18:00:03
2017-11-30T18:00:03
112,641,473
0
0
null
null
null
null
ISO-8859-1
C++
false
false
820
h
#ifndef DINAMICO_H #define DINAMICO_H #include "objeto3D.h" class Dinamico : public Objeto3D{ public: //parte física float massa; Vetor *aceleracao; Vetor *velocidade; float acel; float freio; float resistencia; float velocidadeMaxima; float velocidadeMinima; public: Dinamico(); Dinamico(Ponto *centro, Vetor *n, Vetor *v, float massa, float acelerar, float velocidadeMaxima, float velocidadeMinima, float dN , float dV , float dU); ~Dinamico(); Ponto centroDeMassa(const Dinamico &d); void acelerar(); void freiar(); void darRe(); void passivo(); bool repouso(); bool mProgressivo(); bool mRetrogrado() const; //virtual void update(bool cima, bool baixo, bool esquerda, bool direita, bool metralhadora, bool mina/*, bool teleguiado*/) = 0; virtual void draw() = 0; }; #endif
[ "lsf@cin.ufpe.br" ]
lsf@cin.ufpe.br
be60e332ef1d3d4dd84573c4904f43b634d961af
6ce22059ff64ecf67d7f4ff29b26d3f1de063f8e
/plugins/EstimationPlugin/src/base/measurement/MeasurementModelBase.cpp
567fe27dcdab68a0dd09aa44cc58ffb54df14cc7
[ "Apache-2.0" ]
permissive
spacecraft-ai/GMAT-R2016a
dec5e0124369bb3642d29d339fc267f991362b04
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
refs/heads/master
2021-01-23T12:47:19.009911
2017-06-05T08:24:32
2017-06-05T08:24:32
93,201,082
1
3
null
null
null
null
UTF-8
C++
false
false
1,456
cpp
//$Id$ //------------------------------------------------------------------------------ // MeasurementModelBase //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/06/24 // /** * MeasurementModelBase declaration used in GMAT's estimator and simulator * factory code */ //------------------------------------------------------------------------------ #include "MeasurementModelBase.hpp" MeasurementModelBase::MeasurementModelBase(const std::string& name, const std::string& typeName) : GmatBase (Gmat::MEASUREMENT_MODEL, typeName, name) { } MeasurementModelBase::~MeasurementModelBase() { } MeasurementModelBase::MeasurementModelBase(const MeasurementModelBase& mm) : GmatBase (mm) { } MeasurementModelBase& MeasurementModelBase::operator=( const MeasurementModelBase& mm) { if (this != &mm) GmatBase::operator=(mm); return *this; } Integer MeasurementModelBase::GetParmIdFromEstID(Integer id, GmatBase* obj) { return id - obj->GetType() * 250; }
[ "eabesea@rambler.ru" ]
eabesea@rambler.ru
f8dd5e0b21a4c5cd7c02609157b52e08daed06aa
d4c74a8001451840f3efb87f15856cdb9d5e9eb6
/rtos/mbed-os/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NORDIC_SOFTDEVICE/TARGET_NRF52/source/nRF5xPalSecurityManager.h
4a31345b854dd083940d5803dd7a6486cf2d023a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
danieldennett/gap_sdk
3e4b4d187f03a28a761b08aed36a5e6a06f48e8d
5667c899025a3a152dbf91e5c18e5b3e422d4ea6
refs/heads/master
2020-12-19T19:17:40.083131
2020-02-27T14:51:48
2020-02-27T14:51:48
235,814,026
1
0
Apache-2.0
2020-01-23T14:39:59
2020-01-23T14:39:58
null
UTF-8
C++
false
false
10,491
h
/* mbed Microcontroller Library * Copyright (c) 2018-2018 ARM Limited * * 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 NRF5X_PAL_SECURITY_MANAGER_ #define NRF5X_PAL_SECURITY_MANAGER_ #include "ble/BLETypes.h" #include "ble/pal/PalSecurityManager.h" #include "nrf_ble.h" #include "nRF5xCrypto.h" namespace ble { namespace pal { namespace vendor { namespace nordic { template <class EventHandler> class nRF5xSecurityManager : public ::ble::pal::SecurityManager<nRF5xSecurityManager<EventHandler>, EventHandler> { public: typedef ::ble::pal::SecurityManager< nRF5xSecurityManager<EventHandler>, EventHandler > Base; nRF5xSecurityManager(); ~nRF5xSecurityManager(); //////////////////////////////////////////////////////////////////////////// // SM lifecycle management // /** * @see ::ble::pal::SecurityManager::initialize */ ble_error_t initialize_(); /** * @see ::ble::pal::SecurityManager::terminate */ ble_error_t terminate_(); /** * @see ::ble::pal::SecurityManager::reset */ ble_error_t reset_() ; //////////////////////////////////////////////////////////////////////////// // Resolving list management // /** * @see ::ble::pal::SecurityManager::read_resolving_list_capacity */ uint8_t read_resolving_list_capacity_(); /** * @see ::ble::pal::SecurityManager::add_device_to_resolving_list */ ble_error_t add_device_to_resolving_list_( advertising_peer_address_type_t peer_identity_address_type, const address_t &peer_identity_address, const irk_t &peer_irk ); /** * @see ::ble::pal::SecurityManager::remove_device_from_resolving_list */ ble_error_t remove_device_from_resolving_list_( advertising_peer_address_type_t peer_identity_address_type, const address_t &peer_identity_address ); /** * @see ::ble::pal::SecurityManager::clear_resolving_list */ ble_error_t clear_resolving_list_(); /** * Return the IRKs present in the resolving list * @param count The number of entries present in the resolving list. * @param pointer to the first entry of the resolving list. */ ArrayView<ble_gap_id_key_t> get_resolving_list(); //////////////////////////////////////////////////////////////////////////// // Pairing // /** * @see ::ble::pal::SecurityManager::send_pairing_request */ ble_error_t send_pairing_request_( connection_handle_t connection, bool oob_data_flag, AuthenticationMask authentication_requirements, KeyDistribution initiator_dist, KeyDistribution responder_dist ); /** * @see ::ble::pal::SecurityManager::send_pairing_response */ ble_error_t send_pairing_response_( connection_handle_t connection, bool oob_data_flag, AuthenticationMask authentication_requirements, KeyDistribution initiator_dist, KeyDistribution responder_dist ); /** * @see ::ble::pal::SecurityManager::cancel_pairing */ ble_error_t cancel_pairing_( connection_handle_t connection, pairing_failure_t reason ); //////////////////////////////////////////////////////////////////////////// // Feature support // /** * @see ::ble::pal::SecurityManager::get_secure_connections_support */ ble_error_t get_secure_connections_support_( bool &enabled ); /** * @see ::ble::pal::SecurityManager::set_io_capability */ ble_error_t set_io_capability_(io_capability_t io_capability); //////////////////////////////////////////////////////////////////////////// // Security settings // /** * @see ::ble::pal::SecurityManager::set_authentication_timeout */ ble_error_t set_authentication_timeout_( connection_handle_t, uint16_t timeout_in_10ms ); /** * @see ::ble::pal::SecurityManager::get_authentication_timeout */ ble_error_t get_authentication_timeout_( connection_handle_t, uint16_t &timeout_in_10ms ); /** * @see ::ble::pal::SecurityManager::set_encryption_key_requirements */ ble_error_t set_encryption_key_requirements_( uint8_t min_encryption_key_size, uint8_t max_encryption_key_size ); /** * @see ::ble::pal::SecurityManager::slave_security_request */ ble_error_t slave_security_request_( connection_handle_t connection, AuthenticationMask authentication ); //////////////////////////////////////////////////////////////////////////// // Encryption // /** * @see ::ble::pal::SecurityManager::enable_encryption */ ble_error_t enable_encryption_( connection_handle_t connection, const ltk_t &ltk, const rand_t &rand, const ediv_t &ediv, bool mitm ); /** * @see ::ble::pal::SecurityManager::enable_encryption */ ble_error_t enable_encryption_( connection_handle_t connection, const ltk_t &ltk, bool mitm ) ; /** * @see ::ble::pal::SecurityManager::encrypt_data */ ble_error_t encrypt_data_( const byte_array_t<16> &key, encryption_block_t &data ); //////////////////////////////////////////////////////////////////////////// // Privacy // /** * @see ::ble::pal::SecurityManager::set_private_address_timeout */ ble_error_t set_private_address_timeout_(uint16_t timeout_in_seconds); //////////////////////////////////////////////////////////////////////////// // Keys // /** * @see ::ble::pal::SecurityManager::set_ltk */ ble_error_t set_ltk_( connection_handle_t connection, const ltk_t &ltk, bool mitm, bool secure_connections ); /** * @see ::ble::pal::SecurityManager::set_ltk_not_found */ ble_error_t set_ltk_not_found_( connection_handle_t connection ); /** * @see ::ble::pal::SecurityManager::set_irk */ ble_error_t set_irk_(const irk_t &irk); /** * @see ::ble::pal::SecurityManager::set_csrk */ ble_error_t set_csrk_(const csrk_t &csrk, sign_count_t sign_counter); /** * @see ::ble::pal::SecurityManager::set_peer_csrk */ ble_error_t set_peer_csrk_( connection_handle_t connection, const csrk_t &csrk, bool authenticated, sign_count_t sign_counter ); /** * @see ::ble::pal::SecurityManager::remove_peer_csrk */ ble_error_t remove_peer_csrk_(connection_handle_t connection); //////////////////////////////////////////////////////////////////////////// // Authentication // /** * @see ::ble::pal::SecurityManager::get_random_data */ ble_error_t get_random_data_(byte_array_t<8> &random_data); //////////////////////////////////////////////////////////////////////////// // MITM // /** * @see ::ble::pal::SecurityManager::set_display_passkey */ ble_error_t set_display_passkey_(passkey_num_t passkey); /** * @see ::ble::pal::SecurityManager::passkey_request_reply */ ble_error_t passkey_request_reply_( connection_handle_t connection, passkey_num_t passkey ); /** * @see ::ble::pal::SecurityManager::secure_connections_oob_request_reply */ ble_error_t secure_connections_oob_request_reply_( connection_handle_t connection, const oob_lesc_value_t &local_random, const oob_lesc_value_t &peer_random, const oob_confirm_t &peer_confirm ); /** * @see ::ble::pal::SecurityManager::legacy_pairing_oob_request_reply */ ble_error_t legacy_pairing_oob_request_reply_( connection_handle_t connection, const oob_tk_t &oob_data ); /** * @see ::ble::pal::SecurityManager::confirmation_entered */ ble_error_t confirmation_entered_( connection_handle_t connection, bool confirmation ); /** * @see ::ble::pal::SecurityManager::send_keypress_notification */ ble_error_t send_keypress_notification_( connection_handle_t connection, Keypress_t keypress ); /** * @see ::ble::pal::SecurityManager::generate_secure_connections_oob */ ble_error_t generate_secure_connections_oob_(); // singleton of nordic Security Manager static nRF5xSecurityManager& get_security_manager(); // Event handler bool sm_handler(const ble_evt_t *evt); private: csrk_t _csrk; sign_count_t _sign_counter; io_capability_t _io_capability; uint8_t _min_encryption_key_size; uint8_t _max_encryption_key_size; struct pairing_control_block_t; ble_gap_sec_params_t make_security_params( bool oob_data_flag, AuthenticationMask authentication_requirements, KeyDistribution initiator_dist, KeyDistribution responder_dist ); ble_gap_sec_keyset_t make_keyset( pairing_control_block_t& pairing_cb, KeyDistribution initiator_dist, KeyDistribution responder_dist ); pairing_control_block_t* allocate_pairing_cb(connection_handle_t connection); void release_pairing_cb(pairing_control_block_t* pairing_cb); pairing_control_block_t* get_pairing_cb(connection_handle_t connection); void release_all_pairing_cb(); pairing_control_block_t* _control_blocks; #if defined(MBEDTLS_ECDH_C) ble::public_key_coord_t X; ble::public_key_coord_t Y; ble::public_key_coord_t secret; #endif static const size_t MAX_RESOLVING_LIST_ENTRIES = BLE_GAP_DEVICE_IDENTITIES_MAX_COUNT; size_t resolving_list_entry_count; ble_gap_id_key_t resolving_list[MAX_RESOLVING_LIST_ENTRIES]; }; } // nordic } // vendor } // pal } // ble #endif /* NRF5X_PAL_SECURITY_MANAGER_ */
[ "noreply@github.com" ]
noreply@github.com
a80573e66d0158d243710f4ad1a33ad1b81c6834
2ef6a773dd5288e6526b70e484fb0ec0104529f4
/poj.org/2356/1419299_AC_30MS_124K.cpp
12b3342deb6c6c341c97f3bb08f6e7f4ccf81d21
[]
no_license
thebeet/online_judge_solution
f09426be6b28f157b1e5fd796c2eef99fb9978d8
7e8c25ff2e1f42cc9835e9cc7e25869a9dbbc0a1
refs/heads/master
2023-08-31T15:19:26.619898
2023-08-28T10:51:24
2023-08-28T10:51:24
60,448,261
1
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
#include <stdio.h> #include <memory.h> int main() { long i,n,ss,j; long s[10002]; long m[10002]; scanf("%d",&n); ss=0; memset(s,0,sizeof(s)); for (i=1;i<=n;i++) { scanf("%d",&m[i]); ss=(ss+m[i])%n; if (ss==0) { printf("%d\n",i); for (j=1;j<=i;j++) printf("%d\n",m[j]); return 0; } if (s[ss]>0) { printf("%d\n",i-s[ss]); for (j=s[ss]+1;j<=i;j++) printf("%d\n",m[j]); return 0; } s[ss]=i; } }
[ "项光特" ]
项光特
1979df2940f34bcecfb172d3f260c528857448b8
fdf9c72873625e6322e3ca0b32aa16f11023b5dc
/c++_code/class_a_memory/string1/string1.cpp
0a153be0487013e712c9c8ecda83b04f2e589f33
[]
no_license
LearnerYu3/Learn_Cpp
ecfc903904fe80420728fc8fdace07bf33bbb5f0
69caaf867e0dbfd3ba407a3d6be47fe4e909a785
refs/heads/master
2023-07-11T23:50:17.091930
2021-08-18T03:51:00
2021-08-18T03:51:00
397,455,721
0
0
null
null
null
null
UTF-8
C++
false
false
1,547
cpp
#include<cstring> #include "string1.h" using std::cin; using std::cout; int String::num_strings = 0; int String::HowMany() { return num_strings; } String::String(const char * s) { len = std::strlen(s); str = new char[len + 1]; std::strcpy(str, s); num_strings++; } String::String() { len = 4; str = new char[1]; str[0] = '\0'; num_strings++; } String::String(const String & st) { num_strings++; len = st.len; str = new char[len + 1]; std::strcpy(str, st.str); } String::~String() { --num_strings; delete [] str; } String & String::operator=(const String & st) { if (this == &st) return *this; delete [] str; len = st.len; str = new char[len + 1]; std::strcpy(str, st.str); return *this; } String & String::operator=(const char * s) { delete [] str; len = std::strlen(s); str = new char[len + 1]; std::strcpy(str, s); return *this; } char & String::operator[](int i) { return str[i]; } const char & String::operator[](int i) const { return str[i]; } bool operator<(const String &st1, const String &st2) { return (std::strcmp(st1.str, st2.str) < 0); } bool operator>(const String &st1, const String &st2) { return st2 < st1; } bool operator==(const String &st1, const String &st2) { return (std::strcmp(st1.str, st2.str) == 0); } ostream & operator<<(ostream & os, const String & st) { os << st.str; return os; } istream & operator>>(istream & is, String & st) { char temp[String::CINLM]; is.get(temp, String::CINLM); if (is) st = temp; while (is && is.get() != '\n') continue; return is; }
[ "1330286215@qq.com" ]
1330286215@qq.com
31ce6562e120d2eb8c4f2f9fbb3e1c07fadf916b
011b645acd7d600922209d1741fa79e8110e1270
/Harjoitus 17.cpp
10e78fcb75c5e0f3754be6675b95db0ab9ba9e50
[]
no_license
Tapsa93/harjoitus-17
ae203bf2b089f8755fbf92b96db9621a3366d6a6
822b335a4ed89687538763fe2bceaf7d8f1195da
refs/heads/master
2020-05-29T11:44:57.639117
2014-11-13T10:31:45
2014-11-13T10:31:45
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,267
cpp
/*Muokkaa edellistä ohjelmaa siten, että edellä määriteltyä tietuetyyppiä käytetään myäs kahden muun "koululaisen" tietojen tallentamiseen. Näiden kahden muun koululaisen tiedot alustetaan ao.muuttujien määrittelyn yhteydessä. Ainoastaan yhden koululaisen tiedot kysytään käyttäjältä edellisen tehtävän tapaan. Tulosta kolmen koululaisen tiedot koulumatkan mukaisessa suuruusjärjestyksessä(pienimmästä suurimpaan) näytälle*/ #include <iostream> using namespace std; #include <cstring> struct hlöt { char etunimi[20]; int kengannumero; char sukunimi[15]; float koulumatka; char osoite[30]; int postinumero; }; int main() { hlöt i[4] = { { "Mikki", 33, "Hiiri", 5.4, "Hiirikatu 2", 40200 }, { "Mestari", 44, "Mies", 10.4, "Mestarinkatu", 40400 } }; cout << "Anna kaikki Etunimesi, kengannumero, sukunimi, koulumatkan pituus, osoite ja postinumero.""(Etunimien/etunimen ja osoitteen jälkeen, paina ENTER, muulloin välilyöntiä)"; cin.get(i[2].etunimi, 20) >> ws >> i[2].kengannumero >> ws >> i[2].sukunimi >> ws >> i[2].koulumatka; cin.get(i[2].osoite, 30) >> ws >> i[2].postinumero; if (i[0].koulumatka > i[1].koulumatka) { i[3] = i[0]; i[0] = i[1]; i[1] = i[3]; } if (i[0].koulumatka>i[2].koulumatka) { i[3] = i[0]; i[0] = i[2]; i[2] = i[3]; } if (i[1].koulumatka>i[2].koulumatka) { i[3] = i[1]; i[1] = i[2]; i[2] = i[3]; } cout << "\nTiedot suuruusjärjestyksessä: " << endl; cout << "\nNimesi " << i[0].etunimi << " " << i[0].sukunimi; cout << "\nKengannumero " << i[0].kengannumero; cout << "\nKoulumatkan pituus " << i[0].koulumatka; cout << "\nOsoitteesi " << i[0].osoite; cout << "\nPostinumero " << i[0].postinumero << endl; cout << "\nNimesi " << i[1].etunimi << " " << i[1].sukunimi; cout << "\nKengannumero " << i[1].kengannumero; cout << "\nKoulumatkan pituus " << i[1].koulumatka; cout << "\nOsoitteesi " << i[1].osoite; cout << "\nPostinumero " << i[1].postinumero<< endl; cout << "\nNimesi " << i[2].etunimi << " " << i[2].sukunimi; cout << "\nKengannumero " << i[2].kengannumero; cout << "\nKoulumatkan pituus " << i[2].koulumatka; cout << "\nOsoitteesi " << i[2].osoite; cout << "\nPostinumero " << i[2].postinumero << endl; return 0; }
[ "Tapio.pek@hotmail.com" ]
Tapio.pek@hotmail.com
9023f8d6a27f9262e0bab2efe214457670c68792
16cba4d029596dc9cb0bde4f2cc2ecdd77a63419
/Classes/lySDK/lyPay.h
dea56f8286d147b2ba998e752a41a73ecb64b53e
[]
no_license
shixc/lyGame
99482f745354bc9bd0cbb22be05fc340d148128f
1eadd7c1dab31930c7b9a9d540c190f4db598b85
refs/heads/master
2021-01-22T08:47:54.314033
2016-12-14T09:56:03
2016-12-14T09:56:03
81,913,626
0
1
null
null
null
null
UTF-8
C++
false
false
299
h
// // lyPay.h // ly-client // 登录管理类,从此调用sdk相关接口 // Created by loveyur on 2016/11/10 // #ifndef ly_lyPay_h #define ly_lyPay_h class lyPay { public: lyPay(); ~lyPay(); static lyPay* getInstance(); private: static lyPay *m_plyPay; }; #endif /* ly_lyPay_h */
[ "shixc0608@163.com" ]
shixc0608@163.com
9b857b67e057d3cb7687da0fcc8574a66e2d3752
012858ee0c5d612c96a6e179d52d6ec173f431de
/sort/bubble_sort.cpp
86dbf79a73b75e607b5fb57d1d9e444a48131f99
[]
no_license
aiemag/algorithm
5d89704f4b8514c50fcfd596e53b433c3666cd5d
bc3e577267f64a450397a4b1c389bae3744a0248
refs/heads/master
2020-12-05T12:56:04.903831
2020-10-19T10:21:38
2020-10-19T10:21:38
232,118,089
0
0
null
null
null
null
UTF-8
C++
false
false
437
cpp
#include <stdio.h> int n = 5; int a[5] = {3, 2, 4, 5, 1}; void do_bubble_sort() { int i, j, temp; for (i = n - 1; i > 0; i--) { for (j = 0; j < i; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j+1]; a[j + 1] = temp; } } } } void process() { do_bubble_sort(); } void output(void) { int i, j; for (i = 0; i < n; i++) { printf("%d ", a[i]); } puts(""); } int main(void) { process(); output(); }
[ "59533451+aiemag@users.noreply.github.com" ]
59533451+aiemag@users.noreply.github.com
4f52f92c5a71043ee36dc214d00c3fde57e951be
2d24dce18b849ab2206de7a8e560f2ca576bbb0b
/Source/GameEngine/Geometry.cpp
93c181e91f937e48b3316332be98b5a4dad86634
[]
no_license
timurrustamov/cpp_r-type
85ff98914f0a69bc899de0277e51ea4093d24647
21b8de3c3b5576b5fb98819a9ad873d52c4c5181
refs/heads/master
2021-01-10T02:38:20.466611
2016-01-07T00:09:01
2016-01-07T00:09:01
46,358,962
0
0
null
null
null
null
UTF-8
C++
false
false
5,070
cpp
// // Created by rustam_t on 11/24/15. // #include "Geometry.hpp" Geometry::Geometry(const Rectangle<float> &obj, float terminalVelocity, float inertiaRatio) : _object(NULL) { this->_innerObj = obj; this->_node = NULL; this->_terminalVelocity = terminalVelocity; this->_currentFrame = 0; this->_inertiaRatio = inertiaRatio <= 0 ? 0.001 : inertiaRatio; this->_velocity.setX(0).setY(0); this->_acceleration.setX(0).setY(0); int i = -1; while (++i < 10) this->_previousPosition[i] = obj.getPosition(); } Geometry &Geometry::operator=(const Geometry &geo){ this->_innerObj = geo._innerObj; this->_node = geo._node; this->_terminalVelocity = geo._terminalVelocity; this->_inertiaRatio = geo._inertiaRatio; this->_currentFrame = 0; this->_velocity = geo._velocity; this->_acceleration = geo._acceleration; this->_object = geo._object; int i = -1; while (++i < 10) this->_previousPosition[i] = geo._previousPosition[i]; return (*this); } Geometry::Geometry(const Geometry &geo) : _object(NULL) { this->_innerObj = geo._innerObj; this->_node = geo._node; this->_terminalVelocity = geo._terminalVelocity; this->_currentFrame = 0; this->_inertiaRatio = geo._inertiaRatio; this->_velocity = geo._velocity; this->_acceleration = geo._acceleration; int i = -1; while (++i < 10) this->_previousPosition[i] = geo._previousPosition[i]; } Geometry::~Geometry() { this->detach(); } Geometry & Geometry::tick(float delta_time) { t2Vector<float> acceleration; float step; this->_previousPosition[this->_currentFrame++ % 10] = this->_innerObj.getPosition(); if (this->_object && this->_object->timer.eventExists("acceleration")) { step = this->_object->timer.advancement("acceleration"); acceleration = this->_acceleration * (step * step * (3 - 2 * step)); this->_velocity += acceleration; if (this->_object->timer.eventDone("acceleration")) { this->_object->timer.removeEvent("acceleration"); this->_acceleration.setX(0).setY(0); } } if (this->_velocity != t2Vector<float>(0, 0)) this->_velocity -= (this->_velocity * this->_inertiaRatio * delta_time); if (this->_velocity.length() > this->_terminalVelocity) this->_velocity *= this->_terminalVelocity / this->_velocity.length(); this->_innerObj.position() += this->_velocity * delta_time; return (*this); } const Rectangle<float> & Geometry::getRect() const { return (this->_innerObj); } const t2Vector<int> Geometry::getSize() const { return (this->_innerObj.getSize()); } const t2Vector<float> Geometry::getPosition() const { return (this->_innerObj.getPosition()); } const t2Vector<float> Geometry::getAcceleration() const { return (this->_acceleration); } const t2Vector<float> Geometry::getVelocity() const { return (this->_velocity); } t2Vector<float> & Geometry::velocity() { return (this->_velocity); } float Geometry::getClockWiseAngle() const { if (this->_velocity == t2Vector<float>(0, 0)) return (0); t2Vector<float> normal(1, 1); return (this->_velocity.getAngleTo(normal)); } Geometry & Geometry::setRelativeAngle(float angle) { angle = 0.01745329252 * angle; float tempx = this->_velocity.getX(); this->_velocity.x() = this->_velocity.getX() * cosf(angle) - this->_velocity.getY() * sinf(angle); this->_velocity.y() = tempx * sinf(angle) + this->_velocity.getY() * cosf(angle); return (*this); } Geometry & Geometry::setClockWiseAngle(float angle) { this->setRelativeAngle(-this->getClockWiseAngle()).setRelativeAngle(angle); return (*this); } bool Geometry::isSimulating() const { return (this->_node != NULL); } Geometry & Geometry::attach(QuadTree *quadTree, bool forced) { if (forced) { this->_node = quadTree; return (*this); } if (this->_node == quadTree) return (*this); if (this->_node != NULL) this->_node->remove(this); this->_node = quadTree->insert(this); return (*this); } #include <stdio.h> Geometry & Geometry::attachToObject(Object *obj) { this->_object = obj; return (*this); } Object * Geometry::getObject() { return (this->_object); } Geometry & Geometry::detach() { if (this->_node != NULL) this->_node->remove(this); this->_node = NULL; return (*this); } Geometry & Geometry::hardDetach() { this->_node = NULL; return (*this); } QuadTree * Geometry::getNode() const { return (this->_node); } const t2Vector<float> & Geometry::getPreviousPosition(unsigned int pos) const { if (pos > 10) pos = 10; return (this->_previousPosition[(this->_currentFrame - 1 + pos) % 10]); } t2Vector<float> & Geometry::position() { return (this->_innerObj.position()); } float Geometry::getInertia() const { return (this->_inertiaRatio); } float Geometry::getMaxVelocity() const { return (this->_terminalVelocity); }
[ "timur.rustamov@epitech.eu" ]
timur.rustamov@epitech.eu
3f20d82a4863d47204dcfba8382ed0310d516a81
6abb92d99ff4218866eafab64390653addbf0d64
/AtCoder/othercontests/alc006/d2.cpp
d53e2873235d1a1eeae7e3c342a05072e75a3aa1
[]
no_license
Johannyjm/c-pro
38a7b81aff872b2246e5c63d6e49ef3dfb0789ae
770f2ac419b31bb0d47c4ee93c717c0c98c1d97d
refs/heads/main
2023-08-18T01:02:23.761499
2023-08-07T15:13:58
2023-08-07T15:13:58
217,938,272
0
0
null
2023-06-25T15:11:37
2019-10-28T00:51:09
C++
UTF-8
C++
false
false
808
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep1(i, n) for (int i = 1; i < (n); ++i) using namespace std; typedef long long ll; const ll INF = 1LL << 60; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; int sum = 0; int dig = 0; rep1(i, n){ sum += i; if(sum>=n) { dig = i; break; } } int sub = n-sum; rep(i, 1<<dig){ int cand = 0; rep(j, dig){ if(i &(1<<j)){ cand += j; } } if(cand==sub){ rep(j, dig){ if(i &(1<<j)){ cout << j << endl; } } } } return 0; }
[ "meetpastarts@gmail.com" ]
meetpastarts@gmail.com
77ab916b2d14decba9d01b5502527e0564d61fa1
f751871b350b5c391d1c7f57029655d558c5eab7
/src/test/sanity_tests.cpp
f18b6dceb3d8f2058aedd3dea98afb1660716722
[ "MIT" ]
permissive
vivocoin/vivo
9899cb3871b57a209669a0b78cbd7de7311804ea
fa7eaae9dc540537a230c67b2e2906738ac4b170
refs/heads/master
2021-05-06T00:45:17.381498
2020-09-29T16:41:11
2020-09-29T16:41:11
114,329,048
34
37
MIT
2019-06-25T23:47:40
2017-12-15T05:01:07
C++
UTF-8
C++
false
false
654
cpp
// Copyright (c) 2012-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 "compat/sanity.h" #include "key.h" #include "test/test_vivo.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test"); BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); } BOOST_AUTO_TEST_SUITE_END()
[ "vivocrypto@gmail.com" ]
vivocrypto@gmail.com
eeed6451ffe22b8f1a284eb12ab4d8b76c957a72
648e9398ca0037237057ee93841e4a357f4b18ee
/src/breakpoint/exemplar/src/shadj.cc
73950d7464b50bf8f217b8a1ff56515a06edb100
[]
no_license
shaomingfu/gredu
7f6d473b87191463dafbe19675c43b591bfc3e79
5ffcadda1b29347b3546fcacc1c49459127175e4
refs/heads/master
2020-12-24T20:51:41.570583
2019-01-30T05:35:42
2019-01-30T05:35:42
56,416,600
1
0
null
null
null
null
UTF-8
C++
false
false
1,211
cc
#include "shadj.h" #include <cassert> shadj::shadj() {} shadj::shadj(gene * _x1, gene * _x2, gene * _y1, gene * _y2) : x1(_x1), x2(_x2), y1(_y1), y2(_y2) { direction(); } bool shadj::direction() const { if(x1->x == y1->x && x2->x == y2->x) return true; else if(x1->x + y1->x == 0 && x2->x + y2->x == 0) return false; else assert(false); } bool shadj::adjacent() const { if(x1->b != x2) return false; bool b = direction(); if(b == true && y1->b == y2) return true; if(b == false && y2->b == y1) return true; return false; } bool shadj::conflict(const shadj & sa) const { assert(adjacent()); assert(sa.adjacent()); if(x1 == sa.x1 && y1 == sa.y1) return true; if(x1 == sa.x2 && y1 == sa.y2) return true; if(x2 == sa.x1 && y2 == sa.y1) return true; if(x2 == sa.x2 && y2 == sa.y2) return true; if(x1 == sa.x1 || x1 == sa.x2) return false; if(x2 == sa.x1 || x2 == sa.x2) return false; if(y1 == sa.y1 || y1 == sa.y2) return false; if(y2 == sa.y1 || y2 == sa.y2) return false; return true; } string shadj::print_string(map<gene*, int> & m) const { char s[10240]; sprintf(s, "(%7d[%7d], %7d[%7d]), (%7d[%7d], %7d[%7d])", m[x1], x1->x, m[x2], x2->x, m[y1], y1->x, m[y2], y2->x); return s; }
[ "shaomingfu@gmail.com" ]
shaomingfu@gmail.com
4517c49afff0fd01b8ed33781600c59740f418f2
c0830b5173ec67b39bf79429ee90d4936cd23e40
/include/state-observation/dynamical-system/dynamical-system-functor-base.hpp
122e51b510ebd8a51c8653f8cb975f6ea0eaf9e8
[]
no_license
stack-of-tasks/state-observation
58956a566958ccd1e57709969d1c450e4da479d2
38f8dd07fb69b18fd98858f094552d9ca75966b8
refs/heads/master
2021-01-16T23:48:23.380069
2017-04-25T13:18:24
2017-04-25T13:18:24
14,783,286
5
6
null
2017-04-25T13:18:25
2013-11-28T17:48:31
C++
UTF-8
C++
false
false
2,446
hpp
/** * \file dynamics-functor-base.hpp * \author Mehdi Benallegue * \date 2013 * \brief Gives the base class to be derived in order to define any * dynamics system. * * \details * * */ #ifndef STATEOBSERVERDYNAMICALSYSTEMFUNCTORBASE_H #define STATEOBSERVERDYNAMICALSYSTEMFUNCTORBASE_H #include <state-observation/tools/definitions.hpp> namespace stateObservation { /** * \class DynamicsFunctorBase * \brief * This is the base class of any functor that describes the dynamics * of the state and the measurement. * This class is to be derived in order to be given * to the Extended Kalman Filter. * */ class DynamicalSystemFunctorBase { public: DynamicalSystemFunctorBase(); virtual ~DynamicalSystemFunctorBase(); ///The function to oberload to describe the dynamics of the state virtual Vector stateDynamics (const Vector& x, const Vector& u, unsigned k)=0; ///The function to overload to describe the dynamics of the sensor (measurements) virtual Vector measureDynamics (const Vector& x, const Vector& u, unsigned k)=0; ///The method to overload if the functor needs to be reset when the ///Exteded Kalman filter is reset itself virtual void reset(){} ///gets the state size virtual unsigned getStateSize()const =0 ; ///gets the input size virtual unsigned getInputSize()const =0 ; ///gets the measurements size virtual unsigned getMeasurementSize() const=0; ///Gives a boolean answer on whether or not the vector is correctly sized to be a state vector virtual bool checkStateVector(const Vector &); ///Gives a boolean answer on whether or not the vector is correctly sized to be an input vector virtual bool checkInputvector(const Vector &); protected: inline void assertStateVector_(const Vector & v) { (void)v;//avoid warning BOOST_ASSERT(checkStateVector(v) && "ERROR: The state vector has the wrong size"); } inline void assertInputVector_(const Vector & v) { (void)v;//avoid warning BOOST_ASSERT(checkInputvector(v) && "ERROR: The input vector has the wrong size"); } private: }; } #endif // STATEOBSERVERDYNAMICSYSTEMFUNCTORBASE_H
[ "mehdi.benallegue@gmail.com" ]
mehdi.benallegue@gmail.com
d454824479b5b9300e57c1c6113b8d4a75b94607
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h
e03c82ab9eab723bf3363bd1dea595a50b60b9b2
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,249
h
// Copyright (c) 2012 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 UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_AURAX11_H_ #define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_AURAX11_H_ #include <memory> #include <set> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #if !(defined(OS_EMSCRIPTEN) && defined(DISABLE_PTHREADS)) #include "base/timer/timer.h" #endif #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/window_observer.h" #include "ui/base/cursor/cursor.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/events/event_constants.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/x/x11.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/x11_move_loop_delegate.h" namespace aura { namespace client { class DragDropClientObserver; class DragDropDelegate; } } namespace gfx { class ImageSkia; class Point; } namespace ui { class DropTargetEvent; class OSExchangeData; class OSExchangeDataProviderAuraX11; class SelectionFormatMap; } namespace views { class DesktopNativeCursorManager; class Widget; class X11MoveLoop; // Implements drag and drop on X11 for aura. On one side, this class takes raw // X11 events forwarded from DesktopWindowTreeHostLinux, while on the other, it // handles the views drag events. class VIEWS_EXPORT DesktopDragDropClientAuraX11 : public aura::client::DragDropClient, public aura::WindowObserver, public X11MoveLoopDelegate { public: DesktopDragDropClientAuraX11( aura::Window* root_window, views::DesktopNativeCursorManager* cursor_manager, ::Display* xdisplay, ::Window xwindow); ~DesktopDragDropClientAuraX11() override; // We maintain a mapping of live DesktopDragDropClientAuraX11 objects to // their ::Windows. We do this so that we're able to short circuit sending // X11 messages to windows in our process. static DesktopDragDropClientAuraX11* GetForWindow(::Window window); void Init(); // These methods handle the various X11 client messages from the platform. void OnXdndEnter(const XClientMessageEvent& event); void OnXdndLeave(const XClientMessageEvent& event); void OnXdndPosition(const XClientMessageEvent& event); void OnXdndStatus(const XClientMessageEvent& event); void OnXdndFinished(const XClientMessageEvent& event); void OnXdndDrop(const XClientMessageEvent& event); // Called when XSelection data has been copied to our process. void OnSelectionNotify(const XSelectionEvent& xselection); // Overridden from aura::client::DragDropClient: int StartDragAndDrop(const ui::OSExchangeData& data, aura::Window* root_window, aura::Window* source_window, const gfx::Point& screen_location, int operation, ui::DragDropTypes::DragEventSource source) override; void DragCancel() override; bool IsDragDropInProgress() override; void AddObserver(aura::client::DragDropClientObserver* observer) override; void RemoveObserver(aura::client::DragDropClientObserver* observer) override; // Overridden from aura::WindowObserver: void OnWindowDestroyed(aura::Window* window) override; // Overridden from X11WholeScreenMoveLoopDelegate: void OnMouseMovement(const gfx::Point& screen_point, int flags, base::TimeTicks event_time) override; void OnMouseReleased() override; void OnMoveLoopEnded() override; protected: // The following methods are virtual for the sake of testing. // Creates a move loop. virtual std::unique_ptr<X11MoveLoop> CreateMoveLoop( X11MoveLoopDelegate* delegate); // Finds the topmost X11 window at |screen_point| and returns it if it is // Xdnd aware. Returns NULL otherwise. virtual ::Window FindWindowFor(const gfx::Point& screen_point); // Sends |xev| to |xid|, optionally short circuiting the round trip to the X // server. virtual void SendXClientEvent(::Window xid, XEvent* xev); protected: Widget* drag_widget() { return drag_widget_.get(); } private: enum SourceState { // |source_current_window_| will receive a drop once we receive an // XdndStatus from it. SOURCE_STATE_PENDING_DROP, // The move looped will be ended once we receive XdndFinished from // |source_current_window_|. We should not send XdndPosition to // |source_current_window_| while in this state. SOURCE_STATE_DROPPED, // There is no drag in progress or there is a drag in progress and the // user has not yet released the mouse. SOURCE_STATE_OTHER, }; // Processes a mouse move at |screen_point|. void ProcessMouseMove(const gfx::Point& screen_point, unsigned long event_time); // Start timer to end the move loop if the target is too slow to respond after // the mouse is released. void StartEndMoveLoopTimer(); // Ends the move loop. void EndMoveLoop(); // When we receive an position x11 message, we need to translate that into // the underlying aura::Window representation, as moves internal to the X11 // window can cause internal drag leave and enter messages. void DragTranslate(const gfx::Point& root_window_location, std::unique_ptr<ui::OSExchangeData>* data, std::unique_ptr<ui::DropTargetEvent>* event, aura::client::DragDropDelegate** delegate); // Called when we need to notify the current aura::Window that we're no // longer dragging over it. void NotifyDragLeave(); // Converts our bitfield of actions into an Atom that represents what action // we're most likely to take on drop. ::Atom DragOperationToAtom(int drag_operation); // Converts a single action atom to a drag operation. ui::DragDropTypes::DragOperation AtomToDragOperation(::Atom atom); // During the blocking StartDragAndDrop() call, this converts the views-style // |drag_operation_| bitfield into a vector of Atoms to offer to other // processes. std::vector< ::Atom> GetOfferedDragOperations(); // This returns a representation of the data we're offering in this // drag. This is done to bypass an asynchronous roundtrip with the X11 // server. ui::SelectionFormatMap GetFormatMap() const; // Returns the modifier state for the most recent mouse move. This is done to // bypass an asynchronous roundtrip with the X11 server. int current_modifier_state() const { return current_modifier_state_; } // Handling XdndPosition can be paused while waiting for more data; this is // called either synchronously from OnXdndPosition, or asynchronously after // we've received data requested from the other window. void CompleteXdndPosition(::Window source_window, const gfx::Point& screen_point); void SendXdndEnter(::Window dest_window); void SendXdndLeave(::Window dest_window); void SendXdndPosition(::Window dest_window, const gfx::Point& screen_point, unsigned long event_time); void SendXdndDrop(::Window dest_window); // Creates a widget for the user to drag around. void CreateDragWidget(const gfx::ImageSkia& image); // Returns true if |image| has any visible regions (defined as having a pixel // with alpha > 32). bool IsValidDragImage(const gfx::ImageSkia& image); // A nested run loop that notifies this object of events through the // X11MoveLoopDelegate interface. std::unique_ptr<X11MoveLoop> move_loop_; aura::Window* root_window_; DesktopNativeCursorManager* cursor_manager_; ::Display* xdisplay_; ::Window xwindow_; // Target side information. class X11DragContext; std::unique_ptr<X11DragContext> target_current_context_; // The modifier state for the most recent mouse move. int current_modifier_state_ = ui::EF_NONE; // The Aura window that is currently under the cursor. We need to manually // keep track of this because Windows will only call our drag enter method // once when the user enters the associated X Window. But inside that X // Window there could be multiple aura windows, so we need to generate drag // enter events for them. aura::Window* target_window_ = nullptr; // Because Xdnd messages don't contain the position in messages other than // the XdndPosition message, we must manually keep track of the last position // change. gfx::Point target_window_location_; gfx::Point target_window_root_location_; // In the Xdnd protocol, we aren't supposed to send another XdndPosition // message until we have received a confirming XdndStatus message. bool waiting_on_status_ = false; // If we would send an XdndPosition message while we're waiting for an // XdndStatus response, we need to cache the latest details we'd send. std::unique_ptr<std::pair<gfx::Point, unsigned long>> next_position_message_; // Reprocesses the most recent mouse move event if the mouse has not moved // in a while in case the window stacking order has changed and // |source_current_window_| needs to be updated. base::OneShotTimer repeat_mouse_move_timer_; // When the mouse is released, we need to wait for the last XdndStatus message // only if we have previously received a status message from // |source_current_window_|. bool status_received_since_enter_ = false; // Source side information. ui::OSExchangeDataProviderAuraX11 const* source_provider_ = nullptr; ::Window source_current_window_ = x11::None; SourceState source_state_ = SOURCE_STATE_OTHER; // The current drag-drop client that has an active operation. Since we have // multiple root windows and multiple DesktopDragDropClientAuraX11 instances // it is important to maintain only one drag and drop operation at any time. static DesktopDragDropClientAuraX11* g_current_drag_drop_client; // The operation bitfield as requested by StartDragAndDrop. int drag_operation_ = 0; // We offer the other window a list of possible operations, // XdndActionsList. This is the requested action from the other window. This // is DRAG_NONE if we haven't sent out an XdndPosition message yet, haven't // yet received an XdndStatus or if the other window has told us that there's // no action that we can agree on. ui::DragDropTypes::DragOperation negotiated_operation_ = ui::DragDropTypes::DRAG_NONE; // Ends the move loop if the target is too slow to respond after the mouse is // released. base::OneShotTimer end_move_loop_timer_; // Widget that the user drags around. May be NULL. std::unique_ptr<Widget> drag_widget_; // The size of drag image. gfx::Size drag_image_size_; // The offset of |drag_widget_| relative to the mouse position. gfx::Vector2d drag_widget_offset_; base::WeakPtrFactory<DesktopDragDropClientAuraX11> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DesktopDragDropClientAuraX11); }; } // namespace views #endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_AURAX11_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
d6e4dc55fd8df22fe63470e59f8fc0f1524c8450
7c9a9687e84e0f9d8b5ce85174cea4bd8ec2e6d9
/Military Base/Military Base/Main.cpp
cb629b2435fa57a7541df0c0c830c6fd6497bd7f
[]
no_license
Saprsuu6/ForRapassing
fa53ed08acb1e4d20ecf54407b8b32130d90b414
f805cc6de751afbabe14fd6c0b2676d9a42e9315
refs/heads/main
2023-04-04T11:09:39.983754
2021-04-22T19:22:20
2021-04-22T19:22:20
360,657,494
0
0
null
null
null
null
IBM852
C++
false
false
784
cpp
#include "Header.h" int main() { srand(time(0)); const string classes[5] = { "Infantry", "Transport vehicle", "Heavy ground combat vehicles", "Light ground combat vehicles", "Air force", }; const int speed[5] = { 20, 70, 1550, 300 }; const int power[5] = { 10, 0, 150, 100 }; MilitaryShow* show = new MilitaryShow(); MilitaryBase* base = new MilitaryBase(); MilitaryFor˝e* forces = base->GetForces(); MilitaryFabric* fabric = new MilitaryFabric(); for (int i = 0; i < 5; i++) { forces[i] = *new MilitaryFor˝e(classes[i], speed[i], power[i], to_string(i), show); } for (int i = 0; i < 5; i++) { base->GetForces()[i].Show(i, i); } delete base; delete fabric; delete show; }
[ "coffeei.2002@gmail.com" ]
coffeei.2002@gmail.com
12642f512cd54bebddf43bb5e3df012a1179dcdc
7be6991d1cd04bba3078b5e2c11cb104974368ca
/ex04/NinjaTrap.hpp
371ab73c7f31ce0bec07cb30cb97d5f312ccda84
[]
no_license
axesthump/cpp03
05a8dab0ff6ddec252bb0b22366039a7fe026339
fe704b5290242bb11c77bdf47840e447a5a26e80
refs/heads/main
2023-01-20T18:42:54.456936
2020-12-01T06:17:14
2020-12-01T06:17:14
316,566,358
0
0
null
null
null
null
UTF-8
C++
false
false
551
hpp
// // Created by casubmar on 29.11.2020. // #ifndef EX03_NINJATRAP_HPP #define EX03_NINJATRAP_HPP #include "ClapTrap.hpp" #include "FragTrap.hpp" #include "ScavTrap.hpp" class NinjaTrap: virtual public ClapTrap { public: NinjaTrap(); NinjaTrap(std::string name); ~NinjaTrap(); NinjaTrap(NinjaTrap const& src); NinjaTrap& operator=(NinjaTrap const& rhs); void ninjaShoebox(ClapTrap& target); void ninjaShoebox(FragTrap& target); void ninjaShoebox(ScavTrap& target); void ninjaShoebox(NinjaTrap& target); }; #endif //EX03_NINJATRAP_HPP
[ "mrsalamon77@gmail.com" ]
mrsalamon77@gmail.com
2265f7809be2655dc10e0688e88922d165a72644
9a7e618304001fa2865c56a9acbaaa821a8e352b
/02 - Grundlagen/01_hello/src/ofApp.cpp
2149a4259d8010c7921f208395875420a4b075c9
[]
no_license
brinoausrino/FHD-MID18_Programmierung-1
b09f425e0469600edc88a5478b20d1eed3636104
3e2cd87e3518b226335c1953528fbfa4f72e36ed
refs/heads/master
2020-04-01T10:32:40.082896
2019-01-21T13:24:40
2019-01-21T13:24:40
153,121,617
1
4
null
2018-10-29T08:31:07
2018-10-15T13:51:13
null
UTF-8
C++
false
false
360
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofDrawBitmapString("Hallo du! Willkommen bei openFrameworks",20,50); }
[ "hi@brinoausrino.com" ]
hi@brinoausrino.com
c5ce0c0953dbad4336735f6c66cda4021aa8b1c8
04b1803adb6653ecb7cb827c4f4aa616afacf629
/extensions/renderer/file_system_natives.cc
2567f43d3005ba546659a92a80b2a16f020593c8
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,055
cc
// 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. #include "extensions/renderer/file_system_natives.h" #include <string> #include "base/bind.h" #include "extensions/common/constants.h" #include "extensions/renderer/script_context.h" #include "storage/common/fileapi/file_system_types.h" #include "storage/common/fileapi/file_system_util.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_dom_file_system.h" #include "third_party/blink/public/web/web_local_frame.h" #include "url/origin.h" namespace extensions { FileSystemNatives::FileSystemNatives(ScriptContext* context) : ObjectBackedNativeHandler(context) {} void FileSystemNatives::AddRoutes() { RouteHandlerFunction("GetFileEntry", base::BindRepeating(&FileSystemNatives::GetFileEntry, base::Unretained(this))); RouteHandlerFunction( "GetIsolatedFileSystem", base::BindRepeating(&FileSystemNatives::GetIsolatedFileSystem, base::Unretained(this))); RouteHandlerFunction( "CrackIsolatedFileSystemName", base::BindRepeating(&FileSystemNatives::CrackIsolatedFileSystemName, base::Unretained(this))); } void FileSystemNatives::GetIsolatedFileSystem( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 1 || args.Length() == 2); CHECK(args[0]->IsString()); v8::Isolate* isolate = args.GetIsolate(); std::string file_system_id(*v8::String::Utf8Value(isolate, args[0])); blink::WebLocalFrame* webframe = blink::WebLocalFrame::FrameForContext(context()->v8_context()); DCHECK(webframe); GURL context_url = extensions::ScriptContext::GetDocumentLoaderURLForFrame(webframe); CHECK(context_url.SchemeIs(extensions::kExtensionScheme)); const GURL origin(url::Origin::Create(context_url).Serialize()); std::string name(storage::GetIsolatedFileSystemName(origin, file_system_id)); // The optional second argument is the subfolder within the isolated file // system at which to root the DOMFileSystem we're returning to the caller. std::string optional_root_name; if (args.Length() == 2) { CHECK(args[1]->IsString()); optional_root_name = *v8::String::Utf8Value(isolate, args[1]); } GURL root_url(storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, optional_root_name)); args.GetReturnValue().Set( blink::WebDOMFileSystem::Create( webframe, blink::kWebFileSystemTypeIsolated, blink::WebString::FromUTF8(name), root_url) .ToV8Value(context()->v8_context()->Global(), isolate)); } void FileSystemNatives::GetFileEntry( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(5, args.Length()); CHECK(args[0]->IsString()); v8::Isolate* isolate = args.GetIsolate(); std::string type_string = *v8::String::Utf8Value(isolate, args[0]); blink::WebFileSystemType type; bool is_valid_type = storage::GetFileSystemPublicType(type_string, &type); DCHECK(is_valid_type); if (is_valid_type == false) { return; } CHECK(args[1]->IsString()); CHECK(args[2]->IsString()); CHECK(args[3]->IsString()); std::string file_system_name(*v8::String::Utf8Value(isolate, args[1])); GURL file_system_root_url(*v8::String::Utf8Value(isolate, args[2])); std::string file_path_string(*v8::String::Utf8Value(isolate, args[3])); base::FilePath file_path = base::FilePath::FromUTF8Unsafe(file_path_string); DCHECK(storage::VirtualPath::IsAbsolute(file_path.value())); CHECK(args[4]->IsBoolean()); blink::WebDOMFileSystem::EntryType entry_type = args[4].As<v8::Boolean>()->Value() ? blink::WebDOMFileSystem::kEntryTypeDirectory : blink::WebDOMFileSystem::kEntryTypeFile; blink::WebLocalFrame* webframe = blink::WebLocalFrame::FrameForContext(context()->v8_context()); DCHECK(webframe); args.GetReturnValue().Set( blink::WebDOMFileSystem::Create( webframe, type, blink::WebString::FromUTF8(file_system_name), file_system_root_url) .CreateV8Entry(blink::WebString::FromUTF8(file_path_string), entry_type, context()->v8_context()->Global(), args.GetIsolate())); } void FileSystemNatives::CrackIsolatedFileSystemName( const v8::FunctionCallbackInfo<v8::Value>& args) { DCHECK_EQ(args.Length(), 1); DCHECK(args[0]->IsString()); v8::Isolate* isolate = args.GetIsolate(); std::string filesystem_name = *v8::String::Utf8Value(isolate, args[0]); std::string filesystem_id; if (!storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id)) return; args.GetReturnValue().Set( v8::String::NewFromUtf8(isolate, filesystem_id.c_str(), v8::NewStringType::kNormal, filesystem_id.size()) .ToLocalChecked()); } } // namespace extensions
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
51633c552f6697979f2db6a626f0ef6bccb04f2c
fdf7d3360159a90d482035cd8935300343ecd3c9
/ProjectPOO/Gcommande.cpp
0b6ffc8f09d1bedad62886b04af355a91977609f
[]
no_license
dmohamed7/ProjectPOO
82e63b02c18e22526383c0fdea304e565e013b2c
74526ca306c4509d8239eb0bfb7335cf7a02cb9e
refs/heads/master
2023-02-01T12:51:17.431567
2020-12-06T17:32:55
2020-12-06T17:32:55
316,585,814
0
1
null
null
null
null
UTF-8
C++
false
false
24
cpp
#include "Gcommande.h"
[ "Mohamed.DIAG.dz@viacesi.fr" ]
Mohamed.DIAG.dz@viacesi.fr
3dd80518a0919bf74273aa8bb2f78d746d435a88
e6de52e23d02c1db23f83bb43e608f3a792601f3
/bullet.h
a3d5de657c7a88c79d4eb0d2115d4e4b1fe0cfbe
[]
no_license
hoooplaa/Engine
d9ef61e4cbc2ca962cb64c3892ba387b6efde2af
550c050d958b117edaadc4804b16f8d19f776f86
refs/heads/master
2023-02-27T03:06:02.657598
2021-02-02T20:08:27
2021-02-02T20:08:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
h
#pragma once #include "Object.h" #include "ObjectGuard.h" #include "Entity.h" #include <iostream> #include <SFML/Graphics.hpp> enum class eBulletStates { neutral, active, shot }; class Bullet : public Entity { public: Bullet(); ~Bullet(); void Initialize() override; void Destroy() override; void Update(const double in_dt) override; void Draw(std::shared_ptr<sf::RenderWindow> window) override; sf::Vector2f GetDirection() const { return m_direction; } eBulletStates GetState() const { return m_state; } std::shared_ptr<Entity> GetInstigator() const { return m_instigator; } void SetDirection(const sf::Vector2f& in_direction) { m_direction = in_direction; } void SetSpriteTexture(const sf::Texture& in_texture) { m_sprite.setTexture(in_texture); } void SetState(eBulletStates in_state) { m_state = in_state; } void SetInstigator(std::shared_ptr<Entity> in_entity) { m_instigator = in_entity; } private: sf::Vector2f m_direction; bool m_isActive = false; eBulletStates m_state = eBulletStates::neutral; std::shared_ptr<Entity> m_instigator; };
[ "alexanderh@friends-select.org" ]
alexanderh@friends-select.org
2b387e1aa310698fd0a857c7824533b9710d37f9
ea778bab27868d2841c1428d31358ccfe3baca02
/AnKang_ZhongFu/shengchanfenbudlg.cpp
9122f03f418c02af54401a50e8daef062584a282
[]
no_license
WenYunZi/erp
a355cb7df29abb0b7e26b874d1a342b078d2f91b
c42f6d934ff8fa4938ce4cd70b50358623a86c98
refs/heads/master
2020-05-07T17:33:52.927440
2019-04-11T06:41:48
2019-04-11T06:41:48
180,730,895
2
0
null
null
null
null
UTF-8
C++
false
false
7,640
cpp
#include "shengchanfenbudlg.h" extern mymysql db; shengchanfenbuDlg::shengchanfenbuDlg(QWidget *parent) : QDialog(parent) { SQL = "SELECT B.CheNumber 车辆号码,B.USERCHE 驾驶员,B.GCNAME 工程名称,B.JIAOZHUBW 浇筑部位,B.phbNumber 任务名称,\ D.StrengthGrade 砼等级,B.CheTime 时间,\ B.Z 每车方量,\ SUM(CASE Material WHEN '砂' THEN SJMAT ELSE 0 END) 砂,\ SUM(CASE Material WHEN '水洗砂' THEN SJMAT ELSE 0 END) 水洗砂,\ SUM(CASE Material WHEN '石子' THEN SJMAT ELSE 0 END) 石子,\ SUM(CASE Material WHEN '细石' THEN SJMAT ELSE 0 END) 细石,\ SUM(CASE Material WHEN '水泥1' THEN SJMAT ELSE 0 END) 水泥1,\ SUM(CASE Material WHEN '水泥2' THEN SJMAT ELSE 0 END) 水泥2,\ SUM(CASE Material WHEN '矿粉' THEN SJMAT ELSE 0 END) 矿粉,\ SUM(CASE Material WHEN '粉煤灰' THEN SJMAT ELSE 0 END) 粉煤灰,\ SUM(CASE Material WHEN '膨胀剂' THEN SJMAT ELSE 0 END) 膨胀剂,\ SUM(CASE Material WHEN '外加剂1' THEN SJMAT ELSE 0 END) 外加剂1,\ IF(SUM(CASE Material WHEN '外加剂1' THEN IF((LOCATE('防冻',MATNAME)>0),1,0) ELSE 0 END)>0,'是','否') 外加剂1防冻,\ SUM(CASE Material WHEN '外加剂2' THEN SJMAT ELSE 0 END) 外加剂2,\ IF(SUM(CASE Material WHEN '外加剂2' THEN IF((LOCATE('防冻',MATNAME)>0),1,0) ELSE 0 END)>0,'是','否') 外加剂2防冻,\ SUM(CASE Material WHEN '外加剂3' THEN SJMAT ELSE 0 END) 增效剂,\ SUM(CASE Material WHEN '清水' THEN SJMAT ELSE 0 END) 清水,\ recordNo 记录号,unit 生产机组\ FROM HISTDATA2 A LEFT JOIN (SELECT *,ROUND(SUM(SUMPS),1) Z FROM HISTDATA GROUP BY bsqk) B ON (A.CHETIME=B.CheTime and A.JIZUNO=B.unit) \ LEFT JOIN (SELECT * FROM UnitMaterialSetting) C ON (C.CorrespondingField=A.FILED AND C.SubordinateUnit=A.JIZUNO) \ LEFT JOIN (SELECT * FROM ProductionTaskList) D ON (D.TaskNumber=B.phbNumber)\ WHERE A.CHETIME BETWEEN '%1' AND '%2' GROUP BY A.JIZUNO,A.CHETIME ORDER BY recordNo limit 0"; QLabel *label1 = new QLabel(tr("日期"),this); label1->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); QLabel *label2 = new QLabel(tr("-"),this); label2->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); ProductedVolumeLabel = new QLabel(this); ProductedVolumeLabel->setStyleSheet("color:red"); UnitNoCheck = new QCheckBox(tr("机组"),this); UnitNoCombox = new QComboBox(this); db.sql_fillComboBoxItem("select UnitName from UnitSetting",UnitNoCombox); dateEdit1 = new QDateTimeEdit(this); dateEdit1->setDate(QDate::currentDate().addDays(-1)); dateEdit1->setTime(QTime::fromString("00:00:00","hh:mm:ss")); dateEdit1->setCalendarPopup(true); dateEdit2 = new QDateTimeEdit(this); dateEdit2->setDate(QDate::currentDate()); dateEdit2->setTime(QTime::fromString("00:00:00","hh:mm:ss")); dateEdit2->setCalendarPopup(true); chaxunBtn = new QPushButton(tr("查询"),this); chaxunBtn->setFixedWidth(130); connect(chaxunBtn,SIGNAL(clicked()),this,SLOT(on_chaxunBtn())); daochuBtn = new QPushButton(tr("导出"),this); daochuBtn->setFixedWidth(130); connect(daochuBtn,SIGNAL(clicked()),this,SLOT(on_daochuBtn())); view = new QTableView(this); db.showview(SQL,view,&model); view2Excel = new myExcel(this); QHBoxLayout *hlayout = new QHBoxLayout; hlayout->addWidget(label1,0); hlayout->addWidget(dateEdit1,1); hlayout->addWidget(label2,0); hlayout->addWidget(dateEdit2,1); hlayout->addWidget(UnitNoCheck,0); hlayout->addWidget(UnitNoCombox,1); hlayout->addWidget(chaxunBtn,1); hlayout->addWidget(daochuBtn,1); hlayout->addWidget(ProductedVolumeLabel,1); hlayout->addStretch(6); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->addLayout(hlayout); vlayout->addWidget(view); } void shengchanfenbuDlg::refresh() { } void shengchanfenbuDlg::on_chaxunBtn() { QString UnitNo; if(UnitNoCheck->checkState() == 2){ UnitNo = QString(" and unit='%1'").arg(UnitNoCombox->currentText()); } QString searchSQL = QString("SELECT D.DeliveryVehicle 车辆号码,D.Driver 驾驶员,D.Engineering 工程名称,D.PouringPosition 浇筑部位,B.phbNumber 任务名称,\ D.StrengthGrade 砼等级,B.CheTime 时间,\ B.PRODUCTVOLUME 每车方量,\ SUM(CASE Material WHEN '砂' THEN SJMAT ELSE 0 END) 砂,\ SUM(CASE Material WHEN '水洗砂' THEN SJMAT ELSE 0 END) 水洗砂,\ SUM(CASE Material WHEN '石子' THEN SJMAT ELSE 0 END) 石子,\ SUM(CASE Material WHEN '细石' THEN SJMAT ELSE 0 END) 细石,\ SUM(CASE Material WHEN '水泥1' THEN SJMAT ELSE 0 END) 水泥1,\ SUM(CASE Material WHEN '水泥2' THEN SJMAT ELSE 0 END) 水泥2,\ SUM(CASE Material WHEN '矿粉' THEN SJMAT ELSE 0 END) 矿粉,\ SUM(CASE Material WHEN '粉煤灰' THEN SJMAT ELSE 0 END) 粉煤灰,\ SUM(CASE Material WHEN '膨胀剂' THEN SJMAT ELSE 0 END) 膨胀剂,\ SUM(CASE Material WHEN '外加剂1' THEN IF((LOCATE('防冻',MATNAME)>0),0,SJMAT) ELSE 0 END) 外加剂1,\ SUM(CASE Material WHEN '外加剂1' THEN IF((LOCATE('防冻',MATNAME)>0),SJMAT,0) ELSE 0 END) 防冻剂1,\ SUM(CASE Material WHEN '外加剂2' THEN IF((LOCATE('防冻',MATNAME)>0),0,SJMAT) ELSE 0 END) 外加剂2,\ SUM(CASE Material WHEN '外加剂2' THEN IF((LOCATE('防冻',MATNAME)>0),SJMAT,0) ELSE 0 END) 防冻剂2,\ SUM(CASE Material WHEN '外加剂3' THEN SJMAT ELSE 0 END) 增效剂,\ SUM(CASE Material WHEN '清水' THEN SJMAT ELSE 0 END) 清水,\ recordNo 记录号,JIZUNO 生产机组\ FROM HISTDATA2 A LEFT JOIN (SELECT phbNumber,bsqk,unit,CheTime,ROUND(SUM(SUMPS),1) PRODUCTVOLUME FROM HISTDATA GROUP BY bsqk,unit) B ON (A.recordNo=B.bsqk and A.JIZUNO=B.unit)\ LEFT JOIN (SELECT CorrespondingField,SubordinateUnit,Material FROM UnitMaterialSetting) C ON (C.CorrespondingField=A.FILED AND C.SubordinateUnit=A.JIZUNO) \ LEFT JOIN (SELECT DeliveryVehicle,Driver,Engineering,PouringPosition,StrengthGrade,RecordNumber FROM ProductionNotice) D ON (D.RecordNumber=A.recordNo)\ WHERE A.CHETIME BETWEEN '%1' AND '%2' %3 GROUP BY A.JIZUNO,A.recordNo ORDER BY recordNo") .arg(dateEdit1->dateTime().toString("yyyy-MM-dd hh:mm:ss"),dateEdit2->dateTime().toString("yyyy-MM-dd hh:mm:ss"),UnitNo); db.showview(searchSQL.toStdString().data(),view,&model); double total = 0; int rowCount = model->rowCount(); for(int i=0; i<rowCount; i++){ total += model->item(i,7)->text().toDouble(); } ProductedVolumeLabel->setText(QString("合计: 生产方量%1方").arg(total)); } void shengchanfenbuDlg::on_daochuBtn() { view2Excel->Table2ExcelByHtml(view,QString("生产消耗分布表")); }
[ "test@runoob.com" ]
test@runoob.com
0f9dd1f4ab6e60929c86bc3d7448af71d763a39e
208650de138a6b05b8b8e7e4ca6df9dc72290402
/Problems/Practice/C/170.cpp
d175e45b33dca509c8d8434e1c6a0c9f6c80d95c
[]
no_license
cs15b047/CF
9fcf83c5fd09124b6eaebbd4ecd67d19a1302582
d220d73a2d8739bbb10f4ed71437c06625870490
refs/heads/master
2021-08-20T06:21:24.577260
2021-06-09T04:56:47
2021-06-09T04:57:29
177,541,957
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include <bits/stdc++.h> using namespace std ; typedef long long int ll ; ll bin_search(ll n, ll mod3){ // cout << mod3 << endl; ll l = (mod3 == 0),r = (ll)sqrt(n),m; ll x = 3*l + mod3; if((x*(3*x + 1))/2 > n)return -1; while(l < r){ m = (ll)ceil((float)(l + r)/(float)2) ; x = 3*m + mod3 ; ll expr = (x*(3*x + 1))/2 ; if(expr > n){ r = m - 1; } else{ l = m; } } // cout << l << endl; return l; } int main(){ ll n; cin >> n; ll mod3; if(n % 3 == 0)mod3 = 0; else if(n%3==1)mod3 = 2; else mod3 = 1; ll strt = (mod3==0); ll idx = bin_search(n, mod3); if(idx == -1){ cout << 0 << endl ; } else{ cout << (idx - strt + 1) << endl ; } }
[ "cs15b047@smail.iitm.ac.in" ]
cs15b047@smail.iitm.ac.in
061ba4b4081e4b8f49f8638368392b9df8aadc96
9e5445e081bfa56ba25ae3372f627a38bafc4945
/gkit2light-master_MecaSim/src/master_MecaSim/src-etudiant/ObjetSimuleRigidBody.h
2f34c912dc1171fa1d07cce86b6fb77bf39527ab
[]
no_license
Batora07/clothAnim3D
87cfe9d74af7a9f1cbc987c0270cc508a259518d
329be82b0213c285fb0f1d2176a215829656568e
refs/heads/master
2020-12-31T00:40:44.260992
2017-02-01T11:29:36
2017-02-01T11:29:36
80,612,174
0
0
null
null
null
null
UTF-8
C++
false
false
3,308
h
/** \file ObjetSimuleRigidBody.h \brief Structures de donnes relatives aux objets rigides. */ #ifndef OBJET_SIMULE_RIGID_BODY_H #define OBJET_SIMULE_RIGID_BODY_H /** Librairies de base **/ #include <stdio.h> #include <vector> #include <string.h> #include <fstream> // Fichiers de gkit2light #include "vec.h" #include "mesh.h" // Fichiers de master_meca_sim #include "MSS.h" #include "Noeuds.h" #include "Matrix.h" #include "Properties.h" #include "ObjetSimule.h" #include "ObjetSimuleMSS.h" /** * \brief Structure de donnees pour un objet rigide. */ class ObjetSimuleRigidBody : public ObjetSimuleMSS { public: /*! Constructeur */ ObjetSimuleRigidBody(std::string fich_param); /*! Lecture des parametres lies a un objet rigid */ void Param_rigid(std::string fich_param); /*! Initialisation des tableaux des sommets a partir du fichier de donnees de l objet */ void initObjetSimule(); /*! Calcul de la masse de l objet rigide */ void CalculMasse(); /*! Calcul du IBody */ void CalculIBody(); /*! Calcul de l etat de l objet rigide */ void CalculStateX(); /*! Calcul de d/dt X(t) */ void CalculDeriveeStateX(Vector gravite); /*! Schema integration pour obtenir X(t+dt) */ void Solve(float visco); /*! Simulation de l objet */ void Simulation(Vector gravite, float viscosite, int Tps); /* ! Gestion des collisions avec plan (x,y,z) */ void CollisionPlan(float x, float y, float z); /*! Creation du maillage (pour l affichage) de l objet simule de type RigidBody */ void initMeshObjet(); /*! Mise a jour du Mesh (pour affichage) de l objet en fonction des nouvelles positions calculees */ void updateVertex(); /// Etat du systeme : X(t) // - position : x(t) - position du baycentre // - rotation : R(t) // - quantite de mouvement : P(t) = m v(t) // - moment cinetique : L(t) = I(t) w(t) /// Position du centre de masse Vector _Position; Vector _BaryCentre; /// Position des particules i : // r0i : position constante de la particule i dans l objet // ri(t) : position dans le repere monde // ri(t) = R(t) r0i + x(t) std::vector<Vector> _ROi; /// Matrice de rotation R(t) Matrix _Rotation; /// Quantite de mouvement : P(t) = masse * vitesse Vector _QuantiteMouvement; /// Moment Cinetique : L(t) Vector _MomentCinetique; // On a aussi besoin // masse : m // tenseur inertie : I(t) // vitesse angulaire : w(t) /// Masse de l objet (constante pendant la simulation) float _Mass; /// Tenseur d inertie de l objet rigide - Partie constante Matrix _Ibody; /// Inverse du tenseur d inertie - Partie constante Matrix _IbodyInv; // Inverse du tenseur d inertie Matrix _InertieTenseurInv; /// Vitesse angulaire w(t) Vector _VitesseAngulaire; // Derivee de l etat du systeme : x'(t) = d/dt X(t) // - d/dt x(t) = v(t) - vitesse du baycentre // - d/dt R(t) = r'(t) = w(t) x R(t) // - d/dt P(t) = F(t) - les forces // - d/dt L(t) = moment de la force (torque) = sum_i (ri(t) - x(t)) x Fi(t) /// x't) = vitesse du centre de masse Vector _Vitesse; /// Derivee de la rotation Matrix _RotationDerivee; /// P'(t) = Force appliquee Vector _Force; // L'(t) = Moment de la force Vector _Torque; // Intervalle de temps float _delta_t; }; #endif
[ "batora.ushiromiya.07@gmail.com" ]
batora.ushiromiya.07@gmail.com
a8114938b3a9dff210fde17bfd98540405dd96fa
01421ae859cf0dd15e15ccb20c49c753ac2155b7
/demo/CommonWithSource/main.cpp
bc33b38a485e18961de5f2d695008beb2ba465d2
[ "MIT" ]
permissive
jaredtao/TaoCommon
498f2fd412a28b948e0d81d9ca243d92eab439c4
d74abc4651fcf4366c443e485d2002ed10a270ba
refs/heads/master
2023-05-07T16:12:39.157908
2023-05-06T17:42:28
2023-05-06T17:42:28
217,277,939
32
10
null
null
null
null
UTF-8
C++
false
false
521
cpp
#include "Logger/Logger.h" #include <QGuiApplication> #include <QQmlApplicationEngine> int main(int argc, char* argv[]) { QGuiApplication app(argc, argv); Logger::initLog(); QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect( &engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject* obj, const QUrl& objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }
[ "jared2020@163.com" ]
jared2020@163.com
2ba33cc4f88a3433d13d035c142885b1cccb57b5
f3a52a8832519729d65c5c3c436db2000217703c
/Source/FSD/Private/FSDMainHUDWidget.cpp
c8f08e1b9faa1d94c3ddc9551191f11c1d1a7db8
[]
no_license
NicolasAubinet/virtual-rock-galactic
50be56c6548cfd44b3187cb41e4e03847b2093e7
e82ce900f1f88c7db0abdb1d69c2de31650ca628
refs/heads/main
2023-07-22T08:04:59.552029
2023-07-15T08:16:22
2023-07-15T08:16:22
425,605,229
22
3
null
null
null
null
UTF-8
C++
false
false
218
cpp
#include "FSDMainHUDWidget.h" class URadarPointComponent; void UFSDMainHUDWidget::AddRadarPoint(URadarPointComponent* Point) { } UFSDMainHUDWidget::UFSDMainHUDWidget() : UUserWidget(FObjectInitializer::Get()) { }
[ "n.aubinet@gmail.com" ]
n.aubinet@gmail.com
9634f23e9bd1e429d5c8bbb58800fd05c181bba5
5cb369854f0cb24c351d0fc096fcb7d51642f4bb
/Hackerrank/Secret Message Groups.cpp
02197dcc8531ea050d32bdb30856416d7ea544f8
[]
no_license
sebas095/Competitive-Programming
3b0710bf76c04f274a67527888fc81dd6ddb9c6f
0631caca5b10019f44212588ea16dbfc59c42f53
refs/heads/master
2021-05-24T00:56:51.945526
2020-07-07T06:46:42
2020-07-07T06:46:42
45,226,584
0
2
null
2016-10-28T16:26:50
2015-10-30T03:19:53
C++
UTF-8
C++
false
false
1,460
cpp
#include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(false);cin.tie(NULL) #define endl '\n' // Problem: https://www.hackerrank.com/contests/womens-codesprint/challenges/grouping-the-items using namespace std; string get_key(string s) { string key = s; sort(key.begin(), key.end()); return key; } void solve(map<string, set<string>> &group) { int ms = 0, sz = 0, index = 0; map<string, set<string>> items; // Buscamos el grupo que tenga la mayor cantidad de elementos for (auto &it : group) { ms = max(ms, (int)(it.second.size())); } // Agrupamos dejando como llave el mayor elemento del grupo for (auto &it : group) { if (it.second.size() == ms) { sz++; items[*(it.second.rbegin())] = it.second; } } // Pasamos los grupos a un vector para mostrarlo en el formato pedido vector<vector<string>> ans(sz); for (auto &it : items) { if (it.second.size() == ms) { for (auto &itt : it.second) { ans[index].push_back(itt); } index++; } else continue; } cout << group.size() << endl; for (int i = 0; i < ans.size(); i++) { for (int j = ans[i].size() - 1; j >= 0; j--) { cout << ans[i][j]; if (j > 0) cout << " "; } cout << endl; } } int main() { fast; int n, ms = 0; string s; map<string, set<string>> group; cin >> n; while (n--) { cin >> s; group[get_key(s)].insert(s); } solve(group); return 0; }
[ "sebas_tian_95@hotmail.com" ]
sebas_tian_95@hotmail.com
51835b1fe6e5ff54a9634f7755976fd68a3e87c6
5e35d49887a0c50d75913ca82d187275e217c4f5
/Baekjoon/LEETCODE]symmetrictree.cpp
cdf5f825fcf696311ea411020b2edf56d668960c
[]
no_license
jiun0507/Interview-prep
4866f0c3d3dd6a407bc7078987aaa373d7111c2c
aeaae8a99dc21f2b11ae50f577a75ff49b56e1b3
refs/heads/master
2021-11-14T11:31:03.316564
2021-09-11T21:15:25
2021-09-11T21:15:25
214,645,862
0
0
null
2019-10-12T13:08:09
2019-10-12T12:44:57
null
UTF-8
C++
false
false
2,177
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSymmetric(TreeNode* root) { map<vector<bool>, int> original; vector<bool> track; track.push_back(false); queue<pair<vector<bool>, TreeNode*>> q; if(root->left) q.push(make_pair(track, root->left)); while(!q.empty()){ auto cur = q.front(); q.pop(); vector<bool> cur_track = cur.first; auto cur_node = cur.second; original[cur_track] = cur_node->val; if(cur_node->left){ cur_track.push_back(false); q.push(make_pair(cur_track, cur_node->left)); cur_track.pop_back(); } if(cur_node->right){ cur_track.push_back(true); q.push(make_pair(cur_track, cur_node->right)); cur_track.pop_back(); } } if(root->right) q.push(make_pair(track, root->right)); while(!q.empty()){ auto cur = q.front(); q.pop(); vector<bool> cur_track = cur.first; auto cur_node = cur.second; if(original.count(cur_track)==0){ return false; } if(original[cur_track]!=cur_node->val){ return false; } original.erase(cur_track); if(cur_node->left){ cur_track.push_back(true); q.push(make_pair(cur_track, cur_node->left)); cur_track.pop_back(); } if(cur_node->right){ cur_track.push_back(false); q.push(make_pair(cur_track, cur_node->right)); cur_track.pop_back(); } } if(!original.empty()) return false; return true; } };
[ "jkim2@bowdoin.edu" ]
jkim2@bowdoin.edu
425903c6386ca9e59cd0849744cb5e0b6151b13c
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/ash/test/content/test_shell_content_state.cc
1b04af0c5947da756e0535a5703e2318e47c7483
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
619
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/test/content/test_shell_content_state.h" #include "content/public/test/test_browser_context.h" namespace ash { TestShellContentState::TestShellContentState() = default; TestShellContentState::~TestShellContentState() = default; content::BrowserContext* TestShellContentState::GetActiveBrowserContext() { active_browser_context_.reset(new content::TestBrowserContext()); return active_browser_context_.get(); } } // namespace ash
[ "team@geometry.ee" ]
team@geometry.ee
53cc65fd38d538a0fcc74f6685fb0fe2abe2e05d
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/pdfium/core/fpdfapi/page/cpdf_color.cpp
d06d445adfe76280b3d341c325e7a2182a6c9178
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
4,260
cpp
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfapi/page/cpdf_color.h" #include "core/fpdfapi/page/pageint.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fxcrt/fx_system.h" CPDF_Color::CPDF_Color() : m_pCS(nullptr), m_pBuffer(nullptr) {} CPDF_Color::~CPDF_Color() { ReleaseBuffer(); ReleaseColorSpace(); } bool CPDF_Color::IsPattern() const { return m_pCS && m_pCS->GetFamily() == PDFCS_PATTERN; } void CPDF_Color::ReleaseBuffer() { if (!m_pBuffer) return; if (m_pCS->GetFamily() == PDFCS_PATTERN) { PatternValue* pvalue = (PatternValue*)m_pBuffer; CPDF_Pattern* pPattern = pvalue->m_pCountedPattern ? pvalue->m_pCountedPattern->get() : nullptr; if (pPattern && pPattern->document()) { CPDF_DocPageData* pPageData = pPattern->document()->GetPageData(); if (pPageData) pPageData->ReleasePattern(pPattern->pattern_obj()); } } FX_Free(m_pBuffer); m_pBuffer = nullptr; } void CPDF_Color::ReleaseColorSpace() { if (m_pCS && m_pCS->m_pDocument) { m_pCS->m_pDocument->GetPageData()->ReleaseColorSpace(m_pCS->GetArray()); m_pCS = nullptr; } } void CPDF_Color::SetColorSpace(CPDF_ColorSpace* pCS) { if (m_pCS == pCS) { if (!m_pBuffer) m_pBuffer = pCS->CreateBuf(); ReleaseColorSpace(); m_pCS = pCS; return; } ReleaseBuffer(); ReleaseColorSpace(); m_pCS = pCS; if (m_pCS) { m_pBuffer = pCS->CreateBuf(); pCS->GetDefaultColor(m_pBuffer); } } void CPDF_Color::SetValue(FX_FLOAT* comps) { if (!m_pBuffer) return; if (m_pCS->GetFamily() != PDFCS_PATTERN) FXSYS_memcpy(m_pBuffer, comps, m_pCS->CountComponents() * sizeof(FX_FLOAT)); } void CPDF_Color::SetValue(CPDF_Pattern* pPattern, FX_FLOAT* comps, int ncomps) { if (ncomps > MAX_PATTERN_COLORCOMPS) return; if (!IsPattern()) { FX_Free(m_pBuffer); m_pCS = CPDF_ColorSpace::GetStockCS(PDFCS_PATTERN); m_pBuffer = m_pCS->CreateBuf(); } CPDF_DocPageData* pDocPageData = nullptr; PatternValue* pvalue = (PatternValue*)m_pBuffer; if (pvalue->m_pPattern && pvalue->m_pPattern->document()) { pDocPageData = pvalue->m_pPattern->document()->GetPageData(); if (pDocPageData) pDocPageData->ReleasePattern(pvalue->m_pPattern->pattern_obj()); } pvalue->m_nComps = ncomps; pvalue->m_pPattern = pPattern; if (ncomps) FXSYS_memcpy(pvalue->m_Comps, comps, ncomps * sizeof(FX_FLOAT)); pvalue->m_pCountedPattern = nullptr; if (pPattern && pPattern->document()) { if (!pDocPageData) pDocPageData = pPattern->document()->GetPageData(); pvalue->m_pCountedPattern = pDocPageData->FindPatternPtr(pPattern->pattern_obj()); } } void CPDF_Color::Copy(const CPDF_Color* pSrc) { ReleaseBuffer(); ReleaseColorSpace(); m_pCS = pSrc->m_pCS; if (m_pCS && m_pCS->m_pDocument) { CPDF_Array* pArray = m_pCS->GetArray(); if (pArray) m_pCS = m_pCS->m_pDocument->GetPageData()->GetCopiedColorSpace(pArray); } if (!m_pCS) return; m_pBuffer = m_pCS->CreateBuf(); FXSYS_memcpy(m_pBuffer, pSrc->m_pBuffer, m_pCS->GetBufSize()); if (m_pCS->GetFamily() != PDFCS_PATTERN) return; PatternValue* pValue = reinterpret_cast<PatternValue*>(m_pBuffer); CPDF_Pattern* pPattern = pValue->m_pPattern; if (pPattern && pPattern->document()) { pValue->m_pPattern = pPattern->document()->GetPageData()->GetPattern( pPattern->pattern_obj(), false, pPattern->parent_matrix()); } } FX_BOOL CPDF_Color::GetRGB(int& R, int& G, int& B) const { if (!m_pCS || !m_pBuffer) return FALSE; FX_FLOAT r = 0.0f, g = 0.0f, b = 0.0f; if (!m_pCS->GetRGB(m_pBuffer, r, g, b)) return FALSE; R = (int32_t)(r * 255 + 0.5f); G = (int32_t)(g * 255 + 0.5f); B = (int32_t)(b * 255 + 0.5f); return TRUE; } CPDF_Pattern* CPDF_Color::GetPattern() const { if (!m_pBuffer || m_pCS->GetFamily() != PDFCS_PATTERN) return nullptr; PatternValue* pvalue = (PatternValue*)m_pBuffer; return pvalue->m_pPattern; }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
d470b6560c5e6f15839864dbac848c14f1c204ce
9ed629c3e32090feff4bb60743ba7413780a675c
/ClientDlg.h
f9ebb6f61b96ebcf5eb51565856d67f345a7a8a5
[]
no_license
rahulkumar6081/messenger
18213c6b7130e9b489deab0a8a36dea623ab05da
c7b14136218f943a86ced3ca13f63852ceb121d5
refs/heads/master
2020-04-20T05:10:46.846712
2019-02-01T05:51:30
2019-02-01T05:51:30
168,648,981
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
h
// ClientDlg.h : header file // #pragma once #include "ClientCon.h" #include <Windows.h> #include "resource.h" // CClientDlg dialog class CClientDlg : public CDialogEx { // Construction public: CClientDlg(CWnd* pParent = NULL); // standard constructor void ShowServerInfo(string sValue); // Dialog Data enum { IDD = IDD_CLIENT_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedButton2(); afx_msg void OnBnClickedButton4(); ClientCon *m_pClient; static UINT __cdecl StaticThreadFunc(LPVOID pParam); UINT ThreadFunc(); void AppendTextToEditCtrl(CEdit& edit, LPCTSTR pszText); CEdit m_Portbox; private: HANDLE m_Thread_handle; CWinThread *cTh; public: CEdit m_Textbox; afx_msg void OnBnClickedButton3(); };
[ "noreply@github.com" ]
noreply@github.com
e88bd72ab0ca336bb5f66b9cb5947fb87ba73b21
b648a0ff402d23a6432643879b0b81ebe0bc9685
/vendor/bond/cpp/test/core/container_extensibility.h
ddf7a9820afebc20fb6ac01882b8ea631a12989c
[ "Apache-2.0", "MIT" ]
permissive
jviotti/binary-json-size-benchmark
4712faca2724d47d23efef241983ce875dc71cee
165b577884ef366348bf48042fddf54aacfe647a
refs/heads/main
2023-04-18T01:40:26.141995
2022-12-19T13:25:35
2022-12-19T13:25:35
337,583,132
21
1
Apache-2.0
2022-12-17T21:53:56
2021-02-10T01:18:05
C++
UTF-8
C++
false
false
3,878
h
#pragma once #include "unit_test_limits.h" #include <bond/core/container_interface.h> #include <array> #include <boost/static_assert.hpp> template <typename T> struct SimpleList { SimpleList() : size(0) {} SimpleList(SimpleList&& other) : size(std::move(other.size)) { other.size = 0; for (uint32_t i = 0; i < size; ++i) { items[i] = std::move(other.items[i]); } } SimpleList(const SimpleList&) = default; SimpleList& operator=(const SimpleList&) = default; bool operator==(const SimpleList& rhs) const { if (size != rhs.size) return false; for (uint32_t i = 0; i < size; ++i) if (items[i] != rhs.items[i]) return false; return true; } T items[c_max_list_size]; uint32_t size; }; // list container interface and traits for SimpleList namespace bond { // SimpleList is a list container template <typename T> struct is_list_container<SimpleList<T> > : std::true_type {}; // element_type trait template <typename T> struct element_type<SimpleList<T> > { typedef T type; }; // enumerator template <typename T> class enumerator<SimpleList<T> > : boost::noncopyable { public: enumerator(SimpleList<T>& list) : list(list), index(0) {} bool more() { return index < list.size; } T& next() { return list.items[index++]; } private: SimpleList<T>& list; uint32_t index; }; // const_enumerator template <typename T> class const_enumerator<SimpleList<T> > : boost::noncopyable { public: const_enumerator(const SimpleList<T>& list) : list(list), index(0) {} bool more() { return index != list.size; } const T& next() { return list.items[index++]; } private: const SimpleList<T>& list; uint32_t index; }; }; // container_size template <typename T> uint32_t container_size(const SimpleList<T>& list) { return list.size; } // resize_list template <typename T> void resize_list(SimpleList<T>& list, uint32_t size) { BOOST_ASSERT(size <= c_max_list_size); list.size = size; } namespace bond { template <size_t N> struct is_string<std::array<char, N> > : std::true_type {}; template <size_t N> struct is_string<const std::array<char, N> > : std::true_type {}; template <size_t N> struct is_wstring<std::array<wchar_t, N> > : std::true_type {}; template <size_t N> struct is_wstring<const std::array<wchar_t, N> > : std::true_type {}; template <typename T, size_t N> struct element_type<std::array<T, N> > { typedef T type; }; } namespace std { template <typename T, size_t N> const T* string_data(const std::array<T, N>& str) { return &str[0]; } template <typename T, size_t N> T* string_data(std::array<T, N>& str) { return &str[0]; } template <size_t N> uint32_t string_length(const std::array<char, N>& str) { return static_cast<uint32_t>(strlen(&str[0])); } template <size_t N> uint32_t string_length(const std::array<wchar_t, N>& str) { return static_cast<uint32_t>(wcslen(&str[0])); } template<typename T, size_t N> void resize_string(std::array<T, N>& str, uint32_t size) { BOOST_ASSERT(size < N); str[size] = T(0); } }; class ExtensibilityTest { public: static void Initialize(); static void InitializeAssociative(); };
[ "jv@jviotti.com" ]
jv@jviotti.com
769326f0aa5ec290782e387c86723ee2e13da5f5
6dc23ba6bdbd65566e2c69bebaf76c656ad016bd
/pages/fuel_page.cpp
149f5e051140d7cc7196ad5ed4ff43a86030deeb
[]
no_license
schenlap/ecam
3cb62e8d686ab7f4214211aa874d622845544845
6e23b3ba32564f920baf3550df3fa5133e51f123
refs/heads/master
2023-01-31T19:56:33.032080
2020-12-10T19:53:42
2020-12-10T19:53:42
320,020,423
0
0
null
null
null
null
UTF-8
C++
false
false
7,394
cpp
// 4.4.2015 // TODO: unreachable fuel quantity in cyan // TODO: x feed valve in out tanks // TODO: Fuel Uses Number in amber if engine is on idle // TODO: Pump low pressure indication #include <QPainter> #include <QLabel> #include "widgets/valve.h" #include "widgets/pump.h" #include "fuel_page.h" #include "ui_fuel_page.h" static int linewidth = 2; FuelPage::FuelPage(QWidget *parent) : QWidget(parent), ui(new Ui::FuelPage) { ui->setupUi(this); ui->val_apu->set_apu(true); ui->val_xfeed->set_vertical(false); ui->val_xfeed->set_apu(true); } void FuelPage::paintEvent(QPaintEvent *) { //qDebug("-"); QPainter painter(this); painter.setRenderHint((QPainter::Antialiasing)); painter.setPen(QPen(Qt::green, linewidth)); QPoint apu_val_in = ui->val_apu->inlet_pos(); QPoint eng1_val_in = ui->val_eng1->inlet_pos(); QPoint eng2_val_in = ui->val_eng2->inlet_pos(); QPoint xfeed_val_in = ui->val_xfeed->inlet_pos(); QPoint xfeed_val_out = ui->val_xfeed->outlet_pos(); QPoint pump_ll_out = ui->pump_left_left->outlet_pos(); QPoint pump_lc_out = ui->pump_left_center->outlet_pos(); QPoint pump_cl_out = ui->pump_center_left->outlet_pos(); QPoint pump_cr_out = ui->pump_center_right->outlet_pos(); QPoint pump_rc_out = ui->pump_right_center->outlet_pos(); QPoint pump_rr_out = ui->pump_right_right->outlet_pos(); QPoint xfeed_left = QPoint(eng1_val_in.x(), xfeed_val_in.y()); // Xfeed Y - Position /* horizontal lines */ painter.drawLine(pump_ll_out, eng1_val_in); // Left Left painter.drawLine(pump_lc_out.x(), pump_lc_out.y(), pump_lc_out.x(), pump_lc_out.y()-10); // Left Center painter.drawLine(eng1_val_in.x(), xfeed_left.y() ,pump_cl_out.x() , xfeed_left.y()); // horiz. X Feed painter.drawLine(eng2_val_in.x(), xfeed_left.y() ,pump_cr_out.x() , xfeed_left.y()); // horit. X Feed painter.drawLine(apu_val_in.x(), apu_val_in.y(), apu_val_in.x(), xfeed_left.y()); // APU painter.drawLine(pump_cl_out.x(), xfeed_val_in.y(), pump_cl_out.x(), pump_cl_out.y()); // Center left painter.drawLine(pump_cr_out.x(), xfeed_val_in.y(), pump_cr_out.x(), pump_cr_out.y()); // Center right painter.drawLine(pump_rc_out.x(), pump_rc_out.y(), pump_rc_out.x(), pump_rc_out.y()-10); // Right Center painter.drawLine(pump_rr_out, eng2_val_in); // Right //painter.drawLine(ui->pump_right_right->outlet_pos(), ui->val_eng2->inlet_pos()); /* vertical lines */ painter.save(); painter.setPen(QPen(Qt::blue, linewidth)); painter.drawLine(pump_ll_out.x() - 10, pump_ll_out.y()-10, pump_lc_out.x() + 10, pump_lc_out.y()-10); // Left painter.drawLine(pump_cl_out.x() - 10, pump_cl_out.y()-10, pump_cl_out.x() + 10, pump_cl_out.y()-10); // Center Left painter.drawLine(pump_cr_out.x() - 10, pump_cr_out.y()-10, pump_cr_out.x() + 10, pump_cr_out.y()-10); // Center Right painter.drawLine(pump_rc_out.x() - 10, pump_rc_out.y()-10, pump_rr_out.x() + 10, pump_rr_out.y()-10); // Right painter.restore(); /* x fedd vertical lines */ if (ui->val_xfeed->value() == Valve::OPEN) { painter.drawLine(pump_cl_out.x(), xfeed_val_in.y(), xfeed_val_in.x() , xfeed_val_in.y()); painter.drawLine(pump_cr_out.x(), xfeed_val_out.y(), xfeed_val_out.x() , xfeed_val_out.y()); } painter.setPen(QPen(Qt::blue, 1)); static const int fyo = 83; static const int fxo = 198; static const int fdx = 63; static const int fdy = 18; static const QPoint fr[4] = { QPoint(fxo, fyo), QPoint(fxo + fdx, fyo), QPoint(fxo + fdx, fyo + fdy), QPoint(fxo, fyo + fdy), }; painter.drawConvexPolygon(fr, 4); static const QPoint fr2[4] = { QPoint(fxo-3, fyo-3), QPoint(fxo + fdx+3, fyo-3), QPoint(fxo + fdx+3, fyo + fdy+3), QPoint(fxo-3, fyo + fdy+3), }; painter.drawConvexPolygon(fr2, 4); static const int yofs = 260 + 45; static const int dy = 40; static const int yc = 5; static const QPoint fl[8] = { QPoint(10, yofs), QPoint(90, yofs + yc), QPoint(390, yofs + yc), QPoint(470, yofs), QPoint(470, yofs + dy), QPoint(410, yofs + dy + yc), QPoint(90, yofs + dy + yc), QPoint(10, yofs + dy) }; painter.drawConvexPolygon(fl, 8); static const QPoint fl2[8] = { QPoint(10-3, yofs-3), QPoint(90, yofs + yc-3), QPoint(390, yofs + yc-3), QPoint(470+3, yofs-3), QPoint(470+3, yofs + dy+3), QPoint(390, yofs + dy + yc+3), QPoint(90, yofs + dy + yc+3), QPoint(10-3, yofs + dy+3) }; painter.drawConvexPolygon(fl2, 8); painter.drawLine(pump_cl_out.x()-15, yofs + yc, pump_cl_out.x()-15, yofs + yc + dy); // cl painter.drawLine(pump_cl_out.x()-15 + 3, yofs + yc, pump_cl_out.x()-15 + 3, yofs + yc + dy); painter.drawLine(pump_cr_out.x()+15, yofs + yc, pump_cr_out.x()+15, yofs + yc + dy); // cr painter.drawLine(pump_cr_out.x()+15 - 3, yofs + yc, pump_cr_out.x()+15 - 3, yofs + yc + dy); painter.setPen(QPen(Qt::green, linewidth)); painter.drawLine(90, yofs - 3 - 1, 90, yofs + yc + dy + 3 + 1); // ll painter.drawLine(390, yofs - 3 - 1, 390, yofs + yc + dy + 3 + 1); // rr } bool FuelPage::set_new_value(QLabel *w, int v) { QString s = QString::number(v); if (QString::compare(w->text(), s)) { w->setText(s); return true; } return false; } bool FuelPage::set_new_value(Pump *w, int v) { if (w->value() != !!v) { w->set_value(v ? Pump::ON : Pump::OFF); return true; } return false; } bool FuelPage::set_new_value(Valve *w, int v) { if (w->value() != !!v) { w->set_value(v ? Valve::OPEN : Valve::CLOSE); return true; } return false; } void FuelPage::set_value(ValueType t, int v) { bool newval = false; switch(t) { case FOB: newval = set_new_value(ui->disp_fob, v); break; case LL_FUEL_QUANT : newval = set_new_value(ui->disp_ll, v); break; case LC_FUEL_QUANT : newval = set_new_value(ui->disp_cl, v); break; case CC_FUEL_QUANT : newval = set_new_value(ui->disp_cc, v); break; case RC_FUEL_QUANT : newval = set_new_value(ui->disp_cr, v); break; case RR_FUEL_QUANT : newval = set_new_value(ui->disp_rr, v); break; case LL_FUEL_TEMP : newval = set_new_value(ui->disp_temp_ll, v); break; case LC_FUEL_TEMP : newval = set_new_value(ui->disp_temp_cl, v); break; case RC_FUEL_TEMP : newval = set_new_value(ui->disp_temp_cr, v); break; case RR_FUEL_TEMP : newval = set_new_value(ui->disp_temp_rr, v); break; case TAT : newval = set_new_value(ui->disp_tat, v); break; case SAT : newval = set_new_value(ui->disp_sat, v); break; case HH : newval = set_new_value(ui->disp_hh, v); break; case MM : newval = set_new_value(ui->disp_mm, v); break; case GW : newval = set_new_value(ui->disp_gw, v); break; case PUMP_LL : newval = set_new_value(ui->pump_left_left, v); break; case PUMP_LC : newval = set_new_value(ui->pump_left_center, v); break; case PUMP_CL : newval = set_new_value(ui->pump_center_left, v); break; case PUMP_CR : newval = set_new_value(ui->pump_center_right, v); break; case PUMP_RC : newval = set_new_value(ui->pump_right_center, v);break; case PUMP_RR : newval = set_new_value(ui->pump_right_right, v);break; case VALVE_ENG1 : newval = set_new_value(ui->val_eng1, v); break; case VALVE_APU : newval = set_new_value(ui->val_apu, v);break; case VALVE_XFEED : newval = set_new_value(ui->val_xfeed, v); break; case VALVE_ENG2 : newval = set_new_value(ui->val_eng2, v);break; case FF_ENG1 : newval = set_new_value(ui->disp_ff_eng1, v);break; case FF_ENG2 : newval = set_new_value(ui->disp_ff_eng2, v);break; } if (newval) update(); } FuelPage::~FuelPage() { //delete ui; }
[ "memo5@gmx.at" ]
memo5@gmx.at
7abef1f6585c64234067c009a8cd15691351e925
88903d85c7d1136188472020faf13d9d4036c370
/model.cpp
3a7d561529387985aadbbf659e7ec85e28398c49
[]
no_license
kosuke86/shooting_game
801dd90d2ed82ce46f9f880d8f0fb9e50730c23b
93e678459213396a0e9041c104195aba755c2c98
refs/heads/master
2021-01-10T07:56:46.969953
2016-04-09T03:44:59
2016-04-09T03:44:59
55,738,943
0
0
null
null
null
null
UTF-8
C++
false
false
32,125
cpp
/* * model.cpp * * Created on: 2013/12/09 * Author: yakoh */ //192.168.0.202 #include <iostream> #include "model.h" static int i,j,k; static float distance2(float,float); Model::Model() { // TODO Auto-generated constructor stub } Model::~Model() { // TODO Auto-generated destructor stub } int Model::single_judgeState(){ if(s->run == 0 and s->players[0].visible) { s->run = 1; for(i=1; i<max_players; i++) s->players[i].visible = 1; } else if(s->run == 1){ if(!s->players[1].visible and !s->players[2].visible and !s->players[3].visible) s->run = 2; else if(!s->players[0].visible) s->run = 3; } return s->run; } int Model::judgeState(){ if(s->run == 0){ for(i=0; i<max_players; i++){ if(s->players[i].attend and !s->players[i].visible) break; if(i == max_players-1) s->run = 1; } }if(s->run == 1){ s->winner=max_players; for(i=0; i<max_players; i++){ if(s->players[i].attend and s->players[i].visible and i<s->winner) s->winner = i; if(s->players[i].attend and s->players[i].visible and i>s->winner) {s->winner = max_players; break;} } if(s->winner < max_players) s->run = 2; } return s->run; } void Model::initModelWithScene(Scene *scene){ // std::cout << "Init" << std::endl; //scene=s; s=scene; s->run = 0; create_Map(); //マップを作成 //プレイヤーの初期化 for(i = 0; i < max_players; ++i) { s->players[i].attend = 0; s->players[i].visible = 0; s->players[i].hp = 100; s->players[i].base_angle = 0.0; s->players[i].angle = 0.0; s->players[i].type = 1; s->players[i].shot_type = 1; s->players[i].up_mode = 0; s->players[i].reload_time = 30; s->players[i].reload_count = s->players[i].reload_time; s->players[i].lock = 0; players[i].destroyed = 0; players[i].reload = 0; players[i].rl = 1; players[i].move_speed = players_para[1].move_speed; players[i].rotate_speed = players_para[1].rotate_speed; players[i].shot_power = players_para[1].shot_power; players[i].shot_speed = players_para[1].shot_speed; players[i].reload_speed = players_para[1].reload_speed; players[i].armor = players_para[1].armor; for (j = 1; j <= max_players; ++j) s->players[i].outside[j] = 0; for (j = 1; j <= max_tama_type; ++j) players[i].having_shot_type[j] = 0; //for (j = 1; j <= 4; ++j) players[i].level[j] = 1; for (j = 0; j < max_tama; ++j) s->players[i].tama[j].visible = 0; static int mx, my; do{ mx = g_random_int_range(1, map_mw-1); my = g_random_int_range(1, map_mh-1); }while(s->map[my][mx].type); players[i].x = (mx+0.5) * mapchip_size; players[i].y = (my+0.5) * mapchip_size; } for (i = 0; i < max_item; ++i) s->item[i].visible = 0; s->time = 0; } void Model::startMenu(int id, input_t *in){ //スタート画面での操作 //決定 if(s->players[id].lock == 0){ if(in->r and s->players[id].type < max_players_type) s->players[id].type++; if(in->l and s->players[id].type > 1) s->players[id].type--; if(in->enter) s->players[id].lock++; }else if(s->players[id].lock == 1){ if(in->r and s->players[id].shot_type < max_tama_type) s->players[id].shot_type++; if(in->l and s->players[id].shot_type > 1) s->players[id].shot_type--; if(in->enter) s->players[id].lock++; if(in->cancel) s->players[id].lock--; }else{ if(in->enter){ //選択したタイプから機体の能力値、初期射撃弾を決定 players[id].move_speed = players_para[s->players[id].type].move_speed; players[id].rotate_speed = players_para[s->players[id].type].rotate_speed; players[id].shot_power = players_para[s->players[id].type].shot_power; players[id].shot_speed = players_para[s->players[id].type].shot_speed; players[id].reload_speed = players_para[s->players[id].type].reload_speed; players[id].armor = players_para[s->players[id].type].armor; players[id].having_shot_type[s->players[id].shot_type] = 1; if(s->players[id].shot_type == 5) s->players[id].missile_number = 30; s->players[id].visible = 1; }if(in->cancel){ //s->players[id].outside[s->players[id].lock-1] = 0; //s->players[id].shot_type = 1; s->players[id].lock--; if(s->players[id].missile_number > 0) s->players[id].missile_number = 0; s->players[id].visible = 0; } } } void Model::preAction(void){ s->time++; //弾の時間消滅 for(i=0; i < max_players; ++i){ for(j=0; j < max_tama; ++j){ if(s->players[i].tama[j].visible){ s->players[i].tama[j].count++; if(s->players[i].tama[j].count >= tama[s->players[i].tama[j].type].visible_time){ s->players[i].tama[j].visible = 0; if(s->players[i].tama[j].type == 4) set_effect(players[i].tama[j].x, players[i].tama[j].y, 2, i); if(s->players[i].tama[j].type == 5) set_effect(players[i].tama[j].x, players[i].tama[j].y, 3, i); } } } } //アイテムの変化、時間消滅 for(i=0; i < max_item; ++i){ if(s->item[i].visible){ item[i].count++; if(s->item[i].type <= 4 and item[i].count % 30 == 0) { if(s->item[i].type == 4) s->item[i].type = 1; else s->item[i].type++; }else if(s->item[i].type == 11){ if(item[i].count > 200){ s->item[i].visible = 0; set_effect(item[i].x, item[i].y, 2, -1); }else if(item[i].count > 197) s->item[i].state = 5; else if(item[i].count > 194) s->item[i].state = 4; else if(item[i].count > 191) s->item[i].state = 3; else if(item[i].count > 10){ if(item[i].count % 10 < 5) s->item[i].state = 1; else s->item[i].state = 2; } } if(item[i].count >= 500) s->item[i].visible = 0; } } //リロード、リロードゲージの処理 for(i=0; i< max_players; ++i){ if(players[i].reload) { s->players[i].reload_count++; if(s->players[i].reload_count >= s->players[i].reload_time) players[i].reload = 0; s->players[i].reload_r = 1.0;//,s->players[i].reload_g = 1.0,s->players[i].reload_b = 0.0; } else s->players[i].reload_r = 0.0;//,s->players[i].reload_g = 1.0,s->players[i].reload_b = 0.0; } //プレイヤーのアイテム強化時間の処理 for(i=0; i< max_players; ++i){ if(s->players[i].up_mode > 0) { players[i].up_count++; if(players[i].up_count >= 500){ s->players[i].up_mode = 0; players[i].move_speed = players_para[s->players[i].type].move_speed; players[i].shot_power = players_para[s->players[i].type].shot_power; } } } //時間経過によるアイテムの出現 if((s->time+1)%500 == 0 or (s->time+1)%100 == 0){ for (i=0; i < max_item; ++i) { if(!s->item[i].visible){ s->item[i].visible = 1; item[i].count = 0; s->item[i].state = 0; if((s->time+1)%500 == 0) s->item[i].type = g_random_int_range(1, 5); else s->item[i].type = g_random_int_range(5, 12); int mx,my; do{ mx = g_random_int_range(1, map_mw-1); my = g_random_int_range(1, map_mh-1); }while(s->map[my][mx].type); item[i].x = (mx+0.5) * mapchip_size; item[i].y = (my+0.5) * mapchip_size; break; } } } //時間経過によるエフェクトの変化、消滅 for(i=0; i < max_effect; ++i){ if(s->effect[i].visible){ s->effect[i].count++; switch(s->effect[i].type){ case 1: if(s->effect[i].count >= 69) s->effect[i].visible = 0; break; case 2: if(s->effect[i].count <= 10) s->effect[i].r += 5.0; if(s->effect[i].count >= 15) s->effect[i].w -= 10.0, s->effect[i].r += 5.0; if(s->effect[i].count >= 25) s->effect[i].visible = 0; effect[i].cr = s->effect[i].r + s->effect[i].w/2; break; case 3: if(s->effect[i].count <= 10) s->effect[i].r += 2.0; if(s->effect[i].count >= 15) s->effect[i].w -= 4.0, s->effect[i].r += 2.0; if(s->effect[i].count >= 25) s->effect[i].visible = 0; effect[i].cr = s->effect[i].r + s->effect[i].w/2; break; case 4: s->effect[i].r -= 0.5; s->effect[i].a -= 0.1; if(s->effect[i].count >= 10) s->effect[i].visible = 0; break; case 5: effect[i].x = players[effect[i].target].x; effect[i].y = players[effect[i].target].y; if(s->effect[i].count <= 10) s->effect[i].r += 4.0; if(s->effect[i].count > 10) s->effect[i].r += 0.4; if(s->effect[i].count >= 20) s->effect[i].visible = 0; break; } } } //プレイヤーのダメージ表現の時間 for(i=0; i < max_players; ++i){ if(s->players[i].damage > 0) players[i].damage_count++; if(s->players[i].damage == 1 and players[i].damage_count >= 5){ s->players[i].damage = 0; players[i].move_speed = players_para[s->players[i].type].move_speed; }else if(s->players[i].damage == 2 and players[i].damage_count >= 10){ s->players[i].damage = 0; players[i].move_speed = players_para[s->players[i].type].move_speed; } } } void Model::postAction(void){ // プレイヤー当たり判定用の変数を計算 for(i=0; i < max_players; ++i) { players[i].cx_off = cos(s->players[i].base_angle + M_PI/2) * players_y_off; players[i].cy_off = sin(s->players[i].base_angle + M_PI/2) * players_y_off; players[i].cx = players[i].x + players[i].cx_off; players[i].cy = players[i].y + players[i].cy_off; } //プレイヤーと弾の当たり判定 for(i=0; i < max_players; ++i) { for(j=0; j < max_players; ++j) { for (k=0; k < max_tama; ++k) { if(distance2(players[i].cx - players[j].tama[k].x, players[i].cy - players[j].tama[k].y) < (players_cr + tama[s->players[j].tama[k].type].r) * (players_cr + tama[s->players[j].tama[k].type].r) and s->players[i].visible and s->players[j].tama[k].visible and i!=j) { if(s->players[j].tama[k].type < 4){ s->players[i].hp -= tama[s->players[j].tama[k].type].power * players[j].shot_power / players[i].armor; s->players[i].damage = 1; players[i].damage_count = 0; players[i].move_speed *= (100 - tama[s->players[j].tama[k].type].power)/ (3 * 100); }else if(s->players[j].tama[k].type == 4) set_effect(players[j].tama[k].x, players[j].tama[k].y, 2, j); else if(s->players[j].tama[k].type == 5) set_effect(players[j].tama[k].x, players[j].tama[k].y, 3, j); s->players[j].tama[k].visible = 0; } } } } //プレイヤーと爆発エフェクトの当たり判定 for(i=0; i < max_players; ++i) { for(j=0; j < max_effect; ++j) { if((distance2(players[i].cx - effect[j].x, players[i].cy - effect[j].y) < (players_cr + effect[j].cr) * (players_cr + effect[j].cr) and s->players[i].visible and s->effect[j].visible and effect[j].damage_flag[i]) and (s->effect[j].type == 2 or s->effect[j].type == 3)) { if(s->effect[j].type == 2 and effect[j].target < 0) s->players[i].hp -= tama[4].power / players[i].armor; //爆弾ダメージ else if(s->effect[j].type == 2) s->players[i].hp -= tama[4].power * players[effect[j].target].shot_power / players[i].armor;//爆発弾ダメージ else if(s->effect[j].type == 3) s->players[i].hp -= tama[5].power * players[effect[j].target].shot_power / players[i].armor;//ミサイルダメージ s->players[i].damage = 2; players[i].damage_count = 0; effect[j].damage_flag[i] = 0; players[i].move_speed *= (100 - tama[s->effect[j].type+2].power)/ (3 * 100); players[i].vx += 0.25 * tama[s->effect[j].type+2].power / players[i].armor * cos(atan2(players[i].y - effect[j].y, players[i].x - effect[j].x)); players[i].vy += 0.25 * tama[s->effect[j].type+2].power / players[i].armor * sin(atan2(players[i].y - effect[j].y, players[i].x - effect[j].x)); } } } //アイテムの接触判定 for(i=0; i < max_players; ++i) { for (j=0; j < max_item; ++j) { if(distance2(players[i].cx - item[j].x, players[i].cy - item[j].y) < (players_cr + item_cr) * (players_cr + item_cr) and s->players[i].visible and s->item[j].visible) { if(s->item[j].type < 11){ s->item[j].visible = 0; set_effect(players[i].x, players[i].y, 5, i); if(s->item[j].type <= 4) players[i].having_shot_type[s->item[j].type] = 1; else if(s->item[j].type <= 7){ s->players[i].up_mode = s->item[j].type - 4; players[i].up_count = 0; if(s->item[j].type == 5) players[i].move_speed *= 1.2; else if(s->item[j].type == 6) players[i].shot_power *= 1.2; }else if(s->item[j].type <= 9){ players[i].move_speed *= 1.2; players[i].having_shot_type[5] = 1; s->players[i].missile_number += (s->item[j].type - 7) * 5; if(s->players[i].missile_number > max_missile) s->players[i].missile_number = max_missile; }else{ s->players[i].hp += 10; if(s->players[i].hp > max_hp) s->players[i].hp = max_hp; } } else if(s->item[j].type == 11 and s->item[j].state > 0){ s->item[j].visible = 0; set_effect(item[j].x, item[j].y, 2, -1); } } } } //機体とブロックの接触判定 for(i=0; i < max_players; ++i) { if(s->players[i].visible) block_and_player_hitCheck(&players[i]); } //弾とブロックの接触判定(水にはぶつからない) for(i=0; i < max_players; ++i) { for(j=0; j < max_tama; ++j) { if(s->players[i].tama[j].visible) block_and_tama_hitCheck(i, j); } } //弾とミサイルの当たり判定 for(i=0; i < max_players; ++i) { for(j=0; j < max_players; ++j) { for (k=0; k < max_tama; ++k) { for (int l=0; l < max_tama; ++l) { if(distance2(players[i].tama[k].x - players[j].tama[l].x, players[i].tama[k].y - players[j].tama[l].y) < (tama[s->players[i].tama[k].type].r + tama[s->players[j].tama[l].type].r) * (tama[s->players[i].tama[k].type].r + tama[s->players[j].tama[l].type].r) and s->players[i].tama[k].visible and s->players[j].tama[l].visible and i!=j) { if(s->players[i].tama[k].type == 5) s->players[i].tama[k].visible = 0, set_effect(players[i].tama[k].x, players[i].tama[k].y, 3); if(s->players[j].tama[l].type == 5) s->players[j].tama[l].visible = 0, set_effect(players[j].tama[l].x, players[j].tama[l].y, 3); } } } } } //HPの色 for(i=0; i<max_players; ++i){ if (s->players[i].hp >=40) s->players[i].hp_r =0.0,s->players[i].hp_g =0.0,s->players[i].hp_b =1.0; else if(s->players[i].hp >=15) s->players[i].hp_r =1.0,s->players[i].hp_g =1.0,s->players[i].hp_b =0.0; else s->players[i].hp_r =1.0,s->players[i].hp_g =0.0,s->players[i].hp_b =0.0; } //撃破判定 for(i=0; i<max_players; ++i){ if(s->players[i].hp <= 0 and !players[i].destroyed){ s->players[i].hp = 0; s->players[i].visible = 0; players[i].destroyed = 1; set_effect(players[i].x, players[i].y, 1); } } //ミサイルのロックオン判定(砲塔の向きから一定角度内 & 自機から一定範囲内 にいる他プレイヤーのうち、最も近いプレイヤーをロック) for(i=0; i<max_players; ++i){ float min_distance = window_w/2 * window_w/2; s->players[i].lock = -5; for(j=0; j<max_players; ++j){ if(s->players[j].visible and s->players[i].shot_type == 5){ float angle = atan2(players[j].y - players[i].y, players[j].x - players[i].x); float angle_gap; if(angle >= M_PI/2) angle_gap = fabs(angle - (s->players[i].angle + 3*M_PI/2)); else angle_gap = fabs(angle - (s->players[i].angle - M_PI/2)); if(angle_gap < M_PI/4 and distance2(players[j].y - players[i].y, players[j].x - players[i].x) < min_distance and i!=j){ min_distance = distance2(players[j].y - players[i].y, players[j].x - players[i].x); s->players[i].lock = -(j+1); players[i].lock_count[j]++; if(s->players[j].up_mode < 3 and players[i].lock_count[j] > 30) s->players[i].lock = j; else if(s->players[j].up_mode == 3 and players[i].lock_count[j] > 50) s->players[i].lock = j; } else players[i].lock_count[j] = 0; } } } //相対座標の決定 for(i=0; i < max_players; ++i){ float px = players[i].x; float py = players[i].y; float camera_x, camera_y; if(px < window_w/2) camera_x = -(window_w/2 - px); else if(px > map_w - window_w/2) camera_x = window_w/2 - (map_w - px); else camera_x = 0; if(py < window_h/2) camera_y = -(window_h/2 - py); else if(py > map_h - window_h/2) camera_y = window_h/2 - (map_h - py); else camera_y = 0; s->xx[i] = window_w/2 - px + camera_x; s->yy[i] = window_h/2 - py + camera_y; for(j=0; j < max_players; ++j){ s->players[j].xx[i] = players[j].x + s->xx[i]; s->players[j].yy[i] = players[j].y + s->yy[i]; for (k=0; k < max_tama; ++k) { s->players[j].tama[k].xx[i] = players[j].tama[k].x + s->xx[i]; s->players[j].tama[k].yy[i] = players[j].tama[k].y + s->yy[i]; } }for (j=0; j <max_item; ++j) { s->item[j].xx[i] = item[j].x + s->xx[i]; s->item[j].yy[i] = item[j].y + s->yy[i]; }for (j=0; j <max_effect; ++j) { s->effect[j].xx[i] = effect[j].x + s->xx[i]; s->effect[j].yy[i] = effect[j].y + s->yy[i]; } } //他プレイヤーが画面外にいるときの処理 for(i=0; i < max_players; ++i){ for(j=0; j < max_players; ++j){ float pxx = s->players[j].xx[i]; float pyy = s->players[j].yy[i]; s->players[j].marker_angle[i] = atan2(s->players[j].yy[i] - window_h/2, s->players[j].xx[i] - window_w/2) + M_PI/2; s->players[j].outside[i] = 0; if(fabs(atan((pyy - window_h/2)/(pxx - window_w/2))) < atan(float(window_h)/float(window_w))){ if(pxx > window_w){ s->players[j].marker_xx[i] = window_w-10; s->players[j].outside[i] = 1; s->players[j].marker_yy[i] = window_h/2 + (pyy - window_h/2) * window_w/2 / (pxx - window_w/2); }else if(pxx < 0){ s->players[j].marker_xx[i] = 10; s->players[j].outside[i] = 1; s->players[j].marker_yy[i] = window_h/2 - (pyy - window_h/2) * window_w/2 / (pxx - window_w/2); } }else{ if(pyy > window_h){ s->players[j].marker_yy[i] = window_h-10; s->players[j].outside[i] = 1; s->players[j].marker_xx[i] = window_w/2 + (pxx - window_w/2) * window_h/2 / (pyy - window_h/2); }else if(pyy < 0){ s->players[j].marker_yy[i] = 10; s->players[j].outside[i] = 1; s->players[j].marker_xx[i] = window_w/2 - (pxx - window_w/2) * window_h/2 / (pyy - window_h/2); } } } } } void Model::stepPlayer(int id, input_t *in){ //自機本体の方向転換、移動 int x_angle = in->right - in->left; int y_angle = in->up - in->down; if(!x_angle and !y_angle){ players[id].accel_x = 0.0; players[id].accel_y = 0.0; }else{ if(x_angle == 0 and y_angle == -1) s->players[id].base_angle = M_PI; else s->players[id].base_angle = x_angle*M_PI * (2-y_angle)/4; players[id].accel_x = players[id].move_speed * sin(s->players[id].base_angle); players[id].accel_y = -players[id].move_speed * cos(s->players[id].base_angle); } //砲塔の回転 s->players[id].angle += M_PI/16 * players[id].rotate_speed * (in->yaw_right - in->yaw_left); if(s->players[id].angle >= M_PI) s->players[id].angle -= 2*M_PI; if(s->players[id].angle < -M_PI) s->players[id].angle += 2*M_PI; //弾の発射 if (in->shot and !players[id].reload and s->players[id].visible and !(s->players[id].shot_type == 5 and s->players[id].missile_number <= 0)){ for (i=0; i < max_tama; ++i) { if (!s->players[id].tama[i].visible){ s->players[id].tama[i].visible = 1; s->players[id].tama[i].count = 0; s->players[id].tama[i].type = s->players[id].shot_type; players[id].reload = 1; s->players[id].reload_count = 0; s->players[id].reload_time = tama[s->players[id].tama[i].type].reload_time / players[id].reload_speed; s->players[id].tama[i].angle = s->players[id].angle; if(s->players[id].tama[i].type < 5){ players[id].tama[i].x = players[id].x + cos(s->players[id].angle-M_PI/2)*90; players[id].tama[i].y = players[id].y + sin(s->players[id].angle-M_PI/2)*90; players[id].tama[i].vx = tama[s->players[id].tama[i].type].v * players[id].shot_speed * cos(s->players[id].tama[i].angle - M_PI/2); players[id].tama[i].vy = tama[s->players[id].tama[i].type].v * players[id].shot_speed * sin(s->players[id].tama[i].angle - M_PI/2); } else if(s->players[id].tama[i].type == 5 and s->players[id].missile_number > 0){ players[id].rl *= -1; players[id].tama[i].x = players[id].x + players[id].rl * cos(s->players[id].angle)*30; players[id].tama[i].y = players[id].y + players[id].rl * sin(s->players[id].angle)*30; players[id].tama[i].vx = tama[s->players[id].tama[i].type].v/2 * players[id].rl * cos(s->players[id].tama[i].angle); players[id].tama[i].vy = tama[s->players[id].tama[i].type].v/2 * players[id].rl * sin(s->players[id].tama[i].angle); players[id].tama[i].lock = s->players[id].lock; s->players[id].missile_number--; if(s->players[id].missile_number <= 0) { in->change_shot = 1; players[id].having_shot_type[5] = 0; } } break; } } } //弾の切り替え if (in->change_shot){ for(int i = 0; i < max_tama_type; i++){ if(s->players[id].shot_type == max_tama_type) s->players[id].shot_type = 1; else s->players[id].shot_type++; if(players[id].having_shot_type[s->players[id].shot_type]) break; } } //プレイヤーの移動 players[id].ax = players[id].accel_x - players_move_c * players[id].vx; players[id].vx += players[id].ax; players[id].x += players[id].vx; players[id].ay = players[id].accel_y - players_move_c * players[id].vy; players[id].vy += players[id].ay; players[id].y += players[id].vy; //弾の移動 for (i=0; i < max_tama; ++i) { if(s->players[id].tama[i].visible){ if(s->players[id].tama[i].type == 5 and s->players[id].tama[i].count >= 5) missile_move(id, i); players[id].tama[i].x += players[id].tama[i].vx; players[id].tama[i].y += players[id].tama[i].vy; } } } //1人プレイのときは他の3機がCPUとして以下の行動をする void Model::CPU_Action(int id, input_t *in){ //キー入力を初期化 in->right = in->left = in->up = in->down = in->yaw_right = in->yaw_left = in->shot = 0; //常に射撃 in->shot = 1; //一定間隔で移動方向を変える(止まるときもある) static int x_move[3], y_move[3]; if(s->time%100 == 0){ x_move[id-1] = g_random_int_range(0, 3); y_move[id-1] = g_random_int_range(0, 3); } if(x_move[id-1] == 1) in->right = 1; else if(x_move[id-1] == 2) in->left = 1; if(y_move[id-1] == 1) in->up = 1; else if(y_move[id-1] == 2) in->down = 1; //砲塔は常に自機を狙う float target_angle; target_angle = atan2(players[0].y - players[id].y, players[0].x - players[id].x); if(target_angle >=M_PI/2) target_angle -= 3*M_PI/2; else target_angle += M_PI/2; if(fabs(target_angle - s->players[id].angle) > M_PI/32){ if(s->players[id].angle < target_angle) in->yaw_right = 1; else if(s->players[id].angle > target_angle) in->yaw_left = 1; } } //位置、種類、対象を指定してエフェクトを発生させる void Model::set_effect(float x,float y,int type, int target){ for(int i=0; i < max_effect; i++){ if(!s->effect[i].visible){ effect[i].x = x; effect[i].y = y; effect[i].target = target; s->effect[i].type = type; s->effect[i].visible = 1; s->effect[i].count = 0; if(type == 2) s->effect[i].r = 0.0, s->effect[i].w = 100.0; else if(type == 3) s->effect[i].r = 0.0, s->effect[i].w = 40.0; else if(type == 4) s->effect[i].r = 5.0, s->effect[i].a = 1.0; else if(type == 5) s->effect[i].r = 30.0; if(type == 2 or type == 3) for(int j=0; j < max_players; j++) effect[i].damage_flag[j] = 1; break; } } } //ミサイルの移動計算を行う void Model::missile_move(int id, int i){ const int type = 5; const float move_c = 0.05; const float accel = move_c * tama[type].v * players[id].shot_speed; const float remote_value = M_PI/96; //ミサイル追尾性能(1フレームでの最大補正角度) float x = players[id].tama[i].x; float y = players[id].tama[i].y; if(players[id].tama[i].lock >= 0){ int target = players[id].tama[i].lock; float target_angle = atan2(players[target].y - players[id].tama[i].y, players[target].x - players[id].tama[i].x); if(target_angle >=M_PI/2) target_angle -= 3*M_PI/2; else target_angle += M_PI/2; if(fabs(target_angle - s->players[id].tama[i].angle) < remote_value) s->players[id].tama[i].angle = target_angle; else if(s->players[id].tama[i].angle < target_angle) s->players[id].tama[i].angle += remote_value; else if(s->players[id].tama[i].angle > target_angle) s->players[id].tama[i].angle -= remote_value; } float accel_x = accel * cos(s->players[id].tama[i].angle - M_PI/2); float accel_y = accel * sin(s->players[id].tama[i].angle - M_PI/2); float ax = accel_x - move_c * players[id].tama[i].vx; float ay = accel_y - move_c * players[id].tama[i].vy; players[id].tama[i].vx += ax; players[id].tama[i].vy += ay; if(s->players[id].tama[i].count%3 == 0) set_effect(x - cos(s->players[id].tama[i].angle - M_PI/2) * 10, y - sin(s->players[id].tama[i].angle - M_PI/2) * 10, 4); } //二点間の距離の二乗を返す static float distance2(float x, float y){ return x * x + y * y; } //引数の座標のマップチップ種類を返す int Model::get_MapChip(int mx, int my){ if(mx < 0 or mx >= map_mw or my < 0 or my >= map_mh) return 1; return s->map[my][mx].type; } //マップのランダム生成アルゴリズム void Model::create_Map(){ //マップセルの初期化(外周ブロックのみにする) for(int y = 0; y < map_mh; y++){ for(int x = 0; x < map_mw; x++){ if(x==0 or x==map_mw-1 or y==0 or y==map_mh-1) s->map[y][x].type = 1; else s->map[y][x].type = 0; } } //フィールドを複数の部屋に分割(ランダムサイズで二分割を繰り返す) int div_type = g_random_int_range(0, 2); if(div_type == 0) div_type = -1; room[0].mx = 1; room[0].my = 1; room[0].mw = map_mw-2; room[0].mh = map_mh-2; int temp = 0; for(i = 1; i < max_room; i++,div_type*=-1){ if(div_type == 1){ room[i].mw = g_random_int_range(room[temp].mw * min_room_area /100, room[temp].mw * max_room_area /100); room[i].mh = room[temp].mh; room[temp].mw = room[temp].mw - room[i].mw; room[i].mx = room[temp].mx + room[temp].mw; room[i].my = room[temp].my; if(room[i].mw > room[temp].mw) temp = i; }if(div_type == -1){ room[i].mw = room[temp].mw; room[i].mh = g_random_int_range(room[temp].mh * min_room_area /100, room[temp].mh * max_room_area /100); room[temp].mh = room[temp].mh - room[i].mh; room[i].mx = room[temp].mx; room[i].my = room[temp].my + room[temp].mh; if(room[i].mh > room[temp].mh) temp = i; } } //各部屋にブロックをランダムに選んだパターンで配置 for(i = 0; i < max_room; i++){ set_MapChip(&room[i], g_random_int_range(0,2)); } //配置位置(周囲のブロックセルの有無)からブロックセルの種類を分類 for(int y = 0; y < map_mh; y++){ for(int x = 0; x < map_mw; x++){ if(s->map[y][x].type > 0) judge_MapChip(x, y); } } } //ルーム内にチップをランダムに選ばれたパターンで配置する void Model::set_MapChip(m_room_t *r, int type){ int mx, mxs, mxl; int my, mys, myl; int mw, mh; mxs = r->mx; mxl = mxs + r->mw - 1; mys = r->my; myl = mys + r->mh - 1; int block_type = g_random_int_range(1, 3); switch(type){ case 0: mx = g_random_int_range(mxs, mxl+1); my = g_random_int_range(mys, myl+1); mw = g_random_int_range(1, mxl-mx+2); mh = g_random_int_range(1, myl-my+2); for(int y=my; y < my+mh; y++){ for(int x=mx; x < mx+mw; x++){ s->map[y][x].type = block_type; } } break; case 1: mx = g_random_int_range(mxs, mxl-1); my = g_random_int_range(mys, myl-1); mw = g_random_int_range(3, mxl-mx+2); mh = g_random_int_range(3, myl-my+2); int del = 0; do{ for(int y=my; y < my+mh; y++){ for(int x=mx; x < mx+mw; x++){ if(((x==mx or x==mx+mw-1) and y!=my and y!=my+mh-1) or ((y==my or y==my+mh-1) and x!=mx and x!=mx+mw-1)){ s->map[y][x].type = g_random_int_range(0,2); if(s->map[y][x].type > 0) s->map[y][x].type = block_type; else del++; } } } }while(del < 1); break; } } //配置位置(周囲のセルの状態)からチップの種類を分類 void Model::judge_MapChip(int mx, int my){ for(int i=0; i < 4; i++){ int vx = (i<2)? -1 : 1; int vy = (0<i and i<3)? -1 : 1; int mc = get_MapChip(mx, my ); int xc = get_MapChip(mx + vx, my ); int yc = get_MapChip(mx, my + vy); int xyc = get_MapChip(mx + vx, my + vy); //int chip = &s->map[my][mx].chip; int n = 4; if(mc == xc and mc == yc and mc == xyc) s->map[my][mx].chip[i] = 4 * n + i; else if(mc == xc and mc == yc) s->map[my][mx].chip[i] = 3 * n + i; else if(mc == yc) s->map[my][mx].chip[i] = 2 * n + 1 + (1+vx); else if(mc == xc) s->map[my][mx].chip[i] = 2 * n + (1-vy); else s->map[my][mx].chip[i] = 1 * n + i; } } //プレイヤーとブロックセルとの当たり判定を行う void Model::block_and_player_hitCheck(m_player_t *p){ float x, xs, xl; float y, ys, yl; int mx, mxs, mxl; int my, mys, myl; float r = players_cr; x = p->cx; y = p->cy; xs = x - r; xl = x + r; ys = y - r; yl = y + r; mx = x / mapchip_size; my = y / mapchip_size; mxs = xs / mapchip_size; mxl = xl / mapchip_size; mys = ys / mapchip_size; myl = yl / mapchip_size; //円の十字方向の端4点がブロックセル内かどうかを調べ、そうなら位置補正 if(s->map[my][mxs].type > 0 or s->map[my][mxl].type > 0 or s->map[mys][mx].type > 0 or s->map[myl][mx].type > 0){ if(s->map[my][mxs].type > 0) p->x = (mxs+1) * mapchip_size + r - p->cx_off, p->vx = 0; if(s->map[my][mxl].type > 0) p->x = (mxl+0) * mapchip_size - r - p->cx_off, p->vx = 0; if(s->map[mys][mx].type > 0) p->y = (mys+1) * mapchip_size + r - p->cy_off, p->vy = 0; if(s->map[myl][mx].type > 0) p->y = (myl+0) * mapchip_size - r - p->cy_off, p->vy = 0; } //円のあるセルの周囲にあるブロックセルを調べ、その角が円内部にあるかどうかを調べ、そうなら位置補正 else{ float bxs, bxl; float bys, byl; bxs = (mx+0) * mapchip_size; bxl = (mx+1) * mapchip_size; bys = (my+0) * mapchip_size; byl = (my+1) * mapchip_size; if(s->map[my-1][mx-1].type > 0 and distance2(x-bxs, y-bys) < r*r) { float a = (y-bys)/(x-bxs); float dx = sqrt(r*r/(a*a+1)); p->x = bxs + dx - p->cx_off; p->y = bys + a*dx - p->cy_off; if(!p->accel_x < 0) p->vx = 0; if(!p->accel_y < 0) p->vy = 0; }if(s->map[my-1][mx+1].type > 0 and distance2(bxl-x, y-bys) < r*r) { float a = (y-bys)/(bxl-x); float dx = sqrt(r*r/(a*a+1)); p->x = bxl - dx - p->cx_off; p->y = bys + a*dx - p->cy_off; if(!p->accel_x > 0) p->vx = 0; if(!p->accel_y < 0) p->vy = 0; }if(s->map[my+1][mx-1].type > 0 and distance2(x-bxs, byl-y) < r*r) { float a = (byl-y)/(x-bxs); float dx = sqrt(r*r/(a*a+1)); p->x = bxs + dx - p->cx_off; p->y = byl - a*dx - p->cy_off; if(!p->accel_x < 0) p->vx = 0; if(!p->accel_y > 0) p->vy = 0; }if(s->map[my+1][mx+1].type > 0 and distance2(bxl-x, byl-y) < r*r) { float a = (byl-y)/(bxl-x); float dx = sqrt(r*r/(a*a+1)); p->x = bxl - dx - p->cx_off; p->y = byl - a*dx - p->cy_off; if(!p->accel_x > 0) p->vx = 0; if(!p->accel_y > 0) p->vy = 0; } } } //弾とブロックの当たり判定を行う。ただし、ここでの弾の当たり判定は正方形(円だとややこしい) void Model::block_and_tama_hitCheck(int id, int i){ float x, xs, xl; float y, ys, yl; int mxs, mxl; int mys, myl; float r = tama[s->players[id].tama[i].type].r; x = players[id].tama[i].x; y = players[id].tama[i].y; xs = x - r; xl = x + r; ys = y - r; yl = y + r; mxs = xs / mapchip_size; mxl = xl / mapchip_size; mys = ys / mapchip_size; myl = yl / mapchip_size; if(s->map[mys][mxs].type == 1 or s->map[mys][mxl].type == 1 or s->map[myl][mxs].type == 1 or s->map[myl][mxl].type == 1){ s->players[id].tama[i].visible = 0; if(s->players[id].tama[i].type ==4) set_effect(x, y, 2, id); else if(s->players[id].tama[i].type ==5) set_effect(x, y, 3, id); } }
[ "nishimura@west.sd.keio.ac.jp" ]
nishimura@west.sd.keio.ac.jp
fee300cfe6c5a67ec6a4509504b83ee80b5fa62e
b1f0a0a7ef24f66392919e51efc2a994bbf84f06
/Source/Shooter/Networking/GameServices.h
e40cf5d823befdc3e22eacea57892b619404c42b
[]
no_license
rchudin/Shooter
3b729d1a40f52ba863a2e76d7ef8854f96d93783
4ea69428d2255054714427bf34f3cec35f610bf6
refs/heads/master
2023-01-22T10:50:54.259525
2020-12-05T14:56:12
2020-12-05T14:56:12
262,086,955
8
3
null
null
null
null
UTF-8
C++
false
false
856
h
// Copyright © 2020 ruslanchudin.com #pragma once #include "CoreMinimal.h" #include "UdpNetworking.h" #include "GameServicesInterface.h" class SHOOTER_API FGameServices : public IGameServicesInterface { FGameServices(const FGameServices& FGameServices): Address(FGameServices.Address), Port(FGameServices.Port){} EGameServicesStatus Status = EGameServicesStatus::Undefined; TSharedPtr<FUdpNetworking> UdpNetworking; FString Address; int32 Port; bool InitUdpNetworking(); bool Ping(); public: FGameServices(FString AddressServices, const int32& PortServices); inline bool operator==(const EGameServicesStatus& Other) const { return Status == Other; } inline operator EGameServicesStatus() const { return Status; } virtual bool FindServers(TArray<FServerInstance>* Servers) override; };
[ "me@ruslanchudin.com" ]
me@ruslanchudin.com
3ad9d3ddda16ecf7078e2bb4f3522d7f5b2e8b52
309c15eec78712a7ecbfa895e61a548858ea5828
/user/file.h
c4d909e5373ca7bf5df4b984e19491f311b0bb39
[ "MIT" ]
permissive
Lornatang/ssm
595dc7d1deec63cfdad6125f17a603b7a7a529de
b5db2568878c0d866bf32f16cbead67f10a9a15d
refs/heads/master
2020-03-27T08:54:00.091814
2018-08-30T10:03:25
2018-08-30T10:03:25
146,296,554
1
1
null
null
null
null
UTF-8
C++
false
false
1,059
h
// // Created by mac on 2018/8/28. // This is the file processing for the user user // /** * Class: User * 1.void show() show account data. * */ #ifndef SSM_USER_FILE_H #define SSM_USER_FILE_H #include "user.h" #include "base.h" using namespace std; //从文件读入数据 void User::userRead() { userNode *p; p = head; ifstream in(userDataFile); if (!in) { cout << "None user info!" << endl; return; } while (!in.eof()) { int id; string passwd; string name; string address; string tel; in >> id >> passwd >> name >> address >> tel; userInsert(id, passwd, name, address, tel); } } //保存学生信息 void User::userSave() { userNode *p; p = head->next; ofstream out(userDataFile); if (!out) { cerr << ("Can't open user data file!.\n"); return; } while (p != nullptr) { out << p->id << ("\t"); out << p->name << ("\t"); out << p->passwd << ("\t"); out << p->address << ("\t"); out << p->tel << "\n"; p = p->next; } } #endif //LORNABK_FILE_H
[ "shiyipaisizuo@gmail.com" ]
shiyipaisizuo@gmail.com
6b0efdde1bad9a65f7e26aa5323829d810907f68
0dcbf4505e89db18b1635308cea23ea06a0ac8bd
/lib/Tetris/include/TFigureUnit.h
118046ac3bac420fc692511bd6151328fff1ad92
[ "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
PuppyRush/SDL2_Tetris_Client
94c0da8147efe35cf7e467c9eabf89e93140eb7f
f61b35a866b305d13dfa7227a43ef2583572be78
refs/heads/master
2023-04-15T09:11:03.334300
2023-04-03T08:58:35
2023-04-03T08:58:35
153,282,402
1
0
null
2019-04-02T14:45:30
2018-10-16T12:33:57
C++
UTF-8
C++
false
false
1,903
h
#ifndef TETRISMODULE_TFIGUREUNIT_H #define TETRISMODULE_TFIGUREUNIT_H #if _MSC_VER > 1200 #pragma once #endif #include "GameInterface/include/TypeTraits.h" #include "GameInterface/include/Type.h" #include "GameInterface/include/TStruct.h" #include "SDL2EasyGUI/include/SEG_Type.h" #include "SDL2EasyGUI/include/SEG_Struct.h" #include "TProperty.h" namespace tetris_module { class TFigureUnit final { public: TFigureUnit(); TFigureUnit(const seg::SEG_Point point, const game_interface::t_age age, const seg::ColorCode color, const tetris_module::UnitType type); ~TFigureUnit(); bool operator!=(const TFigureUnit& unit); inline seg::SEG_Point getPoint() const noexcept { return m_point; } inline game_interface::t_age getAge() const noexcept { return m_age; } inline seg::SEG_Color getColor() const noexcept { return m_color; } inline UnitType getType() const noexcept { return m_type; } inline void set(const seg::SEG_Point& m_point) { this->m_point = m_point; } inline void set(seg::SEG_Point&& m_point) { this->m_point = m_point; } inline void set(const game_interface::t_age age) noexcept { this->m_age = age; } inline void set(const seg::SEG_Color& color) noexcept { this->m_color = color; } inline void set(seg::SEG_Color&& color) noexcept { this->m_color = color; } inline void set(const UnitType& m_type) noexcept { this->m_type = m_type; } static TFigureUnit& getDefaultUnit() { static TFigureUnit unit(seg::SEG_Point(0, 0), 0, seg::ColorCode::none, UnitType::Empty); return unit; } private: seg::SEG_Point m_point; seg::SEG_Color m_color; game_interface::t_age m_age; UnitType m_type; }; } #endif
[ "gooddaumi@gmail.com" ]
gooddaumi@gmail.com
b2da1565b68208240cfd9a21c6a6211c346dc94e
37dfdf135379de0b02dee9d3621029e13a31fd24
/CH06_3DPhysics/ソースファイル/3DPhysics_1_1.cpp
dc3255fcdda21a873d1e81d29ffa79eda0c829b0
[]
no_license
starcatneko/-
0c19f612a91a580bb8587037c929c84bac7ac708
cf5f36aa9437f56f2a8b0bcd51be519a5acbaddb
refs/heads/master
2021-10-11T11:37:20.384137
2019-01-25T08:39:38
2019-01-25T08:39:38
160,148,658
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
33,749
cpp
//------------------------------------------------------------ // 3DPhysics_1_1.cpp // 簡単な影の生成 // //------------------------------------------------------------ #include <D3D11.h> #include <D3Dcompiler.h> #include <DirectXMath.h> #include<d3d11shader.h> #include<DirectXTex\DirectXTex.h> #include<WICTextureLoader\WICTextureLoader.h> #define VIEW_WIDTH 800 // 画面幅 #define VIEW_HEIGHT 600 // 画面高さ #define PI 3.1415927f // 円周率 #define ROT_SPEED ( PI / 100.0f ) // 回転速度 #define CORNER_NUM 20 // 角数 #define GROUND_SIZE 20.0f // 床のサイズ #define TURRET_R 1.0f // 砲塔サイズ #define GUNBARREL_LEN 2.0f // 砲身長さ #define GROUND_Y 0.0f // 地面y座標 using namespace DirectX; // 頂点構造体 struct CUSTOMVERTEX { XMFLOAT4 v4Pos; XMFLOAT2 v2UV; }; // プレイヤー構造体 struct MY_PLAYER { float fTheta; // 仰角 float fPhi; // 旋回角 }; MY_PLAYER Player_1; // プレイヤーデータ // 影行列の生成 // 頂点位置と光の進行方向から、平面的な地面の // どこに影が落ちるかを計算する式を行列化したものを生成 XMMATRIX CreateShadowMatrix( XMFLOAT3 v3Light, float fGround_y ) { XMMATRIX matShadowed; matShadowed = XMMatrixIdentity(); // 単位行列に //影を落とすように行列の各値を設定してください。 matShadowed.r[0].m128_f32[0] = 1; matShadowed.r[3].m128_f32[0] *= v3Light.x; matShadowed.r[1].m128_f32[1] = fGround_y; matShadowed.r[3].m128_f32[1] = 0.01; matShadowed.r[2].m128_f32[2] *= v3Light.z*v3Light.y; matShadowed.r[3].m128_f32[2] = 0;//v3Light.z; return matShadowed; // 結果 } int InitPlayer( void ) // プレイヤーの初期化 { // プレイヤー1 Player_1.fTheta = PI / 4.0f; Player_1.fPhi = 0.0f; return 0; } int MovePlayer( void ) // 球の移動 { // 左 if ( GetAsyncKeyState( VK_LEFT ) ) { Player_1.fPhi -= ROT_SPEED; } // 右 if ( GetAsyncKeyState( VK_RIGHT ) ) { Player_1.fPhi += ROT_SPEED; } // 奥 if ( GetAsyncKeyState( VK_UP ) ) { Player_1.fTheta -= ROT_SPEED; if ( Player_1.fTheta < 0.0f ) { Player_1.fTheta = 0.0f; } } // 手前 if ( GetAsyncKeyState( VK_DOWN ) ) { Player_1.fTheta += ROT_SPEED; if ( Player_1.fTheta > PI / 2.0f ) { Player_1.fTheta = PI / 2.0f; } } return 0; } int MakeHemisphereIndexed( float x, float y, float z, float r, CUSTOMVERTEX *pVertices, int *pVertexNum, WORD *pIndices, int *pIndexNum, int nIndexOffset ) // 球の作成(中心位置とインデックス付き) { int i, j; float fTheta; float fPhi; float fAngleDelta; int nIndex; // データのインデックス int nIndexY; // x方向インデックス // 頂点データ作成 fAngleDelta = 2.0f * PI / CORNER_NUM; nIndex = 0; fTheta = 0.0f; for ( i = 0; i < CORNER_NUM / 4 + 1; i++ ) { fPhi = 0.0f; for ( j = 0; j < CORNER_NUM + 1; j++ ) { pVertices[nIndex].v4Pos = XMFLOAT4( x + r * sinf( fTheta ) * cosf( fPhi ), y + r * cosf( fTheta ), z + r * sinf( fTheta ) * sinf( fPhi ), 1.0f ); pVertices[nIndex].v2UV = XMFLOAT2( fPhi / ( 2.0f * PI ), fTheta / PI ); nIndex++; fPhi += fAngleDelta; } fTheta += fAngleDelta; } *pVertexNum = nIndex; // インデックスデータ作成 nIndex = 0; for ( i = 0; i < CORNER_NUM; i++ ) { for ( j = 0; j < CORNER_NUM / 4; j++ ) { nIndexY = j * ( CORNER_NUM + 1 ); pIndices[nIndex ] = nIndexOffset + nIndexY + i; pIndices[nIndex + 1] = nIndexOffset + nIndexY + ( CORNER_NUM + 1 ) + i; pIndices[nIndex + 2] = nIndexOffset + nIndexY + i + 1; nIndex += 3; pIndices[nIndex ] = nIndexOffset + nIndexY + i + 1; pIndices[nIndex + 1] = nIndexOffset + nIndexY + ( CORNER_NUM + 1 ) + i; pIndices[nIndex + 2] = nIndexOffset + nIndexY + ( CORNER_NUM + 1 ) + i + 1; nIndex += 3; } } *pIndexNum = nIndex; return 0; } int MakeCylinderIndexed( float fHeight, float r, CUSTOMVERTEX *pVertices, int *pVertexNum, WORD *pIndices, int *pIndexNum, int nIndexOffset ) // 円筒の作成(インデックス付き) { int i, j; float fTheta; float fAngleDelta; int nIndex; // データのインデックス // 頂点データ作成 fAngleDelta = 2.0f * PI / CORNER_NUM; nIndex = 0; fTheta = 0.0f; for ( j = 0; j < CORNER_NUM + 1; j++ ) { pVertices[nIndex].v4Pos = XMFLOAT4( r * cosf( fTheta ), 0.0f, r * sinf( fTheta ), 1.0f ); pVertices[nIndex].v2UV = XMFLOAT2( fTheta / ( 2.0f * PI ), 0.0f ); nIndex++; pVertices[nIndex].v4Pos = XMFLOAT4( r * cosf( fTheta ), fHeight, r * sinf( fTheta ), 1.0f ); pVertices[nIndex].v2UV = XMFLOAT2( fTheta / ( 2.0f * PI ), 1.0f ); nIndex++; fTheta += fAngleDelta; } *pVertexNum = nIndex; // インデックスデータ作成 nIndex = 0; for ( i = 0; i < CORNER_NUM; i++ ) { pIndices[nIndex ] = nIndexOffset + ( i * 2 ); pIndices[nIndex + 1] = nIndexOffset + ( i + 1 ) * 2; pIndices[nIndex + 2] = nIndexOffset + ( i * 2 ) + 1; nIndex += 3; pIndices[nIndex ] = nIndexOffset + ( i * 2 ) + 1; pIndices[nIndex + 1] = nIndexOffset + ( i + 1 ) * 2; pIndices[nIndex + 2] = nIndexOffset + ( i + 1 ) * 2 + 1; nIndex += 3; } *pIndexNum = nIndex; return 0; } //------------------------------------------------------------ // 以下、DirectXによる表示プログラム #include <stdio.h> #include <windows.h> #include <tchar.h> // Unicode・マルチバイト文字関係 #define MAX_BUFFER_VERTEX 10000 // 最大バッファ頂点数 #define MAX_BUFFER_INDEX 20000 // 最大バッファインデックス数 #define MAX_MODEL_NUM 100 // 最大モデル数 // リンクライブラリ // リンクライブラリ #pragma comment( lib, "d3d11.lib" ) // D3D11ライブラリ #pragma comment( lib, "d3dcompiler.lib" ) #pragma comment( lib, "DirectXTex.lib" ) #pragma comment( lib, "winmm.lib" ) // セーフリリースマクロ #ifndef SAFE_RELEASE #define SAFE_RELEASE( p ) { if ( p ) { ( p )->Release(); ( p )=NULL; } } #endif // シェーダ定数構造体 struct CBNeverChanges { XMMATRIX mView; XMFLOAT4 v4AddColor; }; // テクスチャ絵構造体 struct TEX_PICTURE { ID3D11ShaderResourceView *pSRViewTexture; D3D11_TEXTURE2D_DESC tdDesc; int nWidth, nHeight; }; // モデル構造体 struct MY_MODEL { int nVertexPos; // 頂点位置 int nVertexNum; // 頂点数 int nIndexPos; // インデックス位置 int nIndexNum; // インデックス数 TEX_PICTURE *ptpTexture; // テクスチャ XMMATRIX mMatrix; // 変換行列 XMFLOAT4 v4AddColor; // 加算色 }; // グローバル変数 UINT g_nClientWidth; // 描画領域の横幅 UINT g_nClientHeight; // 描画領域の高さ HWND g_hWnd; // ウィンドウハンドル ID3D11Device *g_pd3dDevice; // デバイス IDXGISwapChain *g_pSwapChain; // DXGIスワップチェイン ID3D11DeviceContext *g_pImmediateContext; // デバイスコンテキスト ID3D11RasterizerState *g_pRS; // ラスタライザ ID3D11RasterizerState *g_pRS_Cull_CW; // ラスタライザ(時計回りカリング) ID3D11RasterizerState *g_pRS_Cull_CCW; // ラスタライザ(反時計回りカリング) ID3D11RenderTargetView *g_pRTV; // レンダリングターゲット ID3D11Texture2D* g_pDepthStencil = NULL; // Zバッファ ID3D11DepthStencilView* g_pDepthStencilView = NULL; // Zバッファのビュー ID3D11DepthStencilState *g_pDSDepthState = NULL; // Zバッファのステート ID3D11DepthStencilState *g_pDSDepthState_NoWrite = NULL; // Zバッファのステート(Zバッファへ書き込みなし) D3D_FEATURE_LEVEL g_FeatureLevel; // フィーチャーレベル ID3D11Buffer *g_pVertexBuffer; // 頂点バッファ ID3D11Buffer *g_pIndexBuffer; // インデックスバッファ ID3D11BlendState *g_pbsAlphaBlend; // アルファブレンド ID3D11VertexShader *g_pVertexShader; // 頂点シェーダ ID3D11PixelShader *g_pPixelShader; // ピクセルシェーダ ID3D11InputLayout *g_pInputLayout; // シェーダ入力レイアウト ID3D11SamplerState *g_pSamplerState; // サンプラステート ID3D11Buffer *g_pCBNeverChanges = NULL; // 描画頂点バッファ CUSTOMVERTEX g_cvVertices[MAX_BUFFER_VERTEX]; int g_nVertexNum = 0; WORD g_wIndices[MAX_BUFFER_INDEX]; int g_nIndexNum = 0; TEX_PICTURE g_tGroundTexture, g_tTurretTexture; MY_MODEL g_mmGround; //MY_MODEL g_mmTriangles[CHECK_TRIANGLE_NUM]; MY_MODEL g_mmTurret; // 砲塔 MY_MODEL g_mmGunbarrel; // 砲身 // Direct3Dの初期化 HRESULT InitD3D( void ) { HRESULT hr = S_OK; D3D_FEATURE_LEVEL FeatureLevelsRequested[6] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; UINT numLevelsRequested = 6; D3D_FEATURE_LEVEL FeatureLevelsSupported; // デバイス作成 hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, FeatureLevelsRequested, numLevelsRequested, D3D11_SDK_VERSION, &g_pd3dDevice, &FeatureLevelsSupported, &g_pImmediateContext ); if( FAILED ( hr ) ) { return hr; } // ファクトリの取得 IDXGIDevice * pDXGIDevice; hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), ( void ** )&pDXGIDevice ); IDXGIAdapter * pDXGIAdapter; hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), ( void ** )&pDXGIAdapter ); IDXGIFactory * pIDXGIFactory; pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), ( void ** )&pIDXGIFactory); // スワップチェインの作成 DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = g_nClientWidth; sd.BufferDesc.Height = g_nClientHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain ); pDXGIDevice->Release(); pDXGIAdapter->Release(); pIDXGIFactory->Release(); if( FAILED ( hr ) ) { return hr; } // レンダリングターゲットの生成 ID3D11Texture2D *pBackBuffer = NULL; D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK ); return hr; } pBackBuffer->GetDesc( &BackBufferSurfaceDesc ); hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV ); SAFE_RELEASE( pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK ); return hr; } // *** Create depth stencil texture *** D3D11_TEXTURE2D_DESC descDepth; RECT rc; GetClientRect( g_hWnd, &rc ); ZeroMemory( &descDepth, sizeof(descDepth) ); descDepth.Width = rc.right - rc.left; descDepth.Height = rc.bottom - rc.top; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil ); if( FAILED( hr ) ) return hr; // *** Create the depth stencil view *** D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV, sizeof(descDSV) ); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView ); if( FAILED( hr ) ) return hr; // *** レンダリングターゲット設定 *** g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, g_pDepthStencilView ); // ステンシルステートの作成 D3D11_DEPTH_STENCIL_DESC dsDesc; // Depth test parameters dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_LESS; // Stencil test parameters dsDesc.StencilEnable = true; dsDesc.StencilReadMask = 0xFF; dsDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create depth stencil state hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState ); dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState_NoWrite ); // g_pImmediateContext->OMSetDepthStencilState( g_pDSDepthState, 1 ); // ラスタライザの設定 D3D11_RASTERIZER_DESC drd; ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_NONE; drd.FrontCounterClockwise = FALSE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } g_pImmediateContext->RSSetState( g_pRS ); // ラスタライザの設定(時計回りカリング) ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_BACK; drd.FrontCounterClockwise = TRUE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CW ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } // g_pImmediateContext->RSSetState( g_pRS_Cull_CW ); // ラスタライザの設定(反時計回りカリング) ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_BACK; drd.FrontCounterClockwise = FALSE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CCW ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } // g_pImmediateContext->RSSetState( g_pRS_Cull_CCW ); // ビューポートの設定 D3D11_VIEWPORT vp; vp.Width = ( FLOAT )g_nClientWidth; vp.Height = ( FLOAT )g_nClientHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0.0f; vp.TopLeftY = 0.0f; g_pImmediateContext->RSSetViewports( 1, &vp ); return S_OK; } // プログラマブルシェーダ作成 HRESULT MakeShaders( void ) { HRESULT hr; ID3DBlob* pVertexShaderBuffer = NULL; ID3DBlob* pPixelShaderBuffer = NULL; ID3DBlob* pError = NULL; DWORD dwShaderFlags = 0; #ifdef _DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; #endif // コンパイル hr = D3DCompileFromFile( _T( "Basic_3D_TexMark.fx" ), nullptr, nullptr, "VS", "vs_4_0_level_9_1", dwShaderFlags, 0, &pVertexShaderBuffer, &pError); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open Basic_3D_TexMark.fx" ), _T( "Error" ), MB_OK ); SAFE_RELEASE( pError ); return hr; } hr = D3DCompileFromFile( _T( "Basic_3D_TexMark.fx" ), nullptr, nullptr, "PS", "ps_4_0_level_9_1", dwShaderFlags, 0, &pPixelShaderBuffer, &pError); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pError ); return hr; } SAFE_RELEASE( pError ); // VertexShader作成 hr = g_pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // PixelShader作成 hr = g_pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // 入力バッファの入力形式 D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // 入力バッファの入力形式作成 hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &g_pInputLayout ); SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); if ( FAILED( hr ) ) { return hr; } // シェーダ定数バッファ作成 D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof( bd ) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( CBNeverChanges ); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBNeverChanges ); if( FAILED( hr ) ) return hr; return S_OK; } // テクスチャロード int LoadTexture( TCHAR *szFileName, TEX_PICTURE *pTexPic, int nWidth, int nHeight, int nTexWidth, int nTexHeight ) { ID3D11Resource *resource = nullptr; HRESULT hr; ID3D11Texture2D *pTexture; hr = DirectX::CreateWICTextureFromFile(g_pd3dDevice, g_pImmediateContext, szFileName, &resource, &(pTexPic->pSRViewTexture)); if (FAILED(hr)) { return hr; } pTexPic->pSRViewTexture->GetResource((ID3D11Resource **)&(pTexture)); pTexture->GetDesc(&(pTexPic->tdDesc)); pTexture->Release(); pTexPic->nWidth = nWidth; pTexPic->nHeight = nHeight; return S_OK; } // 描画モードオブジェクト初期化 int InitDrawModes( void ) { HRESULT hr; // ブレンドステート D3D11_BLEND_DESC BlendDesc; BlendDesc.AlphaToCoverageEnable = FALSE; BlendDesc.IndependentBlendEnable = FALSE; BlendDesc.RenderTarget[0].BlendEnable = TRUE; BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_BLEND_FACTOR; BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_BLEND_FACTOR; BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; hr = g_pd3dDevice->CreateBlendState( &BlendDesc, &g_pbsAlphaBlend ); if ( FAILED( hr ) ) { return hr; } // サンプラ D3D11_SAMPLER_DESC samDesc; ZeroMemory( &samDesc, sizeof( samDesc ) ); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = g_pd3dDevice->CreateSamplerState( &samDesc, &g_pSamplerState ); if ( FAILED( hr ) ) { return hr; } return S_OK; } // ジオメトリの初期化 HRESULT InitGeometry( void ) { HRESULT hr = S_OK; // 頂点バッファ作成 D3D11_BUFFER_DESC BufferDesc; BufferDesc.Usage = D3D11_USAGE_DYNAMIC; BufferDesc.ByteWidth = sizeof( CUSTOMVERTEX ) * MAX_BUFFER_VERTEX; BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; BufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA SubResourceData; SubResourceData.pSysMem = g_cvVertices; SubResourceData.SysMemPitch = 0; SubResourceData.SysMemSlicePitch = 0; hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pVertexBuffer ); if ( FAILED( hr ) ) { return hr; } // インデックスバッファ作成 BufferDesc.Usage = D3D11_USAGE_DYNAMIC; BufferDesc.ByteWidth = sizeof( WORD ) * MAX_BUFFER_INDEX; BufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; BufferDesc.MiscFlags = 0; SubResourceData.pSysMem = g_wIndices; hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pIndexBuffer ); if( FAILED( hr ) ) return hr; // テクスチャ作成 g_tGroundTexture.pSRViewTexture = NULL; hr = LoadTexture( _T( "17.bmp" ), &g_tGroundTexture, 691, 691, 1024, 1024 ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open 17.bmp" ), _T( "Error" ), MB_OK ); return hr; } g_tTurretTexture.pSRViewTexture = NULL; hr = LoadTexture( _T( "14.bmp" ), &g_tTurretTexture, 691, 346, 1024, 512 ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open 14.bmp" ), _T( "Error" ), MB_OK ); return hr; } // モデル作成 // 砲塔 int nVertexNum1, nIndexNum1; MakeHemisphereIndexed( 0.0f, 0.0f, 0.0f, 1.0f, &( g_cvVertices[g_nVertexNum] ), &nVertexNum1, &( g_wIndices[g_nIndexNum] ), &nIndexNum1, 0 ); g_mmTurret.nVertexPos = g_nVertexNum; g_mmTurret.nVertexNum = nVertexNum1; g_mmTurret.nIndexPos = g_nIndexNum; g_mmTurret.nIndexNum = nIndexNum1; g_nVertexNum += nVertexNum1; g_nIndexNum += nIndexNum1; g_mmTurret.ptpTexture = &g_tTurretTexture; g_mmTurret.mMatrix = XMMatrixIdentity(); g_mmTurret.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 砲身 MakeCylinderIndexed( GUNBARREL_LEN, 0.2f, &( g_cvVertices[g_nVertexNum] ), &nVertexNum1, &( g_wIndices[g_nIndexNum] ), &nIndexNum1, 0 ); g_mmGunbarrel.nVertexPos = g_nVertexNum; g_mmGunbarrel.nVertexNum = nVertexNum1; g_mmGunbarrel.nIndexPos = g_nIndexNum; g_mmGunbarrel.nIndexNum = nIndexNum1; g_nVertexNum += nVertexNum1; g_nIndexNum += nIndexNum1; g_mmGunbarrel.ptpTexture = &g_tTurretTexture; g_mmGunbarrel.mMatrix = XMMatrixIdentity(); g_mmGunbarrel.mMatrix.r[3].m128_f32[1] = TURRET_R / 2.0f; g_mmGunbarrel.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 地面 g_cvVertices[g_nVertexNum ].v4Pos = XMFLOAT4( -GROUND_SIZE / 2, GROUND_Y, GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum ].v2UV = XMFLOAT2( 0.0f, 0.0f ); g_cvVertices[g_nVertexNum + 1].v4Pos = XMFLOAT4( GROUND_SIZE / 2, GROUND_Y, GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 1].v2UV = XMFLOAT2( 1.0f, 0.0f ); g_cvVertices[g_nVertexNum + 2].v4Pos = XMFLOAT4( -GROUND_SIZE / 2, GROUND_Y, -GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 2].v2UV = XMFLOAT2( 0.0f, 1.0f ); g_cvVertices[g_nVertexNum + 3].v4Pos = XMFLOAT4( GROUND_SIZE / 2, GROUND_Y, -GROUND_SIZE / 2, 1.0f ); g_cvVertices[g_nVertexNum + 3].v2UV = XMFLOAT2( 1.0f, 1.0f ); g_wIndices[g_nIndexNum ] = 0; g_wIndices[g_nIndexNum + 1] = 2; g_wIndices[g_nIndexNum + 2] = 1; g_wIndices[g_nIndexNum + 3] = 1; g_wIndices[g_nIndexNum + 4] = 2; g_wIndices[g_nIndexNum + 5] = 3; g_mmGround.nVertexPos = g_nVertexNum; g_mmGround.nVertexNum = 4; g_mmGround.nIndexPos = g_nIndexNum; g_mmGround.nIndexNum = 6; g_nVertexNum += 4; g_nIndexNum += 6; g_mmGround.ptpTexture = &g_tGroundTexture; g_mmGround.mMatrix = XMMatrixIdentity(); g_mmGround.v4AddColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); // 頂点バッファ・インデックスバッファ作成 D3D11_MAPPED_SUBRESOURCE mappedVertices, mappedIndices; hr = g_pImmediateContext->Map( g_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertices ); if( FAILED( hr ) ) return hr; hr = g_pImmediateContext->Map( g_pIndexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedIndices ); if( FAILED( hr ) ) { g_pImmediateContext->Unmap( g_pVertexBuffer, 0 ); return hr; } CopyMemory( mappedVertices.pData, g_cvVertices, sizeof( CUSTOMVERTEX ) * g_nVertexNum ); CopyMemory( mappedIndices.pData, g_wIndices, sizeof( WORD ) * g_nIndexNum ); g_pImmediateContext->Unmap( g_pVertexBuffer, 0 ); g_pImmediateContext->Unmap( g_pIndexBuffer, 0 ); return S_OK; } // 終了処理 int Cleanup( void ) { SAFE_RELEASE( g_tGroundTexture.pSRViewTexture ); SAFE_RELEASE( g_tTurretTexture.pSRViewTexture ); SAFE_RELEASE( g_pVertexBuffer ); SAFE_RELEASE( g_pIndexBuffer ); SAFE_RELEASE( g_pSamplerState ); SAFE_RELEASE( g_pbsAlphaBlend ); SAFE_RELEASE( g_pInputLayout ); SAFE_RELEASE( g_pPixelShader ); SAFE_RELEASE( g_pVertexShader ); SAFE_RELEASE( g_pCBNeverChanges ); SAFE_RELEASE( g_pRS ); // ラスタライザ SAFE_RELEASE( g_pRS_Cull_CW ); SAFE_RELEASE( g_pRS_Cull_CCW ); // ステータスをクリア if ( g_pImmediateContext ) { g_pImmediateContext->ClearState(); g_pImmediateContext->Flush(); } SAFE_RELEASE( g_pRTV ); // レンダリングターゲット SAFE_RELEASE( g_pDepthStencil ); // Zバッファ SAFE_RELEASE( g_pDepthStencilView ); // Zバッファのビュー SAFE_RELEASE( g_pDSDepthState ); // Zバッファのステート SAFE_RELEASE( g_pDSDepthState_NoWrite ); // スワップチェーン if ( g_pSwapChain != NULL ) { g_pSwapChain->SetFullscreenState( FALSE, 0 ); } SAFE_RELEASE( g_pSwapChain ); SAFE_RELEASE( g_pImmediateContext ); // デバイスコンテキスト SAFE_RELEASE( g_pd3dDevice ); // デバイス return 0; } // モデルの描画 int DrawMyModel( MY_MODEL *pmmDrawModel, XMMATRIX *pmViewProjection ) { CBNeverChanges cbNeverChanges; cbNeverChanges.mView = XMMatrixTranspose( pmmDrawModel->mMatrix * *pmViewProjection ); cbNeverChanges.v4AddColor = pmmDrawModel->v4AddColor; g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 ); g_pImmediateContext->PSSetShaderResources( 0, 1, &( pmmDrawModel->ptpTexture->pSRViewTexture ) ); g_pImmediateContext->DrawIndexed( pmmDrawModel->nIndexNum, pmmDrawModel->nIndexPos, pmmDrawModel->nVertexPos ); return 0; } // 影モデルの描画 int DrawShadowModel( MY_MODEL *pmmDrawModel, XMMATRIX *pmViewProjection, XMFLOAT3 v3Light, float fGround_y ) { XMMATRIX matShadowed; XMMATRIX matTemp; XMFLOAT4 v4ColorTemp; matShadowed = CreateShadowMatrix( v3Light, fGround_y ); matTemp = matShadowed * *pmViewProjection; v4ColorTemp = pmmDrawModel->v4AddColor; pmmDrawModel->v4AddColor = XMFLOAT4( -1.0f, -1.0f, -1.0f, 1.0f ); DrawMyModel( pmmDrawModel, &matTemp ); pmmDrawModel->v4AddColor = v4ColorTemp; return 0; } // ウィンドウプロシージャ LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); return 0; } return DefWindowProc( hWnd, msg, wParam, lParam ); } // レンダリング HRESULT Render( void ) { // int i; // 画面クリア XMFLOAT4 v4Color = XMFLOAT4( 0.0f, 0.5f, 1.0f, 1.0f ); g_pImmediateContext->ClearRenderTargetView( g_pRTV, ( float * )&v4Color ); // *** Zバッファクリア *** g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 ); // サンプラセット g_pImmediateContext->PSSetSamplers( 0, 1, &g_pSamplerState ); // 描画設定 UINT nStrides = sizeof( CUSTOMVERTEX ); UINT nOffsets = 0; g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &nStrides, &nOffsets ); g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 ); g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); g_pImmediateContext->IASetInputLayout( g_pInputLayout ); // シェーダ設定 g_pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 ); g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCBNeverChanges ); g_pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 ); g_pImmediateContext->PSSetConstantBuffers( 0, 1, &g_pCBNeverChanges ); // 変換行列 CBNeverChanges cbNeverChanges; XMMATRIX mWorld; XMMATRIX mView; XMMATRIX mProjection; XMMATRIX mViewProjection; // Initialize the view matrix XMVECTOR Eye = XMVectorSet( 0.0f, 5.0f, -7.0f, 0.0f ); XMVECTOR At = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f ); XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); mView = XMMatrixLookAtLH( Eye, At, Up ); // Initialize the projection matrix mProjection = XMMatrixPerspectiveFovLH( XM_PIDIV4, VIEW_WIDTH / ( FLOAT )VIEW_HEIGHT, 0.01f, 100.0f ); mViewProjection = mView * mProjection; // 描画 g_pImmediateContext->OMSetDepthStencilState( g_pDSDepthState, 1 ); g_pImmediateContext->RSSetState( g_pRS_Cull_CW ); // カリングあり // 地面 g_pImmediateContext->OMSetBlendState( NULL, NULL, 0xFFFFFFFF ); DrawMyModel( &g_mmGround, &mViewProjection ); // 砲 g_mmTurret.mMatrix = XMMatrixRotationY( Player_1.fPhi ); DrawMyModel( &g_mmTurret, &mViewProjection ); DrawShadowModel( &g_mmTurret, &mViewProjection, XMFLOAT3( -1.0f, -1.0f, -2.0f ), GROUND_Y ); g_pImmediateContext->RSSetState( g_pRS ); // カリングなし g_mmGunbarrel.mMatrix = XMMatrixRotationZ( -Player_1.fTheta ) * XMMatrixRotationY( Player_1.fPhi ); g_mmGunbarrel.mMatrix.r[3].m128_f32[1] = TURRET_R / 2.0f; DrawMyModel( &g_mmGunbarrel, &mViewProjection ); DrawShadowModel( &g_mmGunbarrel, &mViewProjection, XMFLOAT3( -1.0f, -1.0f, -2.0f ), GROUND_Y ); g_pImmediateContext->RSSetState( g_pRS_Cull_CW ); // カリングあり // 半透明地面 XMMATRIX matTemp; float v4Factors[4] = { 0.4f, 0.4f, 0.4f, 1.0f }; g_pImmediateContext->OMSetBlendState( g_pbsAlphaBlend, v4Factors, 0xFFFFFFFF ); matTemp = g_mmGround.mMatrix; g_mmGround.mMatrix.r[3].m128_f32[1] += 0.02f; DrawMyModel( &g_mmGround, &mViewProjection ); g_mmGround.mMatrix = matTemp; return S_OK; } // エントリポイント int WINAPI _tWinMain( HINSTANCE hInst, HINSTANCE, LPTSTR, int ) { LARGE_INTEGER nNowTime, nLastTime; // 現在とひとつ前の時刻 LARGE_INTEGER nTimeFreq; // 時間単位 // 画面サイズ g_nClientWidth = VIEW_WIDTH; // 幅 g_nClientHeight = VIEW_HEIGHT; // 高さ HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); // Register the window class WNDCLASSEX wc = { sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle( NULL ), NULL, NULL, NULL, NULL, _T( "D3D Sample" ), NULL }; RegisterClassEx( &wc ); RECT rcRect; SetRect( &rcRect, 0, 0, g_nClientWidth, g_nClientHeight ); AdjustWindowRect( &rcRect, WS_OVERLAPPEDWINDOW, FALSE ); g_hWnd = CreateWindow( _T( "D3D Sample" ), _T( "3DPhysics_1_1" ), WS_OVERLAPPEDWINDOW, 100, 20, rcRect.right - rcRect.left, rcRect.bottom - rcRect.top, GetDesktopWindow(), NULL, wc.hInstance, NULL ); // Initialize Direct3D if( SUCCEEDED( InitD3D() ) && SUCCEEDED( MakeShaders() ) ) { // Create the shaders if( SUCCEEDED( InitDrawModes() ) ) { if ( SUCCEEDED( InitGeometry() ) ) { // ジオメトリ作成 InitPlayer(); // プレイヤーの初期化 // Show the window ShowWindow( g_hWnd, SW_SHOWDEFAULT ); UpdateWindow( g_hWnd ); QueryPerformanceFrequency( &nTimeFreq ); // 時間単位 QueryPerformanceCounter( &nLastTime ); // 1フレーム前時刻初期化 // Enter the message loop MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { MovePlayer(); Render(); do { if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } QueryPerformanceCounter( &nNowTime ); } while( ( ( nNowTime.QuadPart - nLastTime.QuadPart ) < ( nTimeFreq.QuadPart / 90 ) ) && ( msg.message != WM_QUIT ) ); while( ( ( nNowTime.QuadPart - nLastTime.QuadPart ) < ( nTimeFreq.QuadPart / 60 ) ) && ( msg.message != WM_QUIT ) ) { QueryPerformanceCounter( &nNowTime ); } nLastTime = nNowTime; g_pSwapChain->Present( 0, 0 ); // 表示 } } } } // Clean up everything and exit the app Cleanup(); UnregisterClass( _T( "D3D Sample" ), wc.hInstance ); return 0; }
[ "39890474+starcatneko@users.noreply.github.com" ]
39890474+starcatneko@users.noreply.github.com
de1dda8c2a893e70a9cceb2bdbb07e16297ea62b
1d28a48f1e02f81a8abf5a33c233d9c38e339213
/SVEngine/src/node/SVDummyNode.cpp
e2c7695486e8c37affffb06a48b7bca1603951eb
[ "MIT" ]
permissive
SVEChina/SVEngine
4972bed081b858c39e5871c43fd39e80c527c2b1
56174f479a3096e57165448142c1822e7db8c02f
refs/heads/master
2021-07-09T10:07:46.350906
2020-05-24T04:10:57
2020-05-24T04:10:57
150,706,405
34
9
null
null
null
null
UTF-8
C++
false
false
235
cpp
// // SVDummyNode.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVDummyNode.h" #include "../app/SVInst.h" SVDummyNode::SVDummyNode(SVInst *_app) :SVNode(_app) { }
[ "fuyizhou@svengine.com" ]
fuyizhou@svengine.com
a753fc6d0234f96fb1188f7213e411a3534f99f3
c2b67a59eb14fab0f201801fcb840907012c26f0
/src/Render/DX12/PipelineBase.cpp
7573b8479870e8a8c7e477b3bb5ac1cfa46236be
[ "MIT" ]
permissive
max447385307/Utopia
ca08be5ba842c7f9c850c206e5f6b4b2916d72f7
f800f9da77afd66dfde51d104979a7d107c0ff31
refs/heads/master
2022-12-28T10:11:59.625695
2020-10-15T08:43:36
2020-10-15T08:43:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,419
cpp
#include <Utopia/Render/DX12/PipelineBase.h> #include <Utopia/Render/Material.h> #include <Utopia/Render/Shader.h> #include <Utopia/Render/DX12/RsrcMngrDX12.h> #include <Utopia/Render/DX12/ShaderCBMngrDX12.h> using namespace Ubpa::Utopia; PipelineBase::ShaderCBDesc PipelineBase::UpdateShaderCBs( ShaderCBMngrDX12& shaderCBMngr, const Shader& shader, const std::unordered_set<const Material*>& materials, const std::set<std::string_view>& commonCBs ) { PipelineBase::ShaderCBDesc rst; auto CalculateSize = [&](ID3D12ShaderReflection* refl) { D3D12_SHADER_DESC shaderDesc; ThrowIfFailed(refl->GetDesc(&shaderDesc)); for (UINT i = 0; i < shaderDesc.ConstantBuffers; i++) { auto cb = refl->GetConstantBufferByIndex(i); D3D12_SHADER_BUFFER_DESC cbDesc; ThrowIfFailed(cb->GetDesc(&cbDesc)); if(commonCBs.find(cbDesc.Name) != commonCBs.end()) continue; D3D12_SHADER_INPUT_BIND_DESC rsrcDesc; refl->GetResourceBindingDescByName(cbDesc.Name, &rsrcDesc); auto target = rst.offsetMap.find(rsrcDesc.BindPoint); if(target != rst.offsetMap.end()) continue; rst.offsetMap.emplace_hint(target, std::pair{ rsrcDesc.BindPoint, rst.materialCBSize }); rst.materialCBSize += UDX12::Util::CalcConstantBufferByteSize(cbDesc.Size); } }; for (size_t i = 0; i < shader.passes.size(); i++) { CalculateSize(RsrcMngrDX12::Instance().GetShaderRefl_vs(shader, i)); CalculateSize(RsrcMngrDX12::Instance().GetShaderRefl_ps(shader, i)); } auto buffer = shaderCBMngr.GetBuffer(shader); buffer->FastReserve(rst.materialCBSize * materials.size()); for (auto material : materials) { size_t idx = rst.indexMap.size(); rst.indexMap[material->GetInstanceID()] = idx; } auto UpdateShaderCBsForRefl = [&](std::set<size_t>& flags, const Material* material, ID3D12ShaderReflection* refl) { size_t index = rst.indexMap.at(material->GetInstanceID()); D3D12_SHADER_DESC shaderDesc; ThrowIfFailed(refl->GetDesc(&shaderDesc)); for (UINT i = 0; i < shaderDesc.ConstantBuffers; i++) { auto cb = refl->GetConstantBufferByIndex(i); D3D12_SHADER_BUFFER_DESC cbDesc; ThrowIfFailed(cb->GetDesc(&cbDesc)); D3D12_SHADER_INPUT_BIND_DESC rsrcDesc; refl->GetResourceBindingDescByName(cbDesc.Name, &rsrcDesc); if (rst.offsetMap.find(rsrcDesc.BindPoint) == rst.offsetMap.end()) continue; if(flags.find(rsrcDesc.BindPoint) != flags.end()) continue; flags.insert(rsrcDesc.BindPoint); size_t offset = rst.materialCBSize * index + rst.offsetMap.at(rsrcDesc.BindPoint); for (UINT j = 0; j < cbDesc.Variables; j++) { auto var = cb->GetVariableByIndex(j); D3D12_SHADER_VARIABLE_DESC varDesc; ThrowIfFailed(var->GetDesc(&varDesc)); auto target = material->properties.find(varDesc.Name); if(target == material->properties.end()) continue; std::visit([&](const auto& value) { using Value = std::decay_t<decltype(value)>; if constexpr (std::is_same_v<Value, bool>) { auto v = static_cast<unsigned int>(value); assert(varDesc.Size == sizeof(unsigned int)); buffer->Set(offset + varDesc.StartOffset, &v, sizeof(unsigned int)); } else if constexpr (std::is_same_v<Value, const Texture2D*> || std::is_same_v<Value, const TextureCube*>) assert(false); else { assert(varDesc.Size == sizeof(Value)); buffer->Set(offset + varDesc.StartOffset, &value, varDesc.Size); } }, target->second); } } }; for (auto material : materials) { std::set<size_t> flags; for (size_t i = 0; i < shader.passes.size(); i++) { UpdateShaderCBsForRefl(flags, material, RsrcMngrDX12::Instance().GetShaderRefl_vs(shader, i)); UpdateShaderCBsForRefl(flags, material, RsrcMngrDX12::Instance().GetShaderRefl_ps(shader, i)); } } return rst; } void PipelineBase::SetGraphicsRoot_CBV_SRV( ID3D12GraphicsCommandList* cmdList, ShaderCBMngrDX12& shaderCBMngr, const ShaderCBDesc& shaderCBDescconst, const Material& material, const std::map<std::string_view, D3D12_GPU_VIRTUAL_ADDRESS>& commonCBs, const std::map<std::string_view, D3D12_GPU_DESCRIPTOR_HANDLE>& commonSRVs ) { auto buffer = shaderCBMngr.GetBuffer(*material.shader); size_t cbPos = buffer->GetResource()->GetGPUVirtualAddress() + shaderCBDescconst.indexMap.at(material.GetInstanceID()) * shaderCBDescconst.materialCBSize; auto SetGraphicsRoot_Refl = [&](ID3D12ShaderReflection* refl) { D3D12_SHADER_DESC shaderDesc; ThrowIfFailed(refl->GetDesc(&shaderDesc)); auto GetSRVRootParamIndex = [&](UINT registerIndex) { for (size_t i = 0; i < material.shader->rootParameters.size(); i++) { const auto& param = material.shader->rootParameters[i]; bool flag = std::visit( [=](const auto& param) { using Type = std::decay_t<decltype(param)>; if constexpr (std::is_same_v<Type, RootDescriptorTable>) { const RootDescriptorTable& table = param; if (table.size() != 1) return false; const auto& range = table.front(); assert(range.NumDescriptors > 0); return range.BaseShaderRegister == registerIndex; } else return false; }, param ); if (flag) return (UINT)i; } // assert(false); return static_cast<UINT>(-1); // inner SRV }; auto GetCBVRootParamIndex = [&](UINT registerIndex) { for (size_t i = 0; i < material.shader->rootParameters.size(); i++) { const auto& param = material.shader->rootParameters[i]; bool flag = std::visit( [=](const auto& param) { using Type = std::decay_t<decltype(param)>; if constexpr (std::is_same_v<Type, RootDescriptor>) { const RootDescriptor& descriptor = param; if (descriptor.DescriptorType != RootDescriptorType::CBV) return false; return descriptor.ShaderRegister == registerIndex; } else return false; }, param ); if (flag) return (UINT)i; } assert(false); return static_cast<UINT>(-1); }; for (UINT i = 0; i < shaderDesc.BoundResources; i++) { D3D12_SHADER_INPUT_BIND_DESC rsrcDesc; ThrowIfFailed(refl->GetResourceBindingDesc(i, &rsrcDesc)); switch (rsrcDesc.Type) { case D3D_SIT_CBUFFER: { UINT idx = GetCBVRootParamIndex(rsrcDesc.BindPoint); D3D12_GPU_VIRTUAL_ADDRESS adress; if (auto target = shaderCBDescconst.offsetMap.find(rsrcDesc.BindPoint); target != shaderCBDescconst.offsetMap.end()) adress = cbPos + target->second; else if (auto target = commonCBs.find(rsrcDesc.Name); target != commonCBs.end()) adress = target->second; else { assert(false); break; } cmdList->SetGraphicsRootConstantBufferView(idx, adress); break; } case D3D_SIT_TEXTURE: { UINT rootParamIndex = GetSRVRootParamIndex(rsrcDesc.BindPoint); if (rootParamIndex == static_cast<size_t>(-1)) break; D3D12_GPU_DESCRIPTOR_HANDLE handle; handle.ptr = 0; if (auto target = material.properties.find(rsrcDesc.Name); target != material.properties.end()) { auto dim = rsrcDesc.Dimension; switch (dim) { case D3D_SRV_DIMENSION_TEXTURE2D: { assert(std::holds_alternative<std::shared_ptr<const Texture2D>>(target->second)); auto tex2d = std::get<std::shared_ptr<const Texture2D>>(target->second); handle = RsrcMngrDX12::Instance().GetTexture2DSrvGpuHandle(*tex2d); break; } case D3D_SRV_DIMENSION_TEXTURECUBE: { assert(std::holds_alternative<std::shared_ptr<const TextureCube>>(target->second)); auto texcube = std::get<std::shared_ptr<const TextureCube>>(target->second); handle = RsrcMngrDX12::Instance().GetTextureCubeSrvGpuHandle(*texcube); break; } default: assert("not support" && false); break; } } else if (auto target = commonSRVs.find(rsrcDesc.Name); target != commonSRVs.end()) handle = target->second; else break; if (handle.ptr != 0) cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, handle); break; } default: break; } } }; for (size_t i = 0; i < material.shader->passes.size(); i++) { SetGraphicsRoot_Refl(RsrcMngrDX12::Instance().GetShaderRefl_vs(*material.shader, i)); SetGraphicsRoot_Refl(RsrcMngrDX12::Instance().GetShaderRefl_ps(*material.shader, i)); } } void PipelineBase::SetPSODescForRenderState(D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const RenderState& renderState) { desc.RasterizerState.CullMode = static_cast<D3D12_CULL_MODE>(renderState.cullMode); desc.DepthStencilState.DepthFunc = static_cast<D3D12_COMPARISON_FUNC>(renderState.zTest); desc.DepthStencilState.DepthWriteMask = static_cast<D3D12_DEPTH_WRITE_MASK>(renderState.zWrite); for (size_t i = 0; i < 8; i++) { if (renderState.blendStates[i].enable) { desc.BlendState.RenderTarget[i].BlendEnable = TRUE; desc.BlendState.RenderTarget[i].SrcBlend = static_cast<D3D12_BLEND>(renderState.blendStates[i].src); desc.BlendState.RenderTarget[i].DestBlend = static_cast<D3D12_BLEND>(renderState.blendStates[i].dest); desc.BlendState.RenderTarget[i].BlendOp = static_cast<D3D12_BLEND_OP>(renderState.blendStates[i].op); desc.BlendState.RenderTarget[i].SrcBlendAlpha = static_cast<D3D12_BLEND>(renderState.blendStates[i].srcAlpha); desc.BlendState.RenderTarget[i].DestBlendAlpha = static_cast<D3D12_BLEND>(renderState.blendStates[i].destAlpha); desc.BlendState.RenderTarget[i].BlendOpAlpha = static_cast<D3D12_BLEND_OP>(renderState.blendStates[i].opAlpha); } } if (renderState.stencilState.enable) { desc.DepthStencilState.StencilEnable = TRUE; desc.DepthStencilState.StencilReadMask = renderState.stencilState.readMask; desc.DepthStencilState.StencilWriteMask = renderState.stencilState.writeMask; D3D12_DEPTH_STENCILOP_DESC stencilDesc; stencilDesc.StencilDepthFailOp = static_cast<D3D12_STENCIL_OP>(renderState.stencilState.depthFailOp); stencilDesc.StencilFailOp = static_cast<D3D12_STENCIL_OP>(renderState.stencilState.failOp); stencilDesc.StencilPassOp = static_cast<D3D12_STENCIL_OP>(renderState.stencilState.passOp); stencilDesc.StencilFunc = static_cast<D3D12_COMPARISON_FUNC>(renderState.stencilState.func); desc.DepthStencilState.FrontFace = stencilDesc; desc.DepthStencilState.BackFace = stencilDesc; } for (size_t i = 0; i < 8; i++) desc.BlendState.RenderTarget[i].RenderTargetWriteMask = renderState.colorMask[i]; }
[ "ustczt@mail.ustc.edu.cn" ]
ustczt@mail.ustc.edu.cn
428ce417a9edf4a53e925a372630d7ed25c51e96
70441dcb7a8917a5574dd74c5afdeeaed3672a7a
/AtCoder Beginner Contest 137/D - Summer Vacation/main.cpp
2fefeab7b30d74f37e571c30a5dd8b08656de6af
[]
no_license
tmyksj/atcoder
f12ecf6255b668792d83621369194195f06c10f6
419165e85d8a9a0614e5544232da371d8a2f2f85
refs/heads/master
2023-03-05T12:14:14.945257
2023-02-26T10:10:20
2023-02-26T10:10:20
195,034,198
0
0
null
null
null
null
UTF-8
C++
false
false
681
cpp
#include <algorithm> #include <iostream> #include <queue> #include <utility> #include <vector> using namespace std; int main() { int n, m; cin >> n >> m; vector<pair<int, int>> ab(n, make_pair(0, 0)); for (int i = 0; i < n; i++) { cin >> ab[i].first >> ab[i].second; } sort(ab.begin(), ab.end()); long long sum = 0; priority_queue<int> que; for (int i = m - 1, idx = 0; i >= 0; i--) { for (; idx < n && ab[idx].first <= m - i; idx++) { que.push(ab[idx].second); } if (que.empty()) { continue; } sum += que.top(); que.pop(); } cout << sum << endl; }
[ "33417830+tmyksj@users.noreply.github.com" ]
33417830+tmyksj@users.noreply.github.com
8b73aa275cc86758267c036699729f1301f50d4f
a04a94c8b29ba71809eea944478230063d2af29a
/Dx3D/stdafx.h
e22cf933216612419a3d6a2b4fb183023d4e2f40
[]
no_license
hmgWorks/tmp2
22b960203940ed6df3ac7498e84149d38723376e
ead9375ab1b23f3e15733a5dcb1f755d28750c2d
refs/heads/master
2016-09-09T22:42:14.445487
2015-01-09T04:53:51
2015-01-09T04:53:51
28,863,385
0
0
null
null
null
null
UHC
C++
false
false
1,785
h
// stdafx.h : 자주 사용하지만 자주 변경되지는 않는 // 표준 시스템 포함 파일 및 프로젝트 관련 포함 파일이 // 들어 있는 포함 파일입니다. // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // 거의 사용되지 않는 내용은 Windows 헤더에서 제외합니다. // Windows 헤더 파일: #include <windows.h> // C 런타임 헤더 파일입니다. #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> // TODO: 프로그램에 필요한 추가 헤더는 여기에서 참조합니다. #include <vector> #include <list> #include <map> #include <set> #include <string> #include <assert.h> #include <d3dx9.h> #include <tuple> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") extern HWND g_hWnd; #define SAFE_RELEASE(p) if(p){p->Release(); p = NULL;} #define SAFE_DELETE(p) if(p){delete p; p = NULL;} #define SINGLETONE(class_name) private: class_name(void); ~class_name(void); \ public: static class_name* GetInstance() { static class_name instance; return &instance; } #include "cObject.h" #include "cDeviceManager.h" #include "cTextureManager.h" #define RESOURCE_FOLDER "../../Resources/" struct ST_RHWC_VERTEX { D3DXVECTOR4 p; D3DCOLOR c; enum {FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE}; }; struct ST_RHW_VERTEX { D3DXVECTOR4 p; //D3DCOLOR c; D3DXVECTOR2 t; enum {FVF = D3DFVF_XYZRHW | /*D3DFVF_DIFFUSE*/D3DFVF_TEX1}; }; struct ST_PC_VERTEX { D3DXVECTOR3 p; D3DCOLOR c; enum {FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE}; }; struct ST_PT_VERTEX { D3DXVECTOR3 p; D3DXVECTOR2 t; enum {FVF = D3DFVF_XYZ | D3DFVF_TEX1}; }; struct ST_PNT_VERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; D3DXVECTOR2 t; enum {FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1}; };
[ "tmdnldjazz@gmail.com" ]
tmdnldjazz@gmail.com
0dbc99a740dc247e00d817eb4beecf4361701f37
a9dcca3cc82ef8571a609456156bda7e02ff989a
/source/App/EnmDensityCurvePage.cpp
28885050e94c2f2d7e13d3c9873d2b363f10e394
[ "MIT" ]
permissive
Borrk/Enzyme-labeled-instrument
ea420e174dd8a6b442be6ba19a116e3d899388c9
a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f
refs/heads/master
2020-06-28T17:39:08.672508
2019-09-09T03:14:40
2019-09-09T03:14:40
200,298,941
1
0
null
null
null
null
UTF-8
C++
false
false
5,201
cpp
#include "EnmDensityCurvePage.h" #include <math.h> CEnmDensityCurvePage::CEnmDensityCurvePage() : CEnmBasePage( "", 1 ) { Init(); } void CEnmDensityCurvePage::Init() { mX0 = 36; mY0 = 240 - 30; mLenX = 270; mLenY = 180; mStepX = 30; mStepY = 30; mDataCount = 0; memset( mDensity, 0, sizeof(mDensity) ); mConcMax = 9.0; mDensityMax = 6; } void CEnmDensityCurvePage::FocusOn() { CalculateDensity(); inherited::FocusOn(); } void CEnmDensityCurvePage::Draw() { inherited::Draw(); DrawCurve(); } void CEnmDensityCurvePage::DrawCurve() { DrawAxis(); CEnmScanContext& rScanContext = GetScanContext(); switch ( rScanContext.mProtocol.stQuality.uCurve ) { case 0: DrawCurveLinear(); break; case 1: DrawCurveSegment(); break; } } void CEnmDensityCurvePage::DrawAxis() { tagPoint aArrowX[] = { {mX0 + mLenX - 7, mY0 - 3}, {mX0 + mLenX, mY0}, {mX0 + mLenX - 7, mY0 + 3} }; tagPoint aArrowY[] = { {mX0-3, mY0 - mLenY + 7}, {mX0, mY0 - mLenY}, {mX0 + 3, mY0 - mLenY + 7} }; PutLine( mX0, mY0 + 5, mX0, mY0 - mLenY ); PutLine( mX0 - 5, mY0, mX0 + mLenX, mY0 ); /// Draw axis-x arrow PutLine( aArrowX[0].x, aArrowX[0].y, aArrowX[1].x, aArrowX[1].y ); PutLine( aArrowX[2].x, aArrowX[2].y, aArrowX[1].x, aArrowX[1].y ); /// Draw aixs-y arrow PutLine( aArrowY[0].x, aArrowY[0].y, aArrowY[1].x, aArrowY[1].y ); PutLine( aArrowY[2].x, aArrowY[2].y, aArrowY[1].x, aArrowY[1].y ); /// Draw scaler U16 i; U16 aScalerLen = 4; U16 aSteps = mLenX / mStepX; for ( i = 1; i < aSteps; i++ ) { PutLine( mX0 + i * mStepX, mY0 - aScalerLen, mX0 + i * mStepX, mY0 ); } aSteps = mLenY / mStepY; for ( i = 1; i < aSteps; i++ ) { PutLine( mX0, mY0 - i * mStepY, mX0 + aScalerLen, mY0 - i * mStepY ); } DrawAxisUnit(); } void CEnmDensityCurvePage::DrawAxisUnit() { U16 i; U16 aSteps = mLenX / mStepX; FP64 aStepConc = ( mConcMax / aSteps ); MCHAR aStr[8] = { 0 }; for ( i = 1; i < aSteps; i++ ) { FormatFP2( i * aStepConc, aStr, 4, 3 ); PutStr( mX0 + i * mStepX - 16, mY0 + 0, aStr, 0 ); } aSteps = mLenY / mStepY; FP64 aStepDensity = mDensityMax / aSteps; for ( i = 1; i < aSteps; i++ ) { FormatFP2( i * aStepDensity, aStr, 4, 3 ); PutStr( mX0 - 28, mY0 - i * mStepY - 10, aStr, 0 ); //PutLine( mX0 - aScalerLen, mY0 - i * mStepY, mX0 + aScalerLen, mY0 - i * mStepY ); } } void CEnmDensityCurvePage::DrawCurveLinear() { if ( mDataCount <= 0 ) return; if ( abs( mK ) < 0.0001 ) return; FP64 x0, y0, x1, y1, aX, aY; x0 = 0.0; x1 = mConcMax; y0 = mK * x0 + mC; y1 = mK * x1 + mC; aY = mDensityMax; aX = (aY - mC) / mK; if ( y1 > mDensityMax ) { x1 = aX; y1 = aY; } PutLine( mX0 + x0 * mStepX, mY0 - y0 * mStepY, mX0 + x1 * mStepX, mY0 - y1 * mStepY ); } void CEnmDensityCurvePage::DrawCurveSegment() { } U16 CEnmDensityCurvePage::CalculateDensity() { CEnmScanContext &aScanProt = GetScanContext(); if ( aScanProt.IsConcCalculated() ) { FP64 *apConc = (FP64*)aScanProt.mCalcData.GetConc( TRUE ); mDataCount = aScanProt.GetSampleCount( );; tagDateFormulate aFormulate; if ( Convert2Formulate( aFormulate ) ) { EnmCompareCal( &aFormulate, apConc, mDensity, ENM_DATA_GROUP, ENM_DATA_COUNT ); PickMax(); mK = aFormulate.stCoefficent.a; mC = aFormulate.stCoefficent.b; } else { mDataCount = 0; memset( mDensity, 0, sizeof(mDensity) ); } } else { mDataCount = 0; memset( mDensity, 0, sizeof(mDensity) ); } return mDataCount; } BOOLEAN CEnmDensityCurvePage::Convert2Formulate( tagDateFormulate& rFormulate ) { CEnmScanContext &aScanProt = GetScanContext(); U16 aStdCnt = aScanProt.mProtocol.stQuality.uStdRepeats * aScanProt.mProtocol.stQuality.uStd; rFormulate.calMethod = ENM_FORMULA_COMPARE; rFormulate.unFormul.stCompareCal.culFormula = 0; rFormulate.unFormul.stCompareCal.sampleCnt = aStdCnt; rFormulate.unFormul.stCompareCal.xUnit = aScanProt.mProtocol.stQuality.uAxisX; rFormulate.unFormul.stCompareCal.yUnit = aScanProt.mProtocol.stQuality.uAxisY; U16 aCnt = 0; for ( U16 i = 0; i < aScanProt.mProtocol.stQuality.uStd; i++ ) { rFormulate.unFormul.stCompareCal.stSampleData[aCnt++] = aScanProt.mProtocol.stQuality.stStdDensity[i]; for ( U16 j = 1; j < aScanProt.mProtocol.stQuality.uStdRepeats; j++ ) { rFormulate.unFormul.stCompareCal.stSampleData[aCnt] = aScanProt.mProtocol.stQuality.stStdDensity[i]; if ( rFormulate.unFormul.stCompareCal.stSampleData[aCnt-1].yPos < ENM_DATA_COUNT - 1 ) { rFormulate.unFormul.stCompareCal.stSampleData[aCnt].yPos = rFormulate.unFormul.stCompareCal.stSampleData[aCnt-1].yPos + 1; } else { rFormulate.unFormul.stCompareCal.stSampleData[aCnt].yPos = 0; rFormulate.unFormul.stCompareCal.stSampleData[aCnt].xPos = rFormulate.unFormul.stCompareCal.stSampleData[aCnt-1].xPos + 1; } aCnt++; } } return TRUE; } void CEnmDensityCurvePage::PickMax() { FP64 aConc = 0; FP64 aDensity = 0; FP64 *apConc = (FP64*)GetScanContext().mCalcData.GetConc( TRUE ); for ( U16 i = 0; i < mDataCount; i++ ) { if ( mDensity[i] > aDensity ) aDensity = mDensity[i]; if ( apConc[i] > aConc ) aConc = apConc[i]; } // mDensityMax = aDensity; // mConcMax = aConc; }
[ "yiyasail@hotmail.com" ]
yiyasail@hotmail.com
401a0f2ed3ad38ae42734302ee22ab7b96027b62
072ce61726df8d770c2e13758fbfb36b38a375a7
/homework4/display/layer/intensity_map_layer.h
77ee9b2712027da0e2e87836d44dee32b15332e7
[]
no_license
OceanS2000/PublicCourse
1271c88ca6b15e875ddcfdd4ef083a73508f777d
2a05962fc9d3f916b019622372a54c5b5f2cc2dd
refs/heads/master
2020-05-01T03:35:10.490137
2019-06-16T15:18:44
2019-06-16T15:18:44
177,248,556
1
0
null
2019-03-23T05:33:21
2019-03-23T05:33:21
null
UTF-8
C++
false
false
800
h
// Copyright @2018 Pony AI Inc. All rights reserved. #pragma once #include <string> #include <vector> #include "common/utils/display/layer.h" #include "homework4/display/map_gl_painter.h" #include "homework4/map/map_lib.h" namespace utils { namespace display { class IntensityMapLayer : public utils::display::Layer { public: explicit IntensityMapLayer(const std::string& name); ~IntensityMapLayer() override = default; void Draw() const override; protected: void InitializeOnContextCreated() override; private: void ShowIntensityMap(const std::vector<utils::display::IntensityMapImage>& images, double intensity_map_height) const; std::vector<utils::display::IntensityMapImage> intensity_map_images_; }; } // namespace display } // namespace utils
[ "xuanwang@pony.ai" ]
xuanwang@pony.ai
5110097d73fcb3d53baaa0db725715dee4675623
8ac0a283b1e9d6c887ce37001f1ba529fc507255
/src/qt/test/rpcnestedtests.cpp
3ca3ea442b7f405093a0af5feba1ef858d267aba
[ "MIT" ]
permissive
hutlim/sharecoin-test
7f13920cdd2e3acfd9ef293ce78e1c04d7d129b5
dd0e5db7bb2ff0ab1b089815d328994d878d9b8b
refs/heads/master
2021-05-13T22:32:14.505445
2018-01-08T06:55:17
2018-01-08T06:55:17
116,359,799
0
0
null
null
null
null
UTF-8
C++
false
false
7,452
cpp
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcnestedtests.h" #include "chainparams.h" #include "consensus/validation.h" #include "fs.h" #include "validation.h" #include "rpc/register.h" #include "rpc/server.h" #include "rpcconsole.h" #include "test/testutil.h" #include "test/test_bitcoin.h" #include "univalue.h" #include "util.h" #include <QDir> #include <QtGlobal> static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request) { if (request.fHelp) { return "help message"; } return request.params.write(0, 0); } static const CRPCCommand vRPCCommands[] = { { "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} }, }; void RPCNestedTests::rpcNestedTests() { // do some test setup // could be moved to a more generic place when we add more tests on QT level tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]); ClearDatadirCache(); std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_sharecoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); QDir dir(QString::fromStdString(path)); dir.mkpath("."); gArgs.ForceSetArg("-datadir", path); //mempool.setSanityCheck(1.0); TestingSetup test; SetRPCWarmupFinished(); std::string result; std::string result2; std::string filtered; RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path QVERIFY(result=="main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)"); RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated QVERIFY(result.substr(0,1) == "{"); (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key QVERIFY(result == "null"); (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed QVERIFY(result == result2); (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed QVERIFY(result == result2); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered); QVERIFY(result == "97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9"); QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]"); RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered); QVERIFY(filtered == "importprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered); QVERIFY(filtered == "signrawtransaction(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered); QVERIFY(filtered == "walletpassphrase(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); QVERIFY(filtered == "walletpassphrasechange(…)"); RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered); QVERIFY(filtered == "help(encryptwallet(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest"); QVERIFY(result == "[]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''"); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\""); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc"); QVERIFY(result == "[\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc"); QVERIFY(result == "[\"abc\",\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )"); QVERIFY(result == "[\"abc\",\"cba\"]"); #if QT_VERSION >= 0x050300 // do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3) QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using , #endif fs::remove_all(fs::path(path)); }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
59c98ae6343bbc0090870e47c67943a92781a3a7
578057387314e1796fb3b16cb95b71f7a23410d6
/tests/unittests/lit_cases/test_xnnpack/test_logsoftmax_axis_1_expanded_xnnpack.cc
37299cc24edd3d70f85ad8808357625140d5364c
[ "Apache-2.0" ]
permissive
alibaba/heterogeneity-aware-lowering-and-optimization
986b417eb8e4d229fc8cc6e77bb4eff5c6fa654d
966d4aa8f72f42557df58a4f56a7d44b88068e80
refs/heads/master
2023-08-28T22:15:13.439329
2023-01-06T00:39:07
2023-01-06T07:26:38
289,420,807
256
94
Apache-2.0
2023-06-13T10:38:25
2020-08-22T04:45:46
C++
UTF-8
C++
false
false
1,919
cc
//===-test_logsoftmax_axis_1_expanded_xnnpack.cc-----------------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // 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. // ============================================================================= // clang-format off // Testing CXX Code Gen using ODLA API on xnnpack // RUN: %halo_compiler -target cxx -o %data_path/test_logsoftmax_axis_1_expanded/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_logsoftmax_axis_1_expanded/test_data_set_0/output_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_logsoftmax_axis_1_expanded/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_logsoftmax_axis_1_expanded/test_data_set_0/input_0.pb // RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_logsoftmax_axis_1_expanded/model.onnx -o %t.cc // RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include // RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_logsoftmax_axis_1_expanded/test_data_set_0 %odla_link %device_link -lodla_xnnpack -o %t_xnnpack.exe -Wno-deprecated-declarations // RUN: %t_xnnpack.exe 0.0001 0 xnnpack %data_path/test_logsoftmax_axis_1_expanded | FileCheck %s // CHECK: Result Pass // clang-format on // XFAIL: * #include "test_logsoftmax_axis_1_expanded_xnnpack.cc.tmp.main.cc.in"
[ "74580362+xuhongyao@users.noreply.github.com" ]
74580362+xuhongyao@users.noreply.github.com
c98175b17939b54c1a5115c5403ebed07596132b
b0b500980f0fc6902bfd32bcdc05716ae7372de7
/Angel/Libraries/gwen/include/Gwen/Renderers/OpenGL.h
13c5854386db27c1c38d6d9328be043d4a99e8c8
[]
no_license
Gi133/Honours-Project
ba31639a95a9ba1ec26d7ee88a57090851cbb155
f30ff50c61f45c419c4d0ea5722d0bc58eeb50b6
refs/heads/master
2021-01-21T22:26:51.267727
2015-06-18T15:43:45
2015-06-18T15:43:45
30,205,845
2
1
null
null
null
null
UTF-8
C++
false
false
1,679
h
/* GWEN Copyright (c) 2011 Facepunch Studios See license in Gwen.h */ #ifndef GWEN_RENDERERS_OPENGL_H #define GWEN_RENDERERS_OPENGL_H #include "Gwen/Gwen.h" #include "Gwen/BaseRender.h" namespace Gwen { namespace Renderer { class OpenGL : public Gwen::Renderer::Base { public: struct Vertex { float x, y, z; float u, v; unsigned char r, g, b, a; }; OpenGL(); ~OpenGL(); virtual void Init(); virtual void Begin(); virtual void End(); virtual void SetDrawColor(Gwen::Color color); virtual void DrawFilledRect(Gwen::Rect rect); void StartClip(); void EndClip(); void DrawTexturedRect(Gwen::Texture* pTexture, Gwen::Rect pTargetRect, float u1 = 0.0f, float v1 = 0.0f, float u2 = 1.0f, float v2 = 1.0f); void LoadTexture(Gwen::Texture* pTexture); void FreeTexture(Gwen::Texture* pTexture); Gwen::Color PixelColour(Gwen::Texture* pTexture, unsigned int x, unsigned int y, const Gwen::Color& col_default); protected: static const int MaxVerts = 1024; void Flush(); void AddVert(int x, int y, float u = 0.0f, float v = 0.0f); Gwen::Color m_Color; int m_iVertNum; Vertex m_Vertices[MaxVerts]; public: // // Self Initialization // virtual bool InitializeContext(Gwen::WindowProvider* pWindow); virtual bool ShutdownContext(Gwen::WindowProvider* pWindow); virtual bool PresentContext(Gwen::WindowProvider* pWindow); virtual bool ResizedContext(Gwen::WindowProvider* pWindow, int w, int h); virtual bool BeginContext(Gwen::WindowProvider* pWindow); virtual bool EndContext(Gwen::WindowProvider* pWindow); void* m_pContext; }; } } #endif
[ "xkostascy@hotmail.com" ]
xkostascy@hotmail.com
908a12fef999839c283cdb071ba1c2fa71e83df2
5e95e1a37fdb4713c5eb30bfbf1e5be2cf311915
/src/Universe/GridWnd.cpp
b84b12cb2dfd0ec923f74a9ba18c04e77daa869d
[]
no_license
CycCoder/OpenUniverse
bd489d2be99665ce702c31b1aae74c66f8ab7490
cba537a9fedb7ea1f31637a813283e9226f82f33
refs/heads/master
2023-04-03T00:43:09.523448
2021-02-02T00:11:51
2021-02-02T00:11:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,053
cpp
/******************************************************************************** * Web Runtime for Application - Version 1.0.0.202102020022 * ******************************************************************************** * Copyright (C) 2002-2021 by Tangram Team. All Rights Reserved. * There are Three Key Features of Webruntime: * 1. Built-in Modern Web Browser: Independent Browser Window and Browser Window * as sub windows of other windows are supported in the application process; * 2. DOM Plus: DOMPlus is a natural extension of the standard DOM system. * It allows the application system to support a kind of generalized web pages, * which are composed of standard DOM elements and binary components supported * by the application system; * 3. JavaScript for Application: Similar to VBA in MS office, JavaScript will * become a built-in programmable language in the application system, so that * the application system can be expanded and developed for the Internet based * on modern javscript/Web technology. * Use of this source code is governed by a BSD-style license that * can be found in the LICENSE file. * * CONTACT INFORMATION: * mailto:tangramteam@outlook.com or mailto:sunhuizlz@yeah.net * https://www.tangram.dev *******************************************************************************/ // Xobj.cpp : implementation file #include "stdafx.h" #include "UniverseApp.h" #include "Cosmos.h" #include "Xobj.h" #include "Galaxy.h" #include "XobjHelper.h" #include "GridWnd.h" #include "chromium/Browser.h" #include "chromium/WebPage.h" struct AUX_DATA { // system metrics int cxVScroll, cyHScroll; int cxIcon, cyIcon; int cxBorder2, cyBorder2; // device metrics for screen int cxPixelsPerInch, cyPixelsPerInch; // convenient system color HBRUSH hbrWindowFrame; HBRUSH hbrBtnFace; // color values of system colors used for CToolBar COLORREF clrBtnFace, clrBtnShadow, clrBtnHilite; COLORREF clrBtnText, clrWindowFrame; // standard cursors HCURSOR hcurWait; HCURSOR hcurArrow; HCURSOR hcurHelp; // cursor used in Shift+F1 help // special GDI objects allocated on demand HFONT hStatusFont; HFONT hToolTipsFont; HBITMAP hbmMenuDot; // Implementation AUX_DATA(); ~AUX_DATA(); void UpdateSysColors(); void UpdateSysMetrics(); }; extern AFX_DATA AUX_DATA afxData; #ifndef AFX_CX_BORDER #define AFX_CX_BORDER CX_BORDER #endif #ifndef AFX_CY_BORDER #define AFX_CY_BORDER CY_BORDER #endif #define CX_BORDER 1 #define CY_BORDER 1 // CGridWnd enum HitTestValue { noHit = 0, vSplitterBox = 1, hSplitterBox = 2, bothSplitterBox = 3, // just for keyboard vSplitterBar1 = 101, vSplitterBar15 = 115, hSplitterBar1 = 201, hSplitterBar15 = 215, splitterIntersection1 = 301, splitterIntersection225 = 525 }; IMPLEMENT_DYNCREATE(CGridWnd, CSplitterWnd) CGridWnd::CGridWnd() { bInited = false; m_bCreated = false; m_pXobj = nullptr; m_pHostXobj = nullptr; m_nHostWidth = m_nHostHeight = 0; m_nMasterRow = m_nMasterCol = -1; m_Vmin = m_Vmax = m_Hmin = m_Hmax = 0; } CGridWnd::~CGridWnd() { } BEGIN_MESSAGE_MAP(CGridWnd, CSplitterWnd) ON_WM_SIZE() ON_WM_PAINT() ON_WM_DESTROY() ON_WM_MOUSEMOVE() ON_WM_MOUSEACTIVATE() ON_MESSAGE(WM_TABCHANGE, OnActivePage) ON_MESSAGE(WM_HUBBLE_GETNODE, OnGetCosmosObj) ON_MESSAGE(WM_COSMOSMSG, OnSplitterNodeAdd) ON_MESSAGE(WM_TGM_SETACTIVEPAGE, OnActiveTangramObj) ON_MESSAGE(WM_HOSTNODEFORSPLITTERCREATED, OnSplitterCreated) END_MESSAGE_MAP() // CGridWnd diagnostics #ifdef _DEBUG void CGridWnd::AssertValid() const { //CSplitterWnd::AssertValid(); } #ifndef _WIN32_WCE void CGridWnd::Dump(CDumpContext& dc) const { CSplitterWnd::Dump(dc); } #endif #endif //_DEBUG BOOL CGridWnd::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { if (CWnd::OnNotify(wParam, lParam, pResult)) return TRUE; // route commands to the splitter to the parent frame window //*pResult = EnsureParentFrame()->SendMessage(WM_NOTIFY, wParam, lParam); return true; } void CGridWnd::TrackRowSize(int y, int row) { ASSERT_VALID(this); ASSERT(m_nRows > 1); CPoint pt(0, y); ClientToScreen(&pt); GetPane(row, 0)->ScreenToClient(&pt); m_pRowInfo[row].nIdealSize = pt.y; // new size if (pt.y < m_pRowInfo[row].nMinSize) { // resized too small m_pRowInfo[row].nIdealSize = 0; // make it go away if (GetStyle() & SPLS_DYNAMIC_SPLIT) DeleteRow(row); } else if (m_pRowInfo[row].nCurSize + m_pRowInfo[row + 1].nCurSize < pt.y + m_pRowInfo[row + 1].nMinSize) { // not enough room for other pane if (GetStyle() & SPLS_DYNAMIC_SPLIT) DeleteRow(row + 1); } if (m_pHostXobj && row != m_nRows - 1) { ASSERT(m_nRows > 0 && m_nCols > 0); // must have at least one pane CRect rectInside; GetInsideRect(rectInside); int i; int _nSize = rectInside.Height(); CSplitterWnd::CRowColInfo* pInfo; if (_nSize < 0) _nSize = 0; // if really too small, layout as zero size for (i = 0, pInfo = m_pRowInfo; i < m_nRows - 1; i++, pInfo++) { if (pInfo->nIdealSize < pInfo->nMinSize) pInfo->nIdealSize = 0; // too small to see _nSize -= pInfo->nIdealSize; } _nSize -= (m_nRows - 1) * m_cxSplitterGap; pInfo->nCurSize = _nSize; pInfo->nIdealSize = _nSize; } } void CGridWnd::TrackColumnSize(int x, int col) { ASSERT_VALID(this); ASSERT(m_nCols > 1); CPoint pt(x, 0); ClientToScreen(&pt); GetPane(0, col)->ScreenToClient(&pt); m_pColInfo[col].nIdealSize = pt.x; // new size if (pt.x < m_pColInfo[col].nMinSize) { // resized too small m_pColInfo[col].nIdealSize = 0; // make it go away if (GetStyle() & SPLS_DYNAMIC_SPLIT) DeleteColumn(col); } else if (m_pColInfo[col].nCurSize + m_pColInfo[col + 1].nCurSize < pt.x + m_pColInfo[col + 1].nMinSize) { // not enough room for other pane if (GetStyle() & SPLS_DYNAMIC_SPLIT) DeleteColumn(col + 1); } if (m_pHostXobj && col != m_nCols - 1) { ASSERT(m_nRows > 0 && m_nCols > 0); // must have at least one pane CRect rectInside; GetInsideRect(rectInside); int i; int _nSize = rectInside.Width(); CSplitterWnd::CRowColInfo* pInfo; if (_nSize < 0) _nSize = 0; // if really too small, layout as zero size for (i = 0, pInfo = m_pColInfo; i < m_nCols - 1; i++, pInfo++) { if (pInfo->nIdealSize < pInfo->nMinSize) pInfo->nIdealSize = 0; // too small to see _nSize -= pInfo->nIdealSize; } _nSize -= (m_nCols - 1) * m_cxSplitterGap; pInfo->nCurSize = _nSize; pInfo->nIdealSize = _nSize; } } LRESULT CGridWnd::OnSplitterNodeAdd(WPARAM wParam, LPARAM lParam) { if (lParam == 1992 || wParam == 0x01000 || wParam == 0) { return 0; } if (lParam == 1993) { //fix bug for .net Control or Window Form switch (wParam) { case 1: { bInited = true; ::PostMessage(m_hWnd, WM_COSMOSMSG, 2, 1993); return 0; } break; case 2: { m_pXobj->m_pXobjShareData->m_pGalaxy->HostPosChanged(); return 0; } break; case 3: { RecalcLayout(); return 0; } break; } return 0; } IXobj* _pXobj = nullptr; CString str = (LPCTSTR)lParam; CXobj* pOldNode = (CXobj*)g_pCosmos->m_pDesignXobj; CTangramXmlParse* pOld = pOldNode->m_pHostParse; long m_nRow; g_pCosmos->m_pDesignXobj->get_Row(&m_nRow); long m_nCol; g_pCosmos->m_pDesignXobj->get_Col(&m_nCol); IXobj* _pOldNode = nullptr; m_pXobj->GetXobj(m_nRow, m_nCol, &_pOldNode); CXobj* _pOldNode2 = (CXobj*)_pOldNode; CTangramXmlParse* _pOldParse = _pOldNode2->m_pHostParse; m_pXobj->ObserveEx(m_nRow, m_nCol, CComBSTR(L""), str.AllocSysString(), &_pXobj); CXobj* pXobj = (CXobj*)_pXobj; if (pXobj && pOldNode) { CGalaxy* pGalaxy = m_pXobj->m_pXobjShareData->m_pGalaxy; pXobj->m_pXobjShareData->m_pGalaxy->m_bDesignerState = true; CXobjVector::iterator it; it = find(m_pXobj->m_vChildNodes.begin(), m_pXobj->m_vChildNodes.end(), pOldNode); if (it != m_pXobj->m_vChildNodes.end()) { pXobj->m_pRootObj = m_pXobj->m_pRootObj; pXobj->m_pParentObj = m_pXobj; CXobjVector vec = pXobj->m_vChildNodes; CXobj* pChildNode = nullptr; for (auto it2 : pXobj->m_vChildNodes) { pChildNode = it2; pChildNode->m_pRootObj = m_pXobj->m_pRootObj; } CTangramXmlParse* pNew = pXobj->m_pHostParse; CTangramXmlParse* pRet = m_pXobj->m_pHostParse->ReplaceNode(pOld, pNew, _T("")); m_pXobj->m_vChildNodes.erase(it); m_pXobj->m_vChildNodes.push_back(pXobj); pOldNode->m_pHostWnd->DestroyWindow(); g_pCosmos->m_pDesignXobj = nullptr; RecalcLayout(); } } return -1; } LRESULT CGridWnd::OnActiveTangramObj(WPARAM wParam, LPARAM lParam) { //RecalcLayout(); //m_pXobj->m_pXobjShareData->m_pGalaxy->HostPosChanged(); //::InvalidateRect(::GetParent(m_hWnd), nullptr, true); return -1; } LRESULT CGridWnd::OnSplitterCreated(WPARAM wParam, LPARAM lParam) { int _nWidth = 0; SetColumnInfo(lParam, m_nHostWidth >= 0 ? m_nHostWidth : 0, _nWidth); SetRowInfo(wParam, m_nHostHeight, _nWidth); //SetColumnInfo(lParam, (m_nHostWidth>=0)? m_nHostWidth:0, _nWidth); //SetRowInfo(wParam, (m_nHostHeight>=0)? m_nHostHeight:0, _nWidth); return 0; } LRESULT CGridWnd::OnActivePage(WPARAM wParam, LPARAM lParam) { return CWnd::DefWindowProc(WM_TABCHANGE, wParam, lParam);; } void CGridWnd::StartTracking(int ht) { ASSERT_VALID(this); if (ht == noHit) return; CXobj* pXobj = m_pXobj->m_pXobjShareData->m_pGalaxy->m_pWorkXobj; if (pXobj && pXobj->m_pXobjShareData->m_pHostClientView) { pXobj->m_pHostWnd->ModifyStyle(WS_CLIPSIBLINGS, 0); } HWND hWnd = m_pXobj->m_pXobjShareData->m_pGalaxy->m_pGalaxyCluster->m_hWnd; if (((::GetWindowLong(hWnd, GWL_EXSTYLE) & WS_EX_MDICHILD)) || ::GetParent(hWnd) == NULL) ::BringWindowToTop(hWnd); GetInsideRect(m_rectLimit); if (ht >= splitterIntersection1 && ht <= splitterIntersection225) { // split two directions (two tracking rectangles) int row = (ht - splitterIntersection1) / 15; int col = (ht - splitterIntersection1) % 15; GetHitRect(row + vSplitterBar1, m_rectTracker); int yTrackOffset = m_ptTrackOffset.y; m_bTracking2 = true; GetHitRect(col + hSplitterBar1, m_rectTracker2); m_ptTrackOffset.y = yTrackOffset; } else if (ht == bothSplitterBox) { // hit on splitter boxes (for keyboard) GetHitRect(vSplitterBox, m_rectTracker); int yTrackOffset = m_ptTrackOffset.y; m_bTracking2 = true; GetHitRect(hSplitterBox, m_rectTracker2); m_ptTrackOffset.y = yTrackOffset; // center it m_rectTracker.OffsetRect(0, m_rectLimit.Height() / 2); m_rectTracker2.OffsetRect(m_rectLimit.Width() / 2, 0); } else { // only hit one bar GetHitRect(ht, m_rectTracker); } // steal focus and capture SetCapture(); SetFocus(); // make sure no updates are pending RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_UPDATENOW); // set tracking state and appropriate cursor m_bTracking = true; OnInvertTracker(m_rectTracker); if (m_bTracking2) OnInvertTracker(m_rectTracker2); m_htTrack = ht; } void CGridWnd::StopTracking(BOOL bAccept) { if (!m_bTracking) return; CGalaxy* pGalaxy = m_pXobj->m_pXobjShareData->m_pGalaxy; CXobj* pXobj = pGalaxy->m_pWorkXobj; if (pXobj && pXobj->m_pXobjShareData->m_pHostClientView) { pXobj->m_pHostWnd->ModifyStyle(0, WS_CLIPSIBLINGS); ::InvalidateRect(pGalaxy->m_hWnd, NULL, false); pXobj->m_pHostWnd->Invalidate(); } CSplitterWnd::StopTracking(bAccept); if (bAccept) { ::InvalidateRect(pGalaxy->m_hWnd, nullptr, true); CWebPage* pWebWnd = nullptr; if (pGalaxy->m_pWebPageWnd) { pWebWnd = pGalaxy->m_pWebPageWnd; } else if (g_pCosmos->m_pDesignXobj && g_pCosmos->m_pDesignXobj->m_pXobjShareData->m_pGalaxy->m_pWebPageWnd) pWebWnd = g_pCosmos->m_pDesignXobj->m_pXobjShareData->m_pGalaxy->m_pWebPageWnd; pGalaxy->HostPosChanged(); HWND h = ::GetParent(m_hWnd); if (h) { LRESULT lRes = ::SendMessage(h, WM_HUBBLE_GETNODE, 0, 0); if (lRes) { CXobj* pRetNode = (CXobj*)lRes; if (pRetNode && pRetNode->m_nViewType == Grid) { pRetNode->m_pXobjShareData->m_pGalaxy->HostPosChanged(); } } } RecalcLayout(); if (pWebWnd) { ::SendMessage(::GetParent(pWebWnd->m_hWnd), WM_BROWSERLAYOUT, 0, 4); ::PostMessage(::GetParent(pWebWnd->m_hWnd), WM_BROWSERLAYOUT, 0, 4); } } } void CGridWnd::PostNcDestroy() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); delete m_pXobj; CSplitterWnd::PostNcDestroy(); delete this; } // Generic routine: // for X direction: pInfo = m_pColInfo, nMax = m_nMaxCols, nSize = cx // for Y direction: pInfo = m_pRowInfo, nMax = m_nMaxRows, nSize = cy void CGridWnd::_LayoutRowCol(CSplitterWnd::CRowColInfo* pInfoArray, int nMax, int nSize, int nSizeSplitter, CXobj* pHostNode, bool bCol) { ASSERT(pInfoArray != NULL); ASSERT(nMax > 0); if (nSizeSplitter < 0) nSizeSplitter = 0; //ASSERT(nSizeSplitter > 0); CSplitterWnd::CRowColInfo* pInfo; CSplitterWnd::CRowColInfo* pInfoHost = nullptr; int i; if (nSize < 0) nSize = 0; // if really too small, layout as zero size // start with ideal sizes int _indexHost = -1; int _nSize = nSize; if (pHostNode) { if (bCol) _indexHost = pHostNode->m_nCol; else _indexHost = pHostNode->m_nRow; } if (_indexHost != -1) pInfoHost = &pInfoArray[_indexHost]; for (i = 0, pInfo = pInfoArray; i < nMax; i++, pInfo++) { if (pInfo->nIdealSize < pInfo->nMinSize) pInfo->nIdealSize = 0; // too small to see pInfo->nCurSize = pInfo->nIdealSize; if (_indexHost != -1) { if (_indexHost != i) { _nSize -= pInfo->nIdealSize; } } if (i == nMax - 1) { if (_indexHost != -1 && pInfoHost) { if (_indexHost != nMax - 1) { _nSize -= (nMax - 1) * nSizeSplitter; if (_nSize < 0) _nSize = 0; pInfoHost->nCurSize = _nSize; } else pInfoHost->nCurSize = INT_MAX; // last row/column takes the rest if (bCol) m_nHostWidth = _nSize; else m_nHostHeight = _nSize; } else pInfo->nCurSize = INT_MAX; // last row/column takes the rest } } for (i = 0, pInfo = pInfoArray; i < nMax; i++, pInfo++) { ASSERT(nSize >= 0); if (nSize == 0) { // no more room (set pane to be invisible) pInfo->nCurSize = 0; continue; // don't worry about splitters } else if (nSize < pInfo->nMinSize && i != 0) { // additional panes below the recommended minimum size // aren't shown and the size goes to the previous pane pInfo->nCurSize = 0; // previous pane already has room for splitter + border // add remaining size and remove the extra border ASSERT(afxData.cxBorder2 == afxData.cyBorder2); (pInfo - 1)->nCurSize += nSize + afxData.cxBorder2; nSize = 0; } else { // otherwise we can add the second pane ASSERT(nSize > 0); if (pInfo->nCurSize == 0) { // too small to see if (i != 0) pInfo->nCurSize = 0; } else if (nSize < pInfo->nCurSize) { // this row/col won't fit completely - make as small as possible pInfo->nCurSize = nSize; nSize = 0; } else { // can fit everything nSize -= pInfo->nCurSize; } } // see if we should add a splitter ASSERT(nSize >= 0); if (i != nMax - 1) { // should have a splitter if (nSize > nSizeSplitter) { nSize -= nSizeSplitter; // leave room for splitter + border ASSERT(nSize > 0); } else { // not enough room - add left over less splitter size ASSERT(afxData.cxBorder2 == afxData.cyBorder2); pInfo->nCurSize += nSize; if (pInfo->nCurSize > (nSizeSplitter - afxData.cxBorder2)) pInfo->nCurSize -= (nSizeSplitter - afxData.cyBorder2); nSize = 0; } } } //ASSERT(nSize == 0); // all space should be allocated } // repositions client area of specified window // assumes everything has WS_BORDER or is inset like it does // (includes scroll bars) void CGridWnd::_DeferClientPos(AFX_SIZEPARENTPARAMS* lpLayout, CWnd* pWnd, int x, int y, int cx, int cy, BOOL bScrollBar) { ASSERT(pWnd != NULL); ASSERT(pWnd->m_hWnd != NULL); CRect rect(x, y, x + cx, y + cy); // adjust for 3d border (splitter windows have implied border) if ((pWnd->GetExStyle() & WS_EX_CLIENTEDGE) || pWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd))) rect.InflateRect(afxData.cxBorder2, afxData.cyBorder2); // first check if the new rectangle is the same as the current CRect rectOld; pWnd->GetWindowRect(rectOld); pWnd->GetParent()->ScreenToClient(&rectOld); if (rect != rectOld) { ASSERT(pWnd->m_hWnd != NULL); ASSERT(rect != NULL); HWND hWndParent = ::GetParent(pWnd->m_hWnd); ASSERT(hWndParent != NULL); if (lpLayout != NULL && lpLayout->hDWP == NULL) return; // first check if the new rectangle is the same as the current CRect rectOld; ::GetWindowRect(pWnd->m_hWnd, rectOld); ::ScreenToClient(hWndParent, &rectOld.TopLeft()); ::ScreenToClient(hWndParent, &rectOld.BottomRight()); if (::EqualRect(rectOld, rect)) return; // nothing to do // try to use DeferWindowPos for speed, otherwise use SetWindowPos if (lpLayout != NULL) { lpLayout->hDWP = ::DeferWindowPos(lpLayout->hDWP, pWnd->m_hWnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOZORDER); } else { ::SetWindowPos(pWnd->m_hWnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOZORDER); } } else { ::PostMessage(pWnd->m_hWnd, WM_SPLITTERREPOSITION, 0, 0); } } void CGridWnd::RecalcLayout() { ASSERT_VALID(this); ASSERT(m_nRows > 0 && m_nCols > 0); // must have at least one pane||::IsWindowVisible(m_hWnd) == FALSE if (m_bCreated == false || GetDlgItem(IdFromRowCol(0, 0)) == NULL) return; _RecalcLayout(); } void CGridWnd::_RecalcLayout() { ASSERT_VALID(this); ASSERT(m_nRows > 0 && m_nCols > 0); // must have at least one pane if (m_nMaxCols >= 2) { int LimitWidth = 0; int LimitWndCount = 0; int Width = 0; RECT SplitterWndRect; GetWindowRect(&SplitterWndRect); Width = SplitterWndRect.right - SplitterWndRect.left - m_nMaxCols * m_cxSplitterGap - LimitWidth + m_cxBorder * m_nMaxCols; if (Width < 0) return; } AFX_MANAGE_STATE(AfxGetStaticModuleState()); CRect rectClient; GetClientRect(rectClient); rectClient.InflateRect(-m_cxBorder, -m_cyBorder); CRect rectInside; GetInsideRect(rectInside); // layout columns (restrict to possible sizes) _LayoutRowCol(m_pColInfo, m_nCols, rectInside.Width(), m_cxSplitterGap, m_pHostXobj, true); _LayoutRowCol(m_pRowInfo, m_nRows, rectInside.Height(), m_cySplitterGap, m_pHostXobj, false); // give the hint for the maximum number of HWNDs AFX_SIZEPARENTPARAMS layout; layout.hDWP = ::BeginDeferWindowPos((m_nCols + 1) * (m_nRows + 1) + 1); //BLOCK: Reposition all the panes { int x = rectClient.left; for (int col = 0; col < m_nCols; col++) { int cxCol = m_pColInfo[col].nCurSize; int y = rectClient.top; for (int row = 0; row < m_nRows; row++) { int cyRow = m_pRowInfo[row].nCurSize; CWnd* pWnd = GetPane(row, col); if (pWnd) _DeferClientPos(&layout, pWnd, x, y, cxCol, cyRow, FALSE); y += cyRow + m_cySplitterGap; } x += cxCol + m_cxSplitterGap; } } // move and resize all the windows at once! if (layout.hDWP == NULL || !::EndDeferWindowPos(layout.hDWP)) TRACE(traceAppMsg, 0, "Warning: DeferWindowPos failed - low system resources.\n"); // invalidate all the splitter bars (with NULL pDC) DrawAllSplitBars(NULL, rectInside.right, rectInside.bottom); //::InvalidateRect(m_hWnd, nullptr, false); } BOOL CGridWnd::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { m_pXobj = g_pCosmos->m_pActiveXobj; m_pXobj->m_pHostWnd = this; m_pXobj->m_nViewType = Grid; m_pXobj->m_nID = nID; m_pXobj->m_pDisp = nullptr; int r, g, b; CComBSTR bstrVal(L""); m_pXobj->get_Attribute(CComBSTR("lefttopcolor"), &bstrVal); if (!CString(bstrVal).IsEmpty()) { _stscanf_s(CString(bstrVal), _T("RGB(%d,%d,%d)"), &r, &g, &b); rgbLeftTop = RGB(r, g, b); } else { rgbLeftTop = RGB(240, 240, 240); } bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR("rightbottomcolor"), &bstrVal); if (!CString(bstrVal).IsEmpty()) { _stscanf_s(CString(bstrVal), _T("RGB(%d,%d,%d)"), &r, &g, &b); rgbRightBottom = RGB(r, g, b); } else { rgbRightBottom = RGB(240, 240, 240); } bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"middlecolor"), &bstrVal); if (!CString(bstrVal).IsEmpty()) { _stscanf_s(CString(bstrVal), _T("RGB(%d,%d,%d)"), &r, &g, &b); rgbMiddle = RGB(r, g, b); } else { rgbMiddle = RGB(240, 240, 240); } bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"splitterwidth"), &bstrVal); m_cxSplitterGap = m_cySplitterGap = m_cxSplitter = m_cySplitter = !CString(bstrVal).IsEmpty() ? _ttoi(CString(bstrVal)) : 7; bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"borderwidth"), &bstrVal); m_cxBorder = m_cyBorder = !CString(bstrVal).IsEmpty() ? _ttoi(CString(bstrVal)) : 2; bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"vmin"), &bstrVal); m_Vmin = !CString(bstrVal).IsEmpty() ? _ttoi(CString(bstrVal)) : 0; bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"vmax"), &bstrVal); if (!CString(bstrVal).IsEmpty()) { m_Vmax = _ttoi(CString(bstrVal)); if (m_Vmax <= 0) m_Vmax = 65535; } else m_Vmax = 65535; bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"hmin"), &bstrVal); m_Hmin = !CString(bstrVal).IsEmpty() ? _ttoi(CString(bstrVal)) : 0; bstrVal.Empty(); m_pXobj->get_Attribute(CComBSTR(L"hmax"), &bstrVal); if (!CString(bstrVal).IsEmpty()) { m_Hmax = _ttoi(CString(bstrVal)); if (m_Hmax <= 0) m_Hmax = 65535; } else m_Hmax = 65535; m_pXobj->m_nRows = m_pXobj->m_pHostParse->attrInt(TGM_ROWS, 0); m_pXobj->m_nCols = m_pXobj->m_pHostParse->attrInt(TGM_COLS, 0); m_nMasterRow = m_pXobj->m_pHostParse->attrInt(L"masterrow", -1); m_nMasterCol = m_pXobj->m_pHostParse->attrInt(L"mastercol", -1); if (nID == 0) nID = 1; if (CreateStatic(pParentWnd, m_pXobj->m_nRows, m_pXobj->m_nCols, dwStyle, nID)) { m_pXobj->NodeCreated(); CString strWidth = m_pXobj->m_pHostParse->attr(TGM_WIDTH, _T("")); strWidth += _T(","); CString strHeight = m_pXobj->m_pHostParse->attr(TGM_HEIGHT, _T("")); strHeight += _T(","); int nWidth, nHeight, nPos; CString strW, strH, strOldWidth, strName = _T(""); strOldWidth = strWidth; vector<CTangramXmlParse*> vecParse; long nSize = m_pXobj->m_pHostParse->GetCount(); for (int i = 0; i < nSize; i++) { CTangramXmlParse* _pChild = m_pXobj->m_pHostParse->GetChild(i); if (_pChild->name().CompareNoCase(TGM_XOBJ) == 0) vecParse.push_back(_pChild); } nSize = vecParse.size(); int nIndex = 0; CTangramXmlParse* pSubItem = vecParse[nIndex]; if (pSubItem == nullptr) { strName.Format(_T("%s_splitterchild_%i"), m_pXobj->m_strName, 0); pSubItem = m_pXobj->m_pHostParse->AddNode(strName); vecParse.push_back(pSubItem); } for (int i = 0; i < m_pXobj->m_nRows; i++) { nPos = strHeight.Find(_T(",")); strH = strHeight.Left(nPos); strHeight = strHeight.Mid(nPos + 1); nHeight = _ttoi(strH); strWidth = strOldWidth; for (int j = 0; j < m_pXobj->m_nCols; j++) { nPos = strWidth.Find(_T(",")); strW = strWidth.Left(nPos); strWidth = strWidth.Mid(nPos + 1); nWidth = _ttoi(strW); CXobj* pObj = new CComObject<CXobj>; pObj->m_pRootObj = m_pXobj->m_pRootObj; pObj->m_pHostParse = pSubItem; pObj->m_pParentObj = m_pXobj; m_pXobj->AddChildNode(pObj); pObj->m_nRow = i; pObj->m_nCol = j; pObj->InitWndXobj(); if (pObj->m_pObjClsInfo) { pObj->m_nWidth = nWidth; pObj->m_nHeigh = nHeight; if (pContext->m_pNewViewClass == nullptr) pContext->m_pNewViewClass = RUNTIME_CLASS(CXobjHelper); CreateView(pObj->m_nRow, pObj->m_nCol, pObj->m_pObjClsInfo, CSize(max(pObj->m_nWidth, m_Hmin), max(pObj->m_nHeigh, m_Vmin)), pContext); } if (m_nMasterRow == i && m_nMasterCol == j) { m_pHostXobj = pObj; } nIndex++; if (nIndex < nSize) { pSubItem = vecParse[nIndex]; } else { if (nIndex < m_pXobj->m_nCols * m_pXobj->m_nRows) { strName.Format(_T("%s_splitterchild_%i"), m_pXobj->m_strName, nIndex); pSubItem = m_pXobj->m_pHostParse->AddNode(strName); vecParse.push_back(pSubItem); } } } } SetWindowPos(NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOREDRAW); SetWindowText(m_pXobj->m_strNodeName); m_bCreated = true; CXobj* pHostNode = nullptr; CXobj* pParent = nullptr; CGalaxy* pGalaxy = m_pXobj->m_pXobjShareData->m_pGalaxy; bool bHasHostView = false; if (pGalaxy->m_pBindingXobj) { pHostNode = pGalaxy->m_pBindingXobj; if (::IsChild(m_hWnd, pHostNode->m_pHostWnd->m_hWnd)) { bHasHostView = true; pParent = pHostNode->m_pParentObj; while (pParent != m_pXobj) { pHostNode = pParent; pParent = pHostNode->m_pParentObj; } } } if (pHostNode && ::IsChild(m_hWnd, pHostNode->m_pHostWnd->m_hWnd)) m_pHostXobj = pHostNode; _RecalcLayout(); return true; } return false; } LRESULT CGridWnd::OnGetCosmosObj(WPARAM wParam, LPARAM lParam) { if (m_pXobj) return (LRESULT)m_pXobj; return (long)CWnd::DefWindowProc(WM_HUBBLE_GETNODE, wParam, lParam);; } void CGridWnd::OnPaint() { ASSERT_VALID(this); CPaintDC dc(this); CRect rectClient; GetClientRect(&rectClient); CRect rectInside; GetInsideRect(rectInside); rectInside.InflateRect(4, 4); // draw the splitter boxes if (m_bHasVScroll && m_nRows < m_nMaxRows) { OnDrawSplitter(&dc, splitBox, CRect(rectInside.right, rectClient.top, rectClient.right, rectClient.top + m_cySplitter)); } if (m_bHasHScroll && m_nCols < m_nMaxCols) { OnDrawSplitter(&dc, splitBox, CRect(rectClient.left, rectInside.bottom, rectClient.left + m_cxSplitter, rectClient.bottom)); } // extend split bars to window border (past margins) DrawAllSplitBars(&dc, rectInside.right, rectInside.bottom); // draw splitter intersections (inside only) GetInsideRect(rectInside); dc.IntersectClipRect(rectInside); CRect rect; rect.top = rectInside.top; for (int row = 0; row < m_nRows - 1; row++) { rect.top += m_pRowInfo[row].nCurSize + m_cyBorderShare; rect.bottom = rect.top + m_cySplitter; rect.left = rectInside.left; for (int col = 0; col < m_nCols - 1; col++) { rect.left += m_pColInfo[col].nCurSize + m_cxBorderShare; rect.right = rect.left + m_cxSplitter; OnDrawSplitter(&dc, splitIntersection, rect); rect.left = rect.right + m_cxBorderShare; } rect.top = rect.bottom + m_cxBorderShare; } } void CGridWnd::OnDrawSplitter(CDC* pDC, ESplitType nType, const CRect& rectArg) { if (pDC == nullptr) { RedrawWindow(rectArg, NULL, RDW_INVALIDATE | RDW_NOCHILDREN); return; } ASSERT_VALID(pDC); ; // otherwise, actually draw CRect rect = rectArg; switch (nType) { case splitBorder: //ASSERT(afxData.bWin4); pDC->Draw3dRect(rect, rgbLeftTop, rgbRightBottom); rect.InflateRect(-AFX_CX_BORDER, -AFX_CY_BORDER); pDC->Draw3dRect(rect, rgbLeftTop, rgbRightBottom); return; case splitIntersection: //ASSERT(afxData.bWin4); break; case splitBox: //if (afxData.bWin4) { pDC->Draw3dRect(rect, rgbLeftTop, rgbRightBottom); rect.InflateRect(-AFX_CX_BORDER, -AFX_CY_BORDER); pDC->Draw3dRect(rect, rgbLeftTop, rgbRightBottom); rect.InflateRect(-AFX_CX_BORDER, -AFX_CY_BORDER); break; } // fall through... case splitBar: { pDC->FillSolidRect(rect, rgbMiddle); //pDC->FillSolidRect(rect, rgbMiddle); if ((rect.bottom - rect.top) > (rect.right - rect.left)) { rect.bottom -= 1; rect.top += 1; } else { rect.right -= 1; rect.left += 1; } } break; default: ASSERT(false); // unknown splitter type } } BOOL CGridWnd::PreCreateWindow(CREATESTRUCT& cs) { cs.lpszClass = g_pCosmos->m_lpszSplitterClass; cs.style |= WS_CLIPSIBLINGS; return CSplitterWnd::PreCreateWindow(cs); } void CGridWnd::DrawAllSplitBars(CDC* pDC, int cxInside, int cyInside) { //ColRect.clear(); //RowRect.clear(); ASSERT_VALID(this); int col; int row; CRect rect; // draw pane borders GetClientRect(rect); int x = rect.left; for (col = 0; col < m_nCols; col++) { int cx = m_pColInfo[col].nCurSize + 2 * m_cxBorder; if (col == m_nCols - 1 && m_bHasVScroll) cx += afxData.cxVScroll - CX_BORDER; int y = rect.top; for (row = 0; row < m_nRows; row++) { int cy = m_pRowInfo[row].nCurSize + 2 * m_cyBorder; if (row == m_nRows - 1 && m_bHasHScroll) cy += afxData.cyHScroll - CX_BORDER; OnDrawSplitter(pDC, splitBorder, CRect(x, y, x + cx, y + cy)); y += cy + m_cySplitterGap - 2 * m_cyBorder; } x += cx + m_cxSplitterGap - 2 * m_cxBorder; } // draw column split bars GetClientRect(rect); rect.left += m_cxBorder; for (col = 0; col < m_nCols - 1; col++) { rect.left += m_pColInfo[col].nCurSize + m_cxBorderShare; rect.right = rect.left + m_cxSplitter; if (rect.left > cxInside) break; // stop if not fully visible //ColumnsplitBar = rect; //ColRect.push_back(rect); OnDrawSplitter(pDC, splitBar, rect); rect.left = rect.right + m_cxBorderShare; } // draw row split bars GetClientRect(rect); rect.top += m_cyBorder; for (row = 0; row < m_nRows - 1; row++) { rect.top += m_pRowInfo[row].nCurSize + m_cyBorderShare; rect.bottom = rect.top + m_cySplitter; if (rect.top > cyInside) break; // stop if not fully visible //RowsplitBar = rect; //RowRect.push_back(rect); OnDrawSplitter(pDC, splitBar, rect); rect.top = rect.bottom + m_cyBorderShare; } } CWnd* CGridWnd::GetActivePane(int* pRow, int* pCol) { CWnd* pView = nullptr; pView = GetFocus(); // make sure the pane is a child pane of the splitter if (pView != nullptr && !IsChildPane(pView, pRow, pCol)) pView = nullptr; return pView; } int CGridWnd::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message) { if (g_pCosmos->m_pActiveHtmlWnd) { g_pCosmos->m_pActiveHtmlWnd = nullptr; } CGalaxy* pGalaxy = m_pXobj->m_pXobjShareData->m_pGalaxy; if (pGalaxy->m_pGalaxyCluster->m_pUniverseAppProxy) { HWND hMenuWnd = pGalaxy->m_pGalaxyCluster->m_pUniverseAppProxy->GetActivePopupMenu(nullptr); if (::IsWindow(hMenuWnd)) ::PostMessage(hMenuWnd, WM_CLOSE, 0, 0); } else if ((long)(g_pCosmos->m_pActiveAppProxy) > 1) { HWND hMenuWnd = g_pCosmos->m_pActiveAppProxy->GetActivePopupMenu(nullptr); if (::IsWindow(hMenuWnd)) ::PostMessage(hMenuWnd, WM_CLOSE, 0, 0); } return MA_ACTIVATE;// CSplitterWnd::OnMouseActivate(pDesktopWnd, nHitTest, message); } void CGridWnd::Save() { CString strWidth = _T(""); CString strHeight = _T(""); int minCx, minCy; for (int i = 0; i < m_pXobj->m_nRows; i++) { int iHeight; CString strH; GetRowInfo(i, iHeight, minCy); strH.Format(_T("%d,"), iHeight); strHeight += strH; } for (int j = 0; j < m_pXobj->m_nCols; j++) { int iWidth; CString strW; GetColumnInfo(j, iWidth, minCx); strW.Format(_T("%d,"), iWidth); strWidth += strW; } m_pXobj->put_Attribute(CComBSTR(TGM_HEIGHT), CComBSTR(strHeight)); m_pXobj->put_Attribute(CComBSTR(TGM_WIDTH), CComBSTR(strWidth)); } void CGridWnd::OnMouseMove(UINT nFlags, CPoint point) { if (point.x < m_Hmin && point.y < m_Vmin) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmin, m_Vmin)); } else if (point.x < m_Hmin && point.y > m_Vmin && point.y < m_Vmax) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmin, point.y)); } else if (point.x < m_Hmin && point.y > m_Vmax) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmin, m_Vmax)); } else if (point.x > m_Hmax && point.y < m_Vmin) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmax, m_Vmin)); } else if (point.x > m_Hmax && point.y > m_Vmin && point.y < m_Vmax) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmax, point.y)); } else if (point.x > m_Hmax && point.y > m_Vmax) { CSplitterWnd::OnMouseMove(nFlags, CPoint(m_Hmax, m_Vmax)); } else if (point.x > m_Hmin && point.x < m_Hmax && point.y > m_Vmax) { CSplitterWnd::OnMouseMove(nFlags, CPoint(point.x, m_Vmax)); } else if (point.x > m_Hmin && point.x < m_Hmax && point.y < m_Vmin) { CSplitterWnd::OnMouseMove(nFlags, CPoint(point.x, m_Vmin)); } else { CSplitterWnd::OnMouseMove(nFlags, point); } //CDC *pDC = GetDC(); //for (int col = 0; col < m_nCols - 1; col++) //{ // if(PtInRect( &ColRect.at(col),point) && bColMoving == 0) // { // pDC->FillSolidRect(&(ColRect.at(col)),rgbMiddle); // } //} //for (int row = 0; row < m_nRows - 1; row++) //{ // if(PtInRect( &RowRect.at(row),point)) // { // pDC->FillSolidRect(&(RowRect.at(row)), rgbMiddle); // } //} } void CGridWnd::OnSize(UINT nType, int cx, int cy) { __super::OnSize(nType, cx, cy); if (m_pColInfo != nullptr) RecalcLayout(); } void CGridWnd::OnDestroy() { m_pXobj->Fire_Destroy(); __super::OnDestroy(); }
[ "sunhuizlz@yeah.net" ]
sunhuizlz@yeah.net
3cc1a162c8e94dc64bc8f22e4e9d1e64f3d67510
bc0237bfefc79f5ea1c73e6a59e1ad1e979c0d68
/spillere.cpp
c2b5ba47082da6b5cbee99e6be7524335081af9c
[]
no_license
nestor1119/ooprog-Gruppe-33
9f6bfafdbb7d1be83c9e4b3cb4b1eaebce298de3
636280c5e2663783c0247a2f2cfadb2a7daeec8f
refs/heads/main
2023-04-21T19:58:45.242385
2021-05-13T17:20:38
2021-05-13T17:20:38
367,121,667
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,397
cpp
#include <iostream> #include <fstream> #include "spillere.h" #include "spiller.h" using namespace std; Spillere::Spillere() //konstruktor uten parameter { spillerListe = new List(Sorted); // oppretter ny, sortert liste sisteSpillernr = 0; // Setter siste lik 0 } Spillere::~Spillere() //Destructor { delete spillerListe; } void Spillere::skrivAlleSpillere() //skriver ut alle spillere { cout << "Siste spillernummer er: " << sisteSpillernr << endl; spillerListe->displayList(); //display alle spillere } void Spillere::skrivSpiller(int n) // Skriver ut spiller med gitt nummer { if (spillerListe->inList(n)) { //hvis den finnes spillerListe->displayElement(n); //display spiller } else //hvis den ikke finnes { cout << "Spilleren finnes ikke" << endl; } } void Spillere::nySpiller() // Legger til ny spiller i lista { Spiller* addSpiller; // Lager en temp peker addSpiller = new Spiller(++sisteSpillernr); // Teller opp siste nummer spillerListe->add(addSpiller); // og legger til } void Spillere::nySpillerr(char nav[NVNLEN], ifstream &inn) //leser inn ny spiller fra fil med medsendt navn { Spiller* addSpiller; addSpiller = new Spiller(inn, nav, ++sisteSpillernr); //lager nytt spiller object fra medsent navn og fildata spillerListe->add(addSpiller); //adderer spilleren til spillerliste } void Spillere::skrivSpiller(char c[STRLEN]) //skriver spilleren ut med medsent navn { bool finnes = false; Spiller* Hjelpe; for (int i = 1; i <= sisteSpillernr; i++) //går gjennom alle spillere { if (spillerListe->inList(i)) { //hvis spilleren finnes i lista Hjelpe = (Spiller*)spillerListe->remove(i); //henter spilleren spillerListe->add(Hjelpe); //legger den inni lista if (Hjelpe->finnesSpiller(c)) { //sjekker at den spilleren finnes med navn spillerListe->displayElement(i); //¨skriver den ut til skjerm finnes = true; } } } if (!finnes) { cout << "Spilleren finnes ikke!"; } } void Spillere::lesFraFil() { //leser spilleren fra fil int antSpillere = 0; Spiller* addSpiller; // Lager en temp peker ifstream inn("SPILLERE.DTA"); // Åpner filen det leses fra if (inn) { // Hvis filen finnes: inn >> antSpillere; inn.ignore(); // Les antall spillere for (int i = 1; i <= antSpillere; i++) { addSpiller = new Spiller(inn, ++sisteSpillernr); // Teller opp siste nummer spillerListe->add(addSpiller); // og legger den til liste } } else cout << "Fant ikke filen!\n"; } int Spillere::hentSistespillernr() { //returnerer siste spiller number return sisteSpillernr; } void Spillere::fjernSpiller() //fjerner spiller { int i; cout << "\nHvilket spillernummer skal fjernes: "; cin >> i; // Les spillernummer if (spillerListe->inList(i)) { // Hvis spilleren er i lista spillerListe->destroy(i); // Slett spiller } else // Spilleren er ikke lista { cout << "Spilleren finnes ikke!\n"; } } void Spillere::skrivTilFil() //skriver spillere til fil { int ant; Spiller* Hjelpe; ofstream ut("SPILLERE.DTA"); //lager DTA fil eller finner den ant = spillerListe->noOfElements(); // Henter antall spillere ut << ant << "\n"; for (int i = 1; i <= ant; i++) // For hver spiller { Hjelpe = (Spiller*)spillerListe->remove(i); // Hent spiller Hjelpe->skrivTilFil(ut); // og skriv til fil } }
[ "nestorgfortique@gmail.com" ]
nestorgfortique@gmail.com
506e628f3e335280873d2da771d66b66f795a48f
963cd65d9167cb2217a327260673fc5c64443f47
/src/Query/QueryEntity.h
20b7955d3795bc9d0b98c925df98e7643136190a
[ "Apache-2.0" ]
permissive
salmanahmedshaikh/StreamingCube
749b5753a8c7f4e6f33478c1d06d048796334a05
18ae206c664a269eb70110f34c9a28438a13aec2
refs/heads/master
2021-06-13T21:51:12.278973
2021-02-02T13:40:08
2021-02-02T13:40:08
142,138,212
1
1
null
null
null
null
UTF-8
C++
false
false
2,724
h
////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2017 KDE Laboratory, University of Tsukuba, Tsukuba, Japan. // // // // The JsSpinnerSPE/StreamingCube and the accompanying materials are made available // // under the terms of Eclipse Public License v1.0 which accompanies this distribution // // and is available at <https://eclipse.org/org/documents/epl-v10.php> // ////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <boost/shared_ptr.hpp> #include "../Query/QueryIntermediateRepresentation.h" #include "../IO/IStreamOutput.h" #include "../Operator/LeafOperator.h" #include "../Operator/Operator.h" #include "../Common/Types.h" #include <boost/tuple/tuple.hpp> #include "../Internal/Queue/QueueEntity.h" class RootOperator; class QueryEntity { private: boost::shared_ptr<IStreamOutput> streamOutput; // std::list<boost::shared_ptr<Operator> >operatorList; // bool active; TimeDuration activateDuration; TimeDuration rangeWindowSize; Timestamp lastActivatedTimestamp; std::map<LeafOperator*, bool> masterTagMap; std::map<LeafOperator*, boost::shared_ptr<QueueEntity> > outputQueueMap; boost::shared_ptr<RootOperator> rootOperator; //added by salman bool isDispatcher; bool isExecutor; int queryID; public: QueryEntity(boost::shared_ptr<QueryIntermediateRepresentation>queryIntermediateRepresentation,boost::shared_ptr<IStreamOutput> streamOutput, std::string durationSpecification); QueryEntity(boost::shared_ptr<QueryIntermediateRepresentation> queryIntermediateRepresentation,boost::shared_ptr<IStreamOutput> streamOutput,std::string durationSpecification, bool isDispatcher); ~QueryEntity(); bool getIsDispatcher(); void setIsDispatcher(bool is_Dispatcher); bool getIsExecutor(); void setIsExecutor(bool is_Executor); void setActive(Timestamp ts); bool isActive(Timestamp ts); void addMasterTag(LeafOperator* leafOperator, bool masterTag); bool getMasterTag(LeafOperator* leafOperator); void setRangeWindowSize(TimeDuration rangeWindowSize); TimeDuration getRangeWindowSize(); //salman int getQueryID(void); void addOutputQueue(LeafOperator* leafOperator, boost::shared_ptr<QueueEntity> outputQueue); boost::shared_ptr<QueueEntity> getOutputQueue (LeafOperator* leafOperator) ; friend class QueryIntermediateRepresentationInterpreter; void changeLeafOperator(boost::shared_ptr<LeafOperator>fromOperator, boost::shared_ptr<LeafOperator>toOperator); Timestamp getLastActivatedTimestamp(); boost::shared_ptr<RootOperator> getRootOperator(); };
[ "engrsalmanshaikh@gmail.com" ]
engrsalmanshaikh@gmail.com
9d0e91b3a351931ad3bc66c083bd80a05230e68b
dc10d039f593790a1fe9e0723769bfba07d5ccd9
/VKTS/src/layer0/processor/fn_processor_windows.cpp
900b0cf683c3f308726e05b692b7069d5983bdda
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-happy-bunny", "LicenseRef-scancode-khronos", "BSD-3-Clause", "Apache-2.0" ]
permissive
YoutaVen/Vulkan
5a38ebc694355631f50ebbeee092c959ecf99817
b19dca5388491257c74f18f3b271355be5ff55fa
refs/heads/master
2020-04-05T18:29:35.317945
2016-04-10T15:04:08
2016-04-10T15:04:08
55,913,171
9
0
null
2016-04-10T17:35:04
2016-04-10T17:35:03
null
UTF-8
C++
false
false
1,589
cpp
/** * VKTS - VulKan ToolS. * * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * 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 <vkts/vkts.hpp> #include <windows.h> namespace vkts { VkBool32 VKTS_APIENTRY _processorInit() { // Nothing for now. return VK_TRUE; } uint32_t VKTS_APIENTRY _processorGetNumber() { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); return static_cast<uint32_t>(systemInfo.dwNumberOfProcessors); } void VKTS_APIENTRY _processorTerminate() { // Nothing for now. } }
[ "norbert@nopper.tv" ]
norbert@nopper.tv
9428e9c32607aa4dd5748445bf1bd4b8ac64c066
c2160adb22366c916f2f4f6c82b43a63befc7cbb
/src/rpcnet.cpp
49e4a942fa11691719f8628fa88783e21e2da489
[ "MIT" ]
permissive
musterdam/PWRcoin
34b674bff15fd8ae082d0f0ebdaa503379ef94db
50f6c6c253b8409a05ad06d048d2964d222c686d
refs/heads/master
2020-03-19T13:21:38.852908
2018-05-31T02:25:27
2018-05-31T02:25:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,638
cpp
// Copyright (c) 2009-2012 Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "net.h" #include "pwrcoinrpc.h" #include "alert.h" #include "wallet.h" #include "db.h" #include "walletdb.h" using namespace json_spirit; using namespace std; Value getconnectioncount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "Returns the number of connections to other nodes."); LOCK(cs_vNodes); return (int)vNodes.size(); } static void CopyNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); BOOST_FOREACH(CNode* pnode, vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); } } Value getpeerinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "Returns data about each connected network node."); vector<CNodeStats> vstats; CopyNodeStats(vstats); Array ret; BOOST_FOREACH(const CNodeStats& stats, vstats) { Object obj; obj.push_back(Pair("addr", stats.addrName)); obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices))); obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); obj.push_back(Pair("version", stats.nVersion)); obj.push_back(Pair("subver", stats.strSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); obj.push_back(Pair("banscore", stats.nMisbehavior)); ret.push_back(obj); } return ret; } // pwrcoin: send alert. // There is a known deadlock situation with ThreadMessageHandler // ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages() // ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage() Value sendalert(const Array& params, bool fHelp) { if (fHelp || params.size() < 6) throw runtime_error( "sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n" "<message> is the alert text message\n" "<privatekey> is hex string of alert master private key\n" "<minver> is the minimum applicable internal client version\n" "<maxver> is the maximum applicable internal client version\n" "<priority> is integer priority number\n" "<id> is the alert id\n" "[cancelupto] cancels all alert id's up to this number\n" "Returns true or false."); CAlert alert; CKey key; alert.strStatusBar = params[0].get_str(); alert.nMinVer = params[2].get_int(); alert.nMaxVer = params[3].get_int(); alert.nPriority = params[4].get_int(); alert.nID = params[5].get_int(); if (params.size() > 6) alert.nCancel = params[6].get_int(); alert.nVersion = PROTOCOL_VERSION; alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60; alert.nExpiration = GetAdjustedTime() + 365*24*60*60; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedAlert)alert; alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end()); vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str()); key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) throw runtime_error( "Unable to sign alert, check private key?\n"); if(!alert.ProcessAlert()) throw runtime_error( "Failed to process alert.\n"); // Relay alert { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } Object result; result.push_back(Pair("strStatusBar", alert.strStatusBar)); result.push_back(Pair("nVersion", alert.nVersion)); result.push_back(Pair("nMinVer", alert.nMinVer)); result.push_back(Pair("nMaxVer", alert.nMaxVer)); result.push_back(Pair("nPriority", alert.nPriority)); result.push_back(Pair("nID", alert.nID)); if (alert.nCancel > 0) result.push_back(Pair("nCancel", alert.nCancel)); return result; }
[ "dev@pwr-coin.com" ]
dev@pwr-coin.com
3f77b9ac33e667eea7348a4003fd33137190ee74
584ad23a7dffe39d6657a8a18d542d261a7d4c8a
/Home Budget/VariableModification.h
754c319b27d5d6ca8cc7571e831cc06e4da56e23
[ "Unlicense" ]
permissive
Jakub-Raciborski/C_Training
2487ca9eeebfd48ffe3ee7a4bac507cad02bceca
96aa52b315edac7da77c840dbed6c9155bda7db5
refs/heads/main
2023-07-11T12:01:16.697922
2021-07-29T19:45:44
2021-07-29T19:45:44
359,140,061
1
0
null
null
null
null
UTF-8
C++
false
false
446
h
#ifndef VARIABLEMODIFICATION_H #define VARIABLEMODIFICATION_H #include <iostream> #include "StringMethods.h" using namespace std; class VariableModification{ public: static int convertStringToInt(string wordToConvert); static string convertIntToString(int numberToConvert); static float convertStringToFloat(string wordToConvert); static string convertFloatToString(float numberToConvert); }; #endif // VARIABLEMODIFICATION_H
[ "raciborski.programista@gmail.com" ]
raciborski.programista@gmail.com