blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
5d31765093ac91d1aab9393ac88016ad20c19e44
6c2c2721f57b54a3f56521985ce80d594031760c
/Assignment6/parallelogram.cpp
5ac9648f7d9b7d6d472200495954141b4046326f
[]
no_license
dogaoz/CSCI-15
dd698437372759bfb64555f254b9714266c925d9
898f8d6b23a193ecb169dd150bea3bbe9bbb179d
refs/heads/master
2020-04-17T13:49:22.208316
2019-01-20T06:40:43
2019-01-20T06:40:43
166,631,704
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
cpp
// // parallelogram.cpp // // Doga Ozkaracaabatlioglu // Nov 11, 2018 // Parallelogram Class method definitions // #include "helper_functions.h" #include "parallelogram.h" Parallelogram::Parallelogram() { setDefault(); } void Parallelogram::setDefault() { pointA.setAll(0,0); pointB.setAll(3,2); pointC.setAll(3,5); pointD.setAll(0,3); } Parallelogram::Parallelogram(Point &a, Point &b, Point &c, Point &d) { setAll(a,b,c,d); } void Parallelogram::validate() { // FLOATING POING TYPES IN C++ ARE APPROXIMATIONS, NOT EXACT VALUES. // WRITE AN EQUALS() FUNCTION THAT TAKES 2 DOUBLES AND RETURNS TRUE IF // THEY ARE CLOSE ENOUGH TO THE SAME VALUE, I.E. WITHIN 10^-9 OF EACH OTHER // |AB| and |DC| is parallel (top and bottom) // and |AD| and |BC| (left and right side) if (Equals(pointA.getY(),pointB.getY()) && Equals(pointC.getY(),pointD.getY()) && Equals(pointA.getX(),pointD.getX()) && Equals(pointB.getX(), pointC.getX()) ) { cout << "@@ PARALLELOGRAM VALIDATED" << endl; } else { cout << "@@ ERROR WHILE VALIDATING PARALLELOGRAM" << endl; cout << "+PA+ Erroneous shape coordinates given below: " << endl; Parallelogram::print(cout); cout << endl << "+PA+ Setting and printing default coordinates" << endl; Parallelogram::setDefault(); Parallelogram::print(cout); cout << "+PA+ Done." << endl << endl; } } double Parallelogram::Perimeter() { return Trapezoid::Perimeter(); } double Parallelogram::Area() { return pointA.distance(pointB) * pointB.distance(pointC); } void Parallelogram::print(ostream &out) { out << "This is a Parallelogram" << endl; Trapezoid::print(out); } void Parallelogram::read(istream &in) { Trapezoid::read(in); validate(); } istream &operator >> (istream &in, Parallelogram &t) { t.read(in); return in; } ostream &operator << (ostream &out, Parallelogram &t) { t.print(out); return out; }
[ "doga.ozkaraca@gmail.com" ]
doga.ozkaraca@gmail.com
e3c86bb4fe5c98a23ac1d8342c19fbf60995a2f8
90b1833d8238d76d073786147de6d2d96a941378
/SGP_Honor/Source/Frame.cpp
dc96bbb62919d9cfd5f2dd6c087f0adb00f86824
[]
no_license
nessj1994/Honor
28e5c20864b3d8201852ab8fb48ff9a1b2439c32
00c965c6dd506918ea1b7ffc5955f017396c9651
refs/heads/master
2021-03-19T06:49:31.613801
2014-11-19T18:33:59
2014-11-19T18:33:59
26,241,134
1
0
null
null
null
null
UTF-8
C++
false
false
62
cpp
#include "Frame.h" Frame::Frame() { } Frame::~Frame() { }
[ "msciortino17@gmail.com" ]
msciortino17@gmail.com
8ac4cde5d940e6345b37ebeef7e80c4582bf0125
ace20ae898aadf18c4ef8a2355b528422fc27bb5
/codeforces/diceinline.cpp
bff677b7cfffc68a06cf2c289b29d1269396f5ed
[]
no_license
pidddgy/competitive-programming
19fd79e7888789c68bf93afa3e63812587cbb0fe
ec86287a0a70f7f43a13cbe26f5aa9c5b02f66cc
refs/heads/master
2022-01-28T07:01:07.376581
2022-01-17T21:37:06
2022-01-17T21:37:06
139,354,420
0
3
null
2021-04-06T16:56:29
2018-07-01T19:03:53
C++
UTF-8
C++
false
false
814
cpp
// https://atcoder.jp/contests/abc154/tasks/abc154_d #include <bits/stdc++.h> #define watch(x) cerr << (#x) << " is " << (x) << endl; #define ld long double using namespace std; int main() { int N, K; cin >> N >> K; int a[N+1]; for(int i = 1; i <= N; i++) { cin >> a[i]; } int psa[N+1]; psa[0] = 0; for(int i = 1; i <= N; i++) { psa[i] = a[i] + psa[i-1]; } int bestind = -1; int ma = 0; for(int i = K; i <= N; i++) { if(psa[i] - psa[i-K] > ma) { bestind = i-K+1; ma = psa[i] - psa[i-K]; } } watch(bestind) ld ev = 0; for(int i = bestind; i <= bestind+K-1; i++) { ld x = a[i]; ev += (((x+1)*x)/2) * (1/x); } cout << fixed << setprecision(7) << ev << endl; }
[ "marcus.jn.chong@gmail.com" ]
marcus.jn.chong@gmail.com
f9dfd35e87aee8b2d9d3c3281a22a77bd841a19c
da404c28a9715faefc60b8207fd5a80ee7bae1a0
/CSC8503Common/Player.cpp
99f6858e171920f15ed3a2028c1693417cd62abe
[]
no_license
B5036535/CSC8503
11ea4cf959d733413b904ca1ca7e43f82c7538fc
387e591a09669bf573a8096f64639fa60e51f1a7
refs/heads/main
2023-03-23T23:06:50.761503
2021-03-10T21:38:59
2021-03-10T21:38:59
346,449,831
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
cpp
#include "Player.h" #include "AABBVolume.h" #include "CapsuleVolume.h" #include "../CSC8503Common/PlayerStateRunning.h" using namespace NCL; using namespace CSC8503; Player::Player(Vector3 pos) { tag = GameObjectTag::PLAYER; canJump = true; speed = 1000.0f; jump = 1000.0f; float meshSize = 3.0f; float inverseMass = 0.6f; AABBVolume* volume = new AABBVolume(Vector3(0.3f, 0.85f, 0.3f) * meshSize); //CapsuleVolume* volume = new CapsuleVolume(0.8f, 0.3f); SetBoundingVolume((CollisionVolume*)volume); GetTransform().SetScale(Vector3(meshSize, meshSize, meshSize)).SetPosition(pos).SetOrientation(Matrix4::Rotation(180,Vector3(0, 1, 0))); SetPhysicsObject(new PhysicsObject(&GetTransform(), GetBoundingVolume())); GetPhysicsObject()->SetInverseMass(inverseMass); GetPhysicsObject()->InitSphereInertia(); movementMachine = new PushdownMachine(new PlayerStateRunning(this, speed, jump)); spawnPoint = transform.GetPosition(); timer = new Timer(); } Player::~Player() { //Machine deleted at StateSystem //delete movementMachine; delete timer; } void Player::OnCollisionBegin(GameObject* otherObject) { if (otherObject->GetObjectTag() == GameObjectTag::FLOOR) canJump = true; if (otherObject->GetObjectTag() == GameObjectTag::POWERUP) timer->PowerUp(); }
[ "j.ashman@newcastle.ac.uk" ]
j.ashman@newcastle.ac.uk
e0c767cceab3dc58efd4f55f7f6678c97da9b1f8
b843d693bc2e8802b279814fc3d596abd6c86cd8
/CatalogRobot/form.h
e1cc71d0cbbe35d74b925728f42532edc43ebee5
[]
no_license
pomid0rko0/CatalogRobot
856108b0e56cee1ba7625ffefa92a7135145d71c
acae88f57576c3381abea50ef58dd1b2c968e952
refs/heads/master
2020-06-01T05:53:41.189367
2019-10-15T13:23:29
2019-10-15T13:23:29
173,575,763
0
0
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef FORM_H #define FORM_H #include <QWidget> #include <QFileDialog> namespace Ui { class Form; } class Form : public QWidget { Q_OBJECT public: explicit Form(QWidget *parent = nullptr); ~Form(); private slots: void on_parser_search_button_clicked(); void on_start_button_clicked(); void on_pause_button_clicked(); private: Ui::Form *ui; }; #endif // FORM_H
[ "lev55i@ya.ru" ]
lev55i@ya.ru
503a2f0beda93d47a795ff0d12ea69d315d00e45
6e601105760f09d3c9f5306e18e4cf085f0bb4a2
/10000-99999/10838.cpp
68cecf63c95b5a25591d6da047f76a386ee6c496
[]
no_license
WSJI0/BOJ
6412f69fddd46c4bcc96377e2b6e013f3bb1b524
160d8c13f72d7da835d938686f433e7b245be682
refs/heads/master
2023-07-06T15:35:50.815021
2023-07-04T01:39:48
2023-07-04T01:39:48
199,650,520
2
0
null
2020-04-20T09:03:03
2019-07-30T12:48:37
Python
UTF-8
C++
false
false
200
cpp
#include <bits/stdc++.h> using namespace std; void paint(int a, int b, int c){ } int main(void){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k; cin>>n>>k; }
[ "lifedev@naver.com" ]
lifedev@naver.com
eb13fcbe60acbeda7c84deec95939b47748110c3
f15d6c870d51ffa4a7e6151c42ceb5de0eedf46a
/Vaango/src/CCA/Components/Models/FluidsBased/TableInterface.h
e23e7dcf6da0dcc7abce7da68cbe2240c587d5be
[]
no_license
pinebai/ParSim
1a5ee3687bd1582f31be9dbd88b3914769549095
f787523ae6c47c87ff1a74e199c7068ca45dc780
refs/heads/master
2021-01-24T07:45:12.923015
2017-04-22T04:34:44
2017-04-22T04:34:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,524
h
/* * The MIT License * * Copyright (c) 2013-2014 Callaghan Innovation, New Zealand * * 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. */ /* * The MIT License * * Copyright (c) 1997-2012 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef Uintah_TableInterface_h #define Uintah_TableInterface_h #include <Core/Grid/Variables/CCVariable.h> namespace Uintah { /**************************************** CLASS TableInterface Short description... GENERAL INFORMATION TableInterface.h Steven G. Parker Department of Computer Science University of Utah Center for the Simulation of Accidental Fires and Explosions (C-SAFE) KEYWORDS TableInterface DESCRIPTION Long description... WARNING ****************************************/ class TableInterface { public: TableInterface(); virtual ~TableInterface(); virtual void outputProblemSpec(ProblemSpecP& ps) = 0; virtual void addIndependentVariable(const string&) = 0; virtual int addDependentVariable(const string&) = 0; virtual void setup(const bool cerrSwitch) = 0; virtual void interpolate(int index, CCVariable<double>& result, const CellIterator&, vector<constCCVariable<double> >& independents) = 0; virtual double interpolate(int index, vector<double>& independents) = 0; private: }; } // End namespace Uintah #endif
[ "b.banerjee.nz@gmail.com" ]
b.banerjee.nz@gmail.com
68fde0ff8f7eb6fab07c8e36c9220b739ab15042
8621b712f6468fb110552f130bd085d3ea722842
/gui/Source/View/LinkComponent.h
213354f317a3904006131a579c711327ed5e2384
[]
no_license
imclab/SaM-Designer
f9a7b36a857c7fab8f81a8cedf20acf9874e06f9
fa04d0192b2dcda50002bd492efb11118fc4a36b
refs/heads/master
2021-01-18T09:21:57.778696
2014-06-13T22:59:34
2014-06-13T22:59:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,177
h
/* ============================================================================== LinkComponent.h Created: 21 Aug 2012 11:23:02am Author: Peter Vasil ============================================================================== This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LINKCOMPONENT_H_4CCE4B86__ #define __LINKCOMPONENT_H_4CCE4B86__ namespace synthamodeler { class SelectableObject; class BaseObjectComponent; class ObjController; class ObjectComponent; class LinkComponent : public BaseObjectComponent, public ChangeListener, public SettableTooltipClient, public SelectableObject { public: LinkComponent(ObjController& owner_, ValueTree linkTree); ~LinkComponent(); void resized(); void paint(Graphics& g); void update(); void mouseDown(const MouseEvent& e); void mouseDrag(const MouseEvent& e); void mouseUp(const MouseEvent& e); bool hitTest(int x, int y); void resizeToFit(); void setSelected(bool shouldBeSelected); void getPoints (float& x1, float& y1, float& x2, float& y2) const; void changeListenerCallback (ChangeBroadcaster*); bool sameStartEnd(ValueTree linkTree); void reverseDirection(); Rectangle<int> getIntersectioBounds(); Point<int> getPinPos(); void setSegmented(bool isSegmented) { segmented = isSegmented; resized(); } private: void drawPath(Graphics& g); float lastInputX, lastInputY, lastOutputX, lastOutputY; float curInputX, curInputY, curOutputX, curOutputY; Path linePath, hitPath, iconPath; bool segmented; bool mouseDownSelectStatus; Point<float> iconPos; int iconWidth; int iconHeight; WeakReference<ObjectComponent> startComp; WeakReference<ObjectComponent> endComp; Colour color; Colour colorSelected; Colour currentColor; void getDistancesFromEnds (int x, int y, double& distanceFromStart, double& distanceFromEnd) const { float x1, y1, x2, y2; getPoints (x1, y1, x2, y2); distanceFromStart = juce_hypot (x - (x1 - getX()), y - (y1 - getY())); distanceFromEnd = juce_hypot (x - (x2 - getX()), y - (y2 - getY())); } WeakReference<LinkComponent>::Master masterReference; friend class WeakReference<LinkComponent>; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinkComponent); }; } #endif // __LINKCOMPONENT_H_4CCE4B86__
[ "mail@petervasil.net" ]
mail@petervasil.net
4107e907c726805c6e74eb665dd035d4162f299b
2aed63d9aa027419b797e56b508417789a604a8b
/Injector5degTetra/InjectorFoam/constant/turbulenceProperties
339721897e5d55e55fa8b994b38032f45e2a9693
[]
no_license
icl-rocketry/injectorCFDModelling
70137f1c6574240c7202638c3713102a3e1e9fd8
96591cf2cf3cd4cbd64536d8ae47ed8080ed9016
refs/heads/main
2023-08-25T03:30:59.244137
2021-10-09T21:04:45
2021-10-09T21:04:45
322,369,673
3
5
null
null
null
null
UTF-8
C++
false
false
891
/*--------------------------------*- C++ -*----------------------------------* \ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object turbulenceProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // simulationType laminar; // ************************************************************************* //
[ "39316550+lucpaoli@users.noreply.github.com" ]
39316550+lucpaoli@users.noreply.github.com
ff6b50450a76c1d044da02f898374915daa1c57a
81872dd652810456d2ffbeda4e544fc11c250c5a
/49_StringToInt.cpp
123be83c80d7a56973ba00542ad9b9752164dbf0
[ "Apache-2.0" ]
permissive
Yeolar/AlgorithmExercises
2cd5ab754b58452d3104f37a5a53f58b73e29941
09894c9e2638fb57b7b4de752468256fd84126eb
refs/heads/master
2021-01-02T08:34:50.971110
2017-08-15T15:14:25
2017-08-15T15:14:25
99,020,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,711
cpp
/* * Copyright (C) 2017, Yeolar */ #include <stdexcept> #include <gtest/gtest.h> namespace ae { int strToInt(const char* str) { if (str == nullptr || *str == '\0') { throw std::invalid_argument("Empty string"); } bool negative = false; if (*str == '+') { str++; } else if (*str == '-') { str++; negative = true; } if (*str == '\0') { throw std::invalid_argument("Invalid string"); } long long num = 0; while (*str != '\0') { if (*str >= '0' && *str <= '9') { num = num * 10 + *str - '0'; if ((num > 0x7FFFFFFF && !negative) || (num > 0x80000000 && negative)) { throw std::overflow_error("Too long string"); } str++; } else { throw std::invalid_argument("Invalid string"); } } return negative ? -num : num; } } // namespace ae TEST(strToInt, all) { EXPECT_THROW(ae::strToInt(nullptr), std::invalid_argument); EXPECT_THROW(ae::strToInt(""), std::invalid_argument); EXPECT_EQ(ae::strToInt("123"), 123); EXPECT_EQ(ae::strToInt("+123"), 123); EXPECT_EQ(ae::strToInt("-123"), -123); EXPECT_THROW(ae::strToInt("1a33"), std::invalid_argument); EXPECT_EQ(ae::strToInt("+0"), 0); EXPECT_EQ(ae::strToInt("-0"), 0); EXPECT_EQ(ae::strToInt("+2147483647"), 2147483647); EXPECT_EQ(ae::strToInt("-2147483647"), -2147483647); EXPECT_THROW(ae::strToInt("+2147483648"), std::overflow_error); EXPECT_EQ(ae::strToInt("-2147483648"), -2147483648); EXPECT_THROW(ae::strToInt("+2147483649"), std::overflow_error); EXPECT_THROW(ae::strToInt("-2147483649"), std::overflow_error); EXPECT_THROW(ae::strToInt("+"), std::invalid_argument); EXPECT_THROW(ae::strToInt("-"), std::invalid_argument); }
[ "yeolar@gmail.com" ]
yeolar@gmail.com
56568fb686f619b31069ef7b2b2480ef2924933d
2f6a9ff787b9eb2ababc9bb39e15f1349fefa3d2
/inet/src/inet/visualizer/physicallayer/PhysicalLinkCanvasVisualizer.cc
fe83f238cd8c852ee9f8aa7b884861e44578af2c
[ "BSD-3-Clause", "MPL-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
ntanetani/quisp
97f9c2d0a8d3affbc709452e98c02c568f5fe8fd
47501a9e9adbd6adfb05a1c98624870b004799ea
refs/heads/master
2023-03-10T08:05:30.044698
2022-06-14T17:29:28
2022-06-14T17:29:28
247,196,429
0
1
BSD-3-Clause
2023-02-27T03:27:22
2020-03-14T02:16:19
C++
UTF-8
C++
false
false
1,864
cc
// // Copyright (C) OpenSim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/physicallayer/contract/packetlevel/IRadio.h" #include "inet/visualizer/physicallayer/PhysicalLinkCanvasVisualizer.h" namespace inet { namespace visualizer { Define_Module(PhysicalLinkCanvasVisualizer); bool PhysicalLinkCanvasVisualizer::isLinkStart(cModule *module) const { return dynamic_cast<inet::physicallayer::IRadio *>(module) != nullptr; } bool PhysicalLinkCanvasVisualizer::isLinkEnd(cModule *module) const { return dynamic_cast<inet::physicallayer::IRadio *>(module) != nullptr; } const LinkVisualizerBase::LinkVisualization *PhysicalLinkCanvasVisualizer::createLinkVisualization(cModule *source, cModule *destination, cPacket *packet) const { auto linkVisualization = static_cast<const LinkCanvasVisualization *>(LinkCanvasVisualizerBase::createLinkVisualization(source, destination, packet)); linkVisualization->figure->setTags((std::string("physical_link ") + tags).c_str()); linkVisualization->figure->setTooltip("This arrow represents a physical link between two network nodes"); linkVisualization->shiftPriority = 1; return linkVisualization; } } // namespace visualizer } // namespace inet
[ "n.tanetani@gmail.com" ]
n.tanetani@gmail.com
9520976ba2845d9770057d1ccbf383ae8c10ba1f
d40efadec5724c236f1ec681ac811466fcf848d8
/branches/fs2_open_3_6_16/code/hud/hudtarget.cpp
a492303f5f824d3e16032e7344c95cd3502abe6d
[]
no_license
svn2github/fs2open
0fcbe9345fb54d2abbe45e61ef44a41fa7e02e15
c6d35120e8372c2c74270c85a9e7d88709086278
refs/heads/master
2020-05-17T17:37:03.969697
2015-01-08T15:24:21
2015-01-08T15:24:21
14,258,345
0
0
null
null
null
null
UTF-8
C++
false
false
208,041
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #include "hud/hud.h" #include "hud/hudparse.h" #include "hud/hudartillery.h" #include "hud/hudlock.h" #include "hud/hudmessage.h" #include "hud/hudtarget.h" #include "hud/hudreticle.h" #include "hud/hudbrackets.h" #include "object/object.h" #include "ship/ship.h" #include "render/3dinternal.h" #include "globalincs/linklist.h" #include "weapon/weapon.h" #include "playerman/player.h" #include "freespace2/freespace.h" // for flFrametime #include "io/timer.h" #include "gamesnd/gamesnd.h" #include "debris/debris.h" #include "mission/missionmessage.h" #include "hud/hudtargetbox.h" #include "ship/subsysdamage.h" #include "hud/hudshield.h" #include "mission/missionhotkey.h" #include "asteroid/asteroid.h" #include "jumpnode/jumpnode.h" #include "weapon/emp.h" #include "globalincs/alphacolors.h" #include "localization/localize.h" #include "ship/awacs.h" #include "parse/parselo.h" #include "cmdline/cmdline.h" #include "iff_defs/iff_defs.h" #include "network/multi.h" #include "graphics/font.h" #include "network/multiutil.h" #include "model/model.h" // If any of these bits in the ship->flags are set, ignore this ship when targeting int TARGET_SHIP_IGNORE_FLAGS = (SF_EXPLODED|SF_DEPART_WARP|SF_DYING|SF_ARRIVING_STAGE_1|SF_HIDDEN_FROM_SENSORS); // Global values for the target bracket width and height, used for debugging int Hud_target_w, Hud_target_h; // offscreen triangle that point the the off-screen target float Offscreen_tri_base[GR_NUM_RESOLUTIONS] = { 6.0f, 9.5f }; float Offscreen_tri_height[GR_NUM_RESOLUTIONS] = { 7.0f, 11.0f }; float Max_offscreen_tri_seperation[GR_NUM_RESOLUTIONS] = { 10.0f, 16.0f }; float Max_front_seperation[GR_NUM_RESOLUTIONS] = { 10.0f, 16.0f }; SCP_vector<target_display_info> target_display_list; // The following variables are global to this file, and do not need to be persistent from frame-to-frame // This means the variables are not player-specific object* hostile_obj = NULL; static int ballistic_hud_index = 0; // Goober5000 extern object obj_used_list; // dummy node in linked list of active objects extern char *Cargo_names[]; // shader is used to shade the target box shader Training_msg_glass; // the target triangle (that orbits the reticle) dimensions float Target_triangle_base[GR_NUM_RESOLUTIONS] = { 6.0f, 9.5f }; float Target_triangle_height[GR_NUM_RESOLUTIONS] = { 7.0f, 11.0f }; // stuff for hotkey targeting lists htarget_list htarget_items[MAX_HOTKEY_TARGET_ITEMS]; htarget_list htarget_free_list; /* // coordinates and widths used to render the HUD afterburner energy gauge int current_hud->Aburn_coords[GR_NUM_RESOLUTIONS][4] = { { // GR_640 171, 265, 60, 60 }, { // GR_1024 274, 424, 86, 96 } }; // coordinates and widths used to render the HUD weapons energy gauge int current_hud->Wenergy_coords[GR_NUM_RESOLUTIONS][4] = { { // GR_640 416, 265, 60, 60 }, { // GR_1024 666, 424, 86, 96 } };*/ #define MIN_DISTANCE_TO_CONSIDER_THREAT 1500 // min distance to show hostile warning triangle ////////////////////////////////////////////////////////////////////////// // lists for target in reticle cycling ////////////////////////////////////////////////////////////////////////// #define RL_USED (1<<0) #define RL_USE_DOT (1<<1) // use dot product result, not distance typedef struct _reticle_list { _reticle_list *next, *prev; object *objp; float dist, dot; int flags; } reticle_list; #define RESET_TARGET_IN_RETICLE 750 int Reticle_save_timestamp; reticle_list Reticle_cur_list; reticle_list Reticle_save_list; #define MAX_RETICLE_TARGETS 50 reticle_list Reticle_list[MAX_RETICLE_TARGETS]; ////////////////////////////////////////////////////////////////////////// // used for closest target cycling ////////////////////////////////////////////////////////////////////////// #define TL_RESET 1500 #define TURRET_RESET 1000 static int Tl_hostile_reset_timestamp; static int Tl_friendly_reset_timestamp; static int Target_next_uninspected_object_timestamp; static int Target_newest_ship_timestamp; static int Target_next_turret_timestamp; // animation frames for the hud targeting gauges // frames: 0 => out of range lead // 1 => in range lead float Lead_indicator_half[NUM_HUD_RETICLE_STYLES][GR_NUM_RESOLUTIONS][2] = { { { // GR_640 12.5f, // half-width 12.5f // half-height }, { // GR_1024 20.0f, // half-width 20.0f // half-height } }, { { // GR_640 8.0f, // half-width 8.0f // half-height }, { // GR_1024 13.0f, // half-width 13.0f // half-height } } }; hud_frames Lead_indicator_gauge; int Lead_indicator_gauge_loaded = 0; char Lead_fname[NUM_HUD_RETICLE_STYLES][GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { { "lead1_fs1", "2_lead1_fs1" }, { "lead1", "2_lead1" } }; // animation frames for the countermeasures gauge // frames: 0 => background hud_frames Cmeasure_gauge; int Cmeasure_gauge_loaded = 0; int Cm_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 497, 343 }, { // GR_1024 880, 602 } }; int Cm_text_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 533, 347 }, { // GR_1024 916, 606 } }; int Cm_text_val_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 506, 347 }, { // GR_1024 889, 606 } }; char Cm_fname[GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { "countermeasure1", "countermeasure1" }; #define TOGGLE_TEXT_AUTOT 0 #define TOGGLE_TEXT_TARGET 1 #define TOGGLE_TEXT_AUTOS 2 #define TOGGLE_TEXT_SPEED 3 int Toggle_text_alpha = 255; // animation files for the weapons gauge #define NUM_WEAPON_GAUGES 5 hud_frames Weapon_gauges[NUM_HUD_SETTINGS][NUM_WEAPON_GAUGES]; hud_frames New_weapon; int Weapon_gauges_loaded = 0; // for primaries int Weapon_gauge_primary_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][3][2] = { { // normal HUD { // GR_640 // based on the # of primaries {509, 273}, // top of weapon gauge, first frame, always {497, 293}, // for the first primary {497, 305} // for the second primary }, { // GR_1024 // based on the # of primaries {892, 525}, // top of weapon gauge, first frame, always {880, 545}, // for the first primary {880, 557} // for the second primary } }, { // ballistic HUD - slightly different alignment { // GR_640 // based on the # of primaries {485, 273}, // top of weapon gauge, first frame, always {485, 293}, // for the first primary {485, 305} // for the second primary }, { // GR_1024 // based on the # of primaries {868, 525}, // top of weapon gauge, first frame, always {868, 545}, // for the first primary {868, 557} // for the second primary } } }; int Weapon_gauge_secondary_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][5][2] = { { // normal HUD { // GR_640 // based on the # of secondaries {497, 318}, // bottom of gauge, 0 secondaries {497, 318}, // bottom of gauge, 1 secondaries {497, 317}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {497, 326}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {497, 335} // bottom of gauge, 3 secondaries }, { // GR_1024 // based on the # of secondaries {880, 570}, // bottom of gauge, 0 secondaries {880, 570}, // bottom of gauge, 1 secondaries {880, 569}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {880, 578}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {880, 587} // bottom of gauge, 3 secondaries } }, { // ballistic HUD - slightly different alignment { // GR_640 // based on the # of secondaries {485, 318}, // bottom of gauge, 0 secondaries {485, 318}, // bottom of gauge, 1 secondaries {485, 317}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {485, 326}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {485, 335} // bottom of gauge, 3 secondaries }, { // GR_1024 // based on the # of secondaries {868, 570}, // bottom of gauge, 0 secondaries {868, 570}, // bottom of gauge, 1 secondaries {868, 569}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {868, 578}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {868, 587} // bottom of gauge, 3 secondaries } } }; int Weapon_title_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][2] = { { // normal HUD { // GR_640 518, 274 }, { // GR_1024 901, 527 } }, { // ballistic HUD - slightly different alignment { // GR_640 487, 274 }, { // GR_1024 870, 527 } } }; int Weapon_plink_coords[GR_NUM_RESOLUTIONS][2][2] = { { // GR_640 {530, 285}, // fire-linked thingie, for the first primary {530, 295} // fire-linked thingie, for the second primary }, { // GR_1024 {913, 537}, // fire-linked thingie, for the first primary {913, 547} // fire-linked thingie, for the second primary } }; int Weapon_pname_coords[GR_NUM_RESOLUTIONS][2][2] = { { // GR_640 {536, 285}, // weapon name, first primary {536, 295} // weapon name, second primary }, { // GR_1024 {919, 537}, // weapon name, first primary {919, 547} // weapon name, second primary } }; int Weapon_slinked_x[GR_NUM_RESOLUTIONS] = { 525, // where to draw the second thingie if this weapon is fire-linked 908 }; int Weapon_sunlinked_x[GR_NUM_RESOLUTIONS] = { 530, // where to draw the first thingie if this weapon is selected at all (fire-linked or not) 913 }; int Weapon_secondary_y[GR_NUM_RESOLUTIONS][3] = { { // GR_640 309, // y location of where to draw text for the first secondary 318, // y location of where to draw text for the second secondary 327 // y location of where to draw text for the third secondary }, { // GR_1024 561, // y location of where to draw text for the third secondary 570, // y location of where to draw text for the third secondary 579 // y location of where to draw text for the third secondary } }; int Weapon_primary_y[GR_NUM_RESOLUTIONS][2] = { { // GR_640 285, // y location of where to draw text for the first primary 295 // y location of where to draw text for the second primary }, { // GR_1024 537, // y location of where to draw text for the first primary 547 // y location of where to draw text for the second primary } }; int Weapon_secondary_name_x[GR_NUM_RESOLUTIONS] = { 536, // x location of where to draw weapon name 919 }; int Weapon_secondary_ammo_x[GR_NUM_RESOLUTIONS] = { 525, // x location of where to draw weapon ammo count 908 }; int Weapon_primary_ammo_x[GR_NUM_RESOLUTIONS] = { 525, // x location of where to draw primary weapon ammo count 908 }; int Weapon_secondary_reload_x[GR_NUM_RESOLUTIONS] = { 615, // x location of where to draw the weapon reload time 998 }; char *Weapon_gauge_fnames[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][NUM_WEAPON_GAUGES] = { //XSTR:OFF { // normal HUD { // GR_640 "weapons1", "weapons2", "weapons3", "weapons4", "weapons5" }, { // GR_1024 "weapons1", "weapons2", "weapons3", "weapons4", "weapons5" } }, { // ballistic HUD - slightly different alignment { // GR_640 "weapons1_b", "weapons2_b", "weapons3_b", "weapons4_b", "weapons5_b" }, { // GR_1024 "weapons1_b", "weapons2_b", "weapons3_b", "weapons4_b", "weapons5_b" } } //XSTR:ON }; // Flash the line for a weapon. This normally occurs when the player tries to fire that // weapon, but the firing fails (due to lack of energy or damaged weapons subsystem). #define MAX_WEAPON_FLASH_LINES 7 // 3 primary and 4 secondary typedef struct weapon_flash { int flash_duration[MAX_WEAPON_FLASH_LINES]; int flash_next[MAX_WEAPON_FLASH_LINES]; int is_bright; } weapon_flash; weapon_flash Weapon_flash_info; // Data used for the proximity warning typedef struct homing_beep_info { int snd_handle; // sound handle for last played beep fix last_time_played; // time beep was last played int min_cycle_time; // time (in ms) for fastest cycling of the sound int max_cycle_time; // time (in ms) for slowest cycling of the sound float min_cycle_dist; // distance at which fastest cycling occurs float max_cycle_dist; // distance at which slowest cycling occurs float precalced_interp; // a precalculated value used in a linear interpretation } homing_beep_info; homing_beep_info Homing_beep = { -1, 0, 150, 1000, 30.0f, 1500.0f, 1.729412f }; // Set at the start of a mission, used to decide how to draw the separation for the warning missile indicators float Min_warning_missile_dist; float Max_warning_missile_dist; void hud_maybe_flash_weapon(int index); // if a given object should be ignored because of AWACS effects int hud_target_invalid_awacs(object *objp) { // if objp is ship object, first check if can be targeted with team info if (objp->type == OBJ_SHIP) { if (Player_ship != NULL) { if (ship_is_visible_by_team(objp, Player_ship)) { return 0; } } } // check for invalid status if((Player_ship != NULL) && (awacs_get_level(objp, Player_ship) < 1.0f)){ return 1; } // valid return 0; } ship_subsys *advance_subsys(ship_subsys *cur, int next_flag) { if (next_flag) { return GET_NEXT(cur); } else { return GET_LAST(cur); } } // select a sorted turret subsystem on a ship if no other subsys has been selected void hud_maybe_set_sorted_turret_subsys(ship *shipp) { Assert((Player_ai->target_objnum >= 0) && (Player_ai->target_objnum < MAX_OBJECTS)); if (!((Player_ai->target_objnum >= 0) && (Player_ai->target_objnum < MAX_OBJECTS))) { return; } Assert(Objects[Player_ai->target_objnum].type == OBJ_SHIP); if (Objects[Player_ai->target_objnum].type != OBJ_SHIP) { return; } if (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) { if (shipp->last_targeted_subobject[Player_num] == NULL) { hud_target_live_turret(1, 1); } } } // ----------------------------------------------------------------------- // clear out the linked list of targets in the reticle void hud_reticle_clear_list(reticle_list *rlist) { reticle_list *cur; for ( cur = GET_FIRST(rlist); cur != END_OF_LIST(rlist); cur = GET_NEXT(cur) ) { cur->flags = 0; } list_init(rlist); } // -------------------------------------------------------------------------------------- // hud_reticle_list_init() void hud_reticle_list_init() { int i; for ( i = 0; i < MAX_RETICLE_TARGETS; i++ ) { Reticle_list[i].flags = 0; } Reticle_save_timestamp = 1; list_init(&Reticle_save_list); list_init(&Reticle_cur_list); } // -------------------------------------------------------------------------------------- // hud_check_reticle_list() // // void hud_check_reticle_list() { reticle_list *rl, *temp; // cull dying objects from reticle list rl = GET_FIRST(&Reticle_cur_list); while( rl !=END_OF_LIST(&Reticle_cur_list) ) { temp = GET_NEXT(rl); if ( rl->objp->flags & OF_SHOULD_BE_DEAD ) { list_remove( &Reticle_cur_list, rl ); rl->flags = 0; } rl = temp; } if ( timestamp_elapsed(Reticle_save_timestamp) ) { hud_reticle_clear_list(&Reticle_save_list); Reticle_save_timestamp = timestamp(RESET_TARGET_IN_RETICLE); } } // -------------------------------------------------------------------------------------- // hud_reticle_list_find_free() // // int hud_reticle_list_find_free() { int i; // find a free reticle_list element for ( i = 0; i < MAX_RETICLE_TARGETS; i++ ) { if ( !(Reticle_list[i].flags & RL_USED) ) { break; } } if ( i == MAX_RETICLE_TARGETS ) { // nprintf(("Warning","Warning ==> Ran out of reticle target elements...\n")); return -1; } return i; } // -------------------------------------------------------------------------------------- // hud_stuff_reticle_list() // // #define RETICLE_DEFAULT_DIST 100000.0f #define RETICLE_DEFAULT_DOT 1.0f void hud_stuff_reticle_list(reticle_list *rl, object *objp, float measure, int dot_flag) { if ( dot_flag ) { rl->dot = measure; rl->dist = RETICLE_DEFAULT_DIST; rl->flags |= RL_USE_DOT; } else { rl->dist = measure; rl->dot = RETICLE_DEFAULT_DOT; } rl->objp = objp; } // -------------------------------------------------------------------------------------- // hud_reticle_list_update() // // Update Reticle_cur_list with an object that lies in the reticle // // parmeters: objp => object pointer to target // measure => distance or dot product, depending on dot_flag // dot_flag => if 0, measure is distance, if 1 measure is dot // void hud_reticle_list_update(object *objp, float measure, int dot_flag) { reticle_list *rl, *new_rl; int i; SCP_list<CJumpNode>::iterator jnp; if (objp->type == OBJ_JUMP_NODE) { for (jnp = Jump_nodes.begin(); jnp != Jump_nodes.end(); ++jnp) { if( jnp->GetSCPObject() != objp ) continue; if( jnp->IsHidden() ) return; } } for ( rl = GET_FIRST(&Reticle_cur_list); rl != END_OF_LIST(&Reticle_cur_list); rl = GET_NEXT(rl) ) { if ( rl->objp == objp ) return; } i = hud_reticle_list_find_free(); if ( i == -1 ) return; new_rl = &Reticle_list[i]; new_rl->flags |= RL_USED; hud_stuff_reticle_list(new_rl, objp, measure, dot_flag); int was_inserted = 0; if ( EMPTY(&Reticle_cur_list) ) { list_insert(&Reticle_cur_list, new_rl); was_inserted = 1; } else { for ( rl = GET_FIRST(&Reticle_cur_list); rl != END_OF_LIST(&Reticle_cur_list); rl = GET_NEXT(rl) ) { if ( !dot_flag ) { // compare based on distance if ( measure < rl->dist ) { list_insert_before(rl, new_rl); was_inserted = 1; break; } } else { // compare based on dot if ( measure > rl->dot ) { list_insert_before(rl, new_rl); was_inserted = 1; break; } } } // end for } if ( !was_inserted ) { list_append(&Reticle_cur_list, new_rl); } } // -------------------------------------------------------------------------------------- // hud_reticle_pick_target() // // Pick a target from Reticle_cur_list, based on what is in Reticle_save_list // // object *hud_reticle_pick_target() { reticle_list *cur_rl, *save_rl, *new_rl; object *return_objp; int in_save_list, i; return_objp = NULL; // As a first step, see if both ships and debris are in the list. If so, cull the debris. int debris_in_list = 0; int ship_in_list = 0; for ( cur_rl = GET_FIRST(&Reticle_cur_list); cur_rl != END_OF_LIST(&Reticle_cur_list); cur_rl = GET_NEXT(cur_rl) ) { if ( (cur_rl->objp->type == OBJ_SHIP) || (cur_rl->objp->type == OBJ_JUMP_NODE) ) { ship_in_list = 1; continue; } if ( cur_rl->objp->type == OBJ_WEAPON ) { if ( Weapon_info[Weapons[cur_rl->objp->instance].weapon_info_index].subtype == WP_MISSILE ) { ship_in_list = 1; continue; } } if ( (cur_rl->objp->type == OBJ_DEBRIS) || (cur_rl->objp->type == OBJ_ASTEROID) ) { debris_in_list = 1; continue; } } if ( ship_in_list && debris_in_list ) { // cull debris reticle_list *rl, *next; rl = GET_FIRST(&Reticle_cur_list); while ( rl != &Reticle_cur_list ) { next = rl->next; if ( (rl->objp->type == OBJ_DEBRIS) || (rl->objp->type == OBJ_ASTEROID) ){ list_remove(&Reticle_cur_list,rl); rl->flags = 0; } rl = next; } } for ( cur_rl = GET_FIRST(&Reticle_cur_list); cur_rl != END_OF_LIST(&Reticle_cur_list); cur_rl = GET_NEXT(cur_rl) ) { in_save_list = 0; for ( save_rl = GET_FIRST(&Reticle_save_list); save_rl != END_OF_LIST(&Reticle_save_list); save_rl = GET_NEXT(save_rl) ) { if ( cur_rl->objp == save_rl->objp ) { in_save_list = 1; break; } } if ( !in_save_list ) { return_objp = cur_rl->objp; i = hud_reticle_list_find_free(); if ( i == -1 ) break; new_rl = &Reticle_list[i]; new_rl->flags |= RL_USED; if ( cur_rl->flags & RL_USE_DOT ) { hud_stuff_reticle_list(new_rl, cur_rl->objp, cur_rl->dot, 1); } else { hud_stuff_reticle_list(new_rl, cur_rl->objp, cur_rl->dist, 0); } list_append(&Reticle_save_list, new_rl); break; } } // end for if ( return_objp == NULL && !EMPTY(&Reticle_cur_list) ) { i = hud_reticle_list_find_free(); if ( i == -1 ) return NULL; new_rl = &Reticle_list[i]; cur_rl = GET_FIRST(&Reticle_cur_list); *new_rl = *cur_rl; return_objp = cur_rl->objp; hud_reticle_clear_list(&Reticle_save_list); list_append(&Reticle_save_list, new_rl); } return return_objp; } // hud_target_hotkey_add_remove takes as its parameter which hotkey (1-0) to add/remove the current // target from. This function behaves like the Shift-<selection> does in Windows -- using shift # will toggle // the current target in and out of the selection set. void hud_target_hotkey_add_remove( int k, object *ctarget, int how_to_add ) { htarget_list *hitem, *plist; // don't do anything if a standalone multiplayer server if ( MULTIPLAYER_STANDALONE ) return; if ( (k < 0) || (k >= MAX_KEYED_TARGETS) ) { nprintf(("Warning", "Bogus hotkey %d sent to hud_target_hotkey_add_remove\n", k)); return; } plist = &(Players[Player_num].keyed_targets[k]); // we must operate only on ships if ( ctarget->type != OBJ_SHIP ) return; // don't allow player into hotkey set if ( ctarget == Player_obj ) return; // don't put dying or departing if ( Ships[ctarget->instance].flags & (SF_DYING|SF_DEPARTING) ) return; // don't add mission file added hotkey assignments if there are player added assignments // already in the list if ( (how_to_add == HOTKEY_MISSION_FILE_ADDED) && NOT_EMPTY(plist) ) { for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( hitem->how_added == HOTKEY_USER_ADDED ) return; } } // determine if the current target is currently in the set or not for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( hitem->objp == ctarget ) break; } // if hitem == end of the list, then the target should be added, else it should be removed if ( hitem == END_OF_LIST(plist) ) { if ( EMPTY(&htarget_free_list) ) { Int3(); // get Allender -- no more free hotkey target items return; } nprintf(("network", "Hotkey: Adding %s\n", Ships[ctarget->instance].ship_name)); hitem = GET_FIRST( &htarget_free_list ); list_remove( &htarget_free_list, hitem ); list_append( plist, hitem ); hitem->objp = ctarget; hitem->how_added = how_to_add; } else { nprintf(("network", "Hotkey: Removing %s\n", Ships[ctarget->instance].ship_name)); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; // for safety } } // the following function clears the hotkey set given by parameter passed in void hud_target_hotkey_clear( int k ) { htarget_list *hitem, *plist, *temp; plist = &(Players[Player_num].keyed_targets[k]); hitem = GET_FIRST(plist); while ( hitem != END_OF_LIST(plist) ) { temp = GET_NEXT(hitem); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; hitem = temp; } if ( Players[Player_num].current_hotkey_set == k ) // clear this variable if we removed the bindings Players[Player_num].current_hotkey_set = -1; } // the next function sets the current selected set to be N. If there is just one ship in the selection // set, this ship will become the new target. If there is more than one ship in the selection set, // then the current_target will remain what it was. void hud_target_hotkey_select( int k ) { int visible_count = 0; htarget_list *hitem, *plist, *target, *next_target, *first_target; int target_objnum; plist = &(Players[Player_num].keyed_targets[k]); if ( EMPTY( plist ) ) // no items in list, then do nothing return; // a simple walk of the list to get the count for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ){ if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { visible_count++; } } // no visible ships in list if (visible_count == 0) { return; } // set the current target to be the "next" ship in the list. Scan the list to see if our // current target is in the set. If so, target the next ship in the list, otherwise target // the first // set first_target - first visible item in list // target - item in list that is the player's currently selected target // next_target - next visible item in list following target target_objnum = Player_ai->target_objnum; target = NULL; next_target = NULL; first_target = NULL; for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { // get the first valid target if (first_target == NULL) { first_target = hitem; } // get the next target in the list following the player currently selected target if (target != NULL) { next_target = hitem; break; } } // mark the player currently selected target if ( OBJ_INDEX(hitem->objp) == target_objnum ) { target = hitem; } } // if current target is not in list, then target and next_target will be NULL // so we use the first found target if (target == NULL) { Assert(first_target != NULL); if (first_target != NULL) { target = first_target; next_target = first_target; } else { // this should not happen return; } } // update target if more than 1 is visible if (visible_count > 1) { // next already found (after current target in list) if (next_target != NULL) { target = next_target; } else { // next is before current target, so search from start of list for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { target = hitem; break; } } } } Assert( target != END_OF_LIST(plist) ); if ( Player_obj != target->objp ){ set_target_objnum( Player_ai, OBJ_INDEX(target->objp) ); } Players[Player_num].current_hotkey_set = k; } // hud_init_targeting_colors() will initialize the shader and gradient objects used // on the HUD // color HUD_color_homing_indicator; void hud_make_shader(shader *sh, ubyte r, ubyte g, ubyte b, float dimmer = 1000.0f) { // The m matrix converts all colors to shades of green //float tmp = 16.0f*(0.0015625f * i2fl(HUD_color_alpha+1.0f)); float tmp = 0.025f * i2fl(HUD_color_alpha+1.0f); ubyte R = ubyte(r * tmp); ubyte G = ubyte(r * tmp); ubyte B = ubyte(r * tmp); ubyte A = ubyte((float(r) / dimmer)*(i2fl(HUD_color_alpha) / 15.0f) * 255.0f); gr_create_shader( sh, R, G, B, A ); } void hud_init_targeting_colors() { gr_init_color( &HUD_color_homing_indicator, 0x7f, 0x7f, 0 ); // yellow hud_make_shader(&Training_msg_glass, 61, 61, 85, 500.0f); hud_init_brackets(); } void hud_keyed_targets_clear() { int i; // clear out the keyed target list for (i = 0; i < MAX_KEYED_TARGETS; i++ ) list_init( &(Players[Player_num].keyed_targets[i]) ); Players[Player_num].current_hotkey_set = -1; // place all of the hoykey target items back onto the free list list_init( &htarget_free_list ); for ( i = 0; i < MAX_HOTKEY_TARGET_ITEMS; i++ ) list_append( &htarget_free_list, &htarget_items[i] ); } // Init data used for the weapons display on the HUD void hud_weapons_init() { Weapon_flash_info.is_bright = 0; for ( int i = 0; i < MAX_WEAPON_FLASH_LINES; i++ ) { Weapon_flash_info.flash_duration[i] = 1; Weapon_flash_info.flash_next[i] = 1; } // The E: There used to be a number of checks here. They are no longer needed, as the new HUD code handles it on its own. Weapon_gauges_loaded = 1; } // init data used to play the homing "proximity warning" sound void hud_init_homing_beep() { Homing_beep.snd_handle = -1; Homing_beep.last_time_played = 0; Homing_beep.precalced_interp = (Homing_beep.max_cycle_dist-Homing_beep.min_cycle_dist) / (Homing_beep.max_cycle_time - Homing_beep.min_cycle_time ); } // hud_init_targeting() will set the current target to point to the dummy node // in the object used list // void hud_init_targeting() { Assert(Player_ai != NULL); int i; // decide whether to realign HUD for ballistic primaries ballistic_hud_index = 0; for (i = 0; i < Player_ship->weapons.num_primary_banks; i++) { if (Weapon_info[Player_ship->weapons.primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC) { ballistic_hud_index = 1; break; } } // make sure there is no current target set_target_objnum( Player_ai, -1 ); Player_ai->last_target = -1; Player_ai->last_subsys_target = NULL; Player_ai->last_dist = 0.0f; Player_ai->last_speed = 0.0f; hud_keyed_targets_clear(); hud_init_missile_lock(); hud_init_artillery(); // Init the lists that hold targets in reticle (to allow cycling of targets in reticle) hud_reticle_list_init(); hud_init_homing_beep(); hud_weapons_init(); Min_warning_missile_dist = 2.5f*Player_obj->radius; Max_warning_missile_dist = 1500.0f; Tl_hostile_reset_timestamp = timestamp(0); Tl_friendly_reset_timestamp = timestamp(0); Target_next_uninspected_object_timestamp = timestamp(0); Target_newest_ship_timestamp = timestamp(0); Target_next_turret_timestamp = timestamp(0); if(The_mission.flags & MISSION_FLAG_FULLNEB) { Toggle_text_alpha = TOGGLE_TEXT_NEBULA_ALPHA; } else { Toggle_text_alpha = TOGGLE_TEXT_NORMAL_ALPHA; } } // Target the next or previous subobject on the currently selected ship, based on next_flag. void hud_target_subobject_common(int next_flag) { if (Player_ai->target_objnum == -1) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "No target selected.", 322)); snd_play( &Snds[SND_TARGET_FAIL] ); return; } if (Objects[Player_ai->target_objnum].type != OBJ_SHIP) { snd_play( &Snds[SND_TARGET_FAIL]); return; } ship_subsys *start, *start2, *A; ship_subsys *subsys_to_target=NULL; ship *target_shipp; target_shipp = &Ships[Objects[Player_ai->target_objnum].instance]; if (!Player_ai->targeted_subsys) { start = GET_FIRST(&target_shipp->subsys_list); } else { start = Player_ai->targeted_subsys; } start2 = advance_subsys(start, next_flag); for ( A = start2; A != start; A = advance_subsys(A, next_flag) ) { if ( A == &target_shipp->subsys_list ) { continue; } // ignore turrets if ( A->system_info->type == SUBSYSTEM_TURRET ) { continue; } if ( A->flags & SSF_UNTARGETABLE ) { continue; } subsys_to_target = A; break; } // end for if ( subsys_to_target == NULL ) { snd_play( &Snds[SND_TARGET_FAIL]); } else { set_targeted_subsys(Player_ai, subsys_to_target, Player_ai->target_objnum); target_shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } } object *advance_fb(object *objp, int next_flag) { if (next_flag) return GET_NEXT(objp); else return GET_LAST(objp); } // Target the previous subobject on the currently selected ship. // void hud_target_prev_subobject() { hud_target_subobject_common(0); } void hud_target_next_subobject() { hud_target_subobject_common(1); } // hud_target_next() will set the Players[Player_num].current_target to the next target in the object // used list whose team matches the team parameter. The player is NOT included in the target list. // // parameters: team_mask => team(s) of ship to target next // void hud_target_common(int team_mask, int next_flag) { object *A, *start, *start2; ship *shipp; int is_ship, target_found = FALSE; SCP_list<CJumpNode>::iterator jnp; if (Player_ai->target_objnum == -1) start = &obj_used_list; else start = &Objects[Player_ai->target_objnum]; start2 = advance_fb(start, next_flag); for ( A = start2; A != start; A = advance_fb(A, next_flag) ) { is_ship = 0; if (A == &obj_used_list) continue; if ( (A == Player_obj) || ((A->type != OBJ_SHIP) && (A->type != OBJ_WEAPON) && (A->type != OBJ_JUMP_NODE)) ) continue; if ( hud_target_invalid_awacs(A) ) continue; if (A->type == OBJ_WEAPON) { if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags2 & WIF2_CAN_BE_TARGETED) ) if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ) continue; if (Weapons[A->instance].lssm_stage == 3) continue; } if (A->type == OBJ_SHIP) { if (Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS) continue; is_ship = 1; } if (A->type == OBJ_JUMP_NODE) { for (jnp = Jump_nodes.begin(); jnp != Jump_nodes.end(); ++jnp) { if( jnp->GetSCPObject() == A ) break; } if( jnp->IsHidden() ) continue; } if ( vm_vec_same(&A->pos, &Eye_position) ) continue; if ( is_ship ) { shipp = &Ships[A->instance]; // get a pointer to the ship information if (!iff_matches_mask(shipp->team, team_mask)) { continue; } if ( A == Player_obj || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ){ continue; } // if we've reached here, it is a valid next target if ( Player_ai->target_objnum != A-Objects ) { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); // if ship is BIG|HUGE and last subsys is NULL, get turret hud_maybe_set_sorted_turret_subsys(shipp); hud_restore_subsystem_target(shipp); } } else { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); } break; } if ( target_found == FALSE ) { snd_play( &Snds[SND_TARGET_FAIL] ); } } void hud_target_next(int team_mask) { hud_target_common(team_mask, 1); } void hud_target_prev(int team_mask) { hud_target_common(team_mask, 0); } // ------------------------------------------------------------------- // advance_missile_obj() // missile_obj *advance_missile_obj(missile_obj *mo, int next_flag) { if (next_flag){ return GET_NEXT(mo); } return GET_LAST(mo); } ship_obj *advance_ship(ship_obj *so, int next_flag) { if (next_flag){ return GET_NEXT(so); } return GET_LAST(so); } /// \brief Iterates down to and selects the next target in a linked list /// fashion ordered from closest to farthest from the /// attacked_object_number, returning the next valid target. /// /// /// \param targeting_from_closest_to_farthest[in] targets the closest object /// if true. Targets the farthest /// away object if false. /// \param valid_team_mask[in] A bit mask that defines the desired /// victim team. /// \param attacked_object_number[in] The objectid that is under attack. /// Defaults to -1. /// \param target_filters Applies a bit filter to exclude certain /// classes of objects from being targeted. /// Defaults to (SIF_CARGO | SIF_NAVBUOY) /// /// \returns The next object to target if targeting was successful. /// Returns NULL if targeting was unsuccessful. static object* select_next_target_by_distance( const bool targeting_from_closest_to_farthest, const int valid_team_mask, const int attacked_object_number = -1, const int target_filters = (SIF_CARGO | SIF_NAVBUOY)) { object *minimum_object_ptr, *maximum_object_ptr, *nearest_object_ptr; minimum_object_ptr = maximum_object_ptr = nearest_object_ptr = NULL; float current_distance = hud_find_target_distance(&Objects[Player_ai->target_objnum], Player_obj); float minimum_distance = 1e20f; float maximum_distance = 0.0f; int player_object_index = OBJ_INDEX(Player_obj); float nearest_distance; if ( targeting_from_closest_to_farthest ) { nearest_distance = 1e20f; } else { nearest_distance = 0.0f; } ship_obj *ship_object_ptr; object *prospective_victim_ptr; ship *prospective_victim_ship_ptr; for ( ship_object_ptr = GET_FIRST(&Ship_obj_list); ship_object_ptr != END_OF_LIST(&Ship_obj_list); ship_object_ptr = GET_NEXT( ship_object_ptr) ) { prospective_victim_ptr = &Objects[ ship_object_ptr->objnum]; // get a pointer to the ship information prospective_victim_ship_ptr = &Ships[prospective_victim_ptr->instance]; float new_distance; if ( (prospective_victim_ptr == Player_obj) || (prospective_victim_ship_ptr->flags & TARGET_SHIP_IGNORE_FLAGS) ) { continue; } // choose from the correct team if ( !iff_matches_mask(prospective_victim_ship_ptr->team, valid_team_mask) ) { continue; } // don't use object if it is already a target if ( OBJ_INDEX(prospective_victim_ptr) == Player_ai->target_objnum ) { continue; } if( attacked_object_number == -1 ) { // always ignore navbuoys and cargo if ( Ship_info[prospective_victim_ship_ptr->ship_info_index].flags & target_filters ) { continue; } if(hud_target_invalid_awacs(prospective_victim_ptr)){ continue; } new_distance = hud_find_target_distance(prospective_victim_ptr,Player_obj); } else { // Filter out any target that is not targeting the player --Mastadon if ( (attacked_object_number == player_object_index) && (Ai_info[prospective_victim_ship_ptr->ai_index].target_objnum != player_object_index) ) { continue; } esct eval_ship_as_closest_target_args; eval_ship_as_closest_target_args.attacked_objnum = attacked_object_number; eval_ship_as_closest_target_args.check_all_turrets = (attacked_object_number == player_object_index); eval_ship_as_closest_target_args.check_nearest_turret = FALSE; // We don't ever filter our target selection to just bombers or fighters // because the select next attacker logic doesn't. --Mastadon eval_ship_as_closest_target_args.filter = 0; eval_ship_as_closest_target_args.team_mask = valid_team_mask; // We always get the turret attacking, since that's how the select next // attacker logic does it. --Mastadon eval_ship_as_closest_target_args.turret_attacking_target = 1; eval_ship_as_closest_target_args.shipp = prospective_victim_ship_ptr; evaluate_ship_as_closest_target( &eval_ship_as_closest_target_args ); new_distance = eval_ship_as_closest_target_args.min_distance; } if (new_distance <= minimum_distance) { minimum_distance = new_distance; minimum_object_ptr = prospective_victim_ptr; } if (new_distance >= maximum_distance) { maximum_distance = new_distance; maximum_object_ptr = prospective_victim_ptr; } float diff = 0.0f; if ( targeting_from_closest_to_farthest ) { diff = new_distance - current_distance; if ( diff > 0.0f ) { if ( diff < ( nearest_distance - current_distance ) ) { nearest_distance = new_distance; nearest_object_ptr = prospective_victim_ptr; } } } else { diff = current_distance - new_distance; if ( diff > 0.0f ) { if ( diff < ( current_distance - nearest_distance ) ) { nearest_distance = new_distance; nearest_object_ptr = const_cast<object *>(prospective_victim_ptr); } } } } if ( nearest_object_ptr == NULL ) { if ( targeting_from_closest_to_farthest ) { if ( minimum_object_ptr != NULL ) { nearest_object_ptr = minimum_object_ptr; } } else { if ( maximum_object_ptr != NULL ) { nearest_object_ptr = maximum_object_ptr; } } } return nearest_object_ptr; } ship_obj *get_ship_obj_ptr_from_index(int index); // ------------------------------------------------------------------- // hud_target_missile() // // Target the closest locked missile that is locked on locked_obj // // input: source_obj => pointer to object that fired weapon // next_flag => 0 -> previous 1 -> next // // NOTE: this function is only allows targeting bombs void hud_target_missile(object *source_obj, int next_flag) { missile_obj *end, *start, *mo; object *A, *target_objp; ai_info *aip; weapon *wp; weapon_info *wip; int target_found = 0; if ( source_obj->type != OBJ_SHIP ) return; Assert( Ships[source_obj->instance].ai_index != -1 ); aip = &Ai_info[Ships[source_obj->instance].ai_index]; end = &Missile_obj_list; if (aip->target_objnum != -1) { target_objp = &Objects[aip->target_objnum]; if ( target_objp->type == OBJ_WEAPON && Weapon_info[Weapons[target_objp->instance].weapon_info_index].subtype == WP_MISSILE ) { // must be a missile end = missile_obj_return_address(Weapons[target_objp->instance].missile_list_index); } } start = advance_missile_obj(end, next_flag); for ( mo = start; mo != end; mo = advance_missile_obj(mo, next_flag) ) { if ( mo == &Missile_obj_list ){ continue; } Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); A = &Objects[mo->objnum]; Assert(A->type == OBJ_WEAPON); Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; wip = &Weapon_info[wp->weapon_info_index]; // only allow targeting of bombs if ( !(wip->wi_flags2 & WIF2_CAN_BE_TARGETED) ) { if ( !(wip->wi_flags & WIF_BOMB) ) { continue; } } if (wp->lssm_stage==3){ continue; } // only allow targeting of hostile bombs if (!iff_x_attacks_y(Player_ship->team, obj_team(A))) { continue; } if(hud_target_invalid_awacs(A)){ continue; } // if we've reached here, got a new target target_found = TRUE; set_target_objnum( aip, OBJ_INDEX(A) ); break; } // end for if ( !target_found ) { // if no bomb is found, search for bombers ship_obj *startShip, *so; if ( (aip->target_objnum != -1) && (Objects[aip->target_objnum].type == OBJ_SHIP) && ((Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & SIF_BOMBER) || (Objects[aip->target_objnum].flags & OF_TARGETABLE_AS_BOMB))) { int index = Ships[Objects[aip->target_objnum].instance].ship_list_index; startShip = get_ship_obj_ptr_from_index(index); } else { startShip = GET_FIRST(&Ship_obj_list); } for (so=advance_ship(startShip, next_flag); so!=startShip; so=advance_ship(so, next_flag)) { A = &Objects[so->objnum]; // don't look at header if (so == &Ship_obj_list) { continue; } // only allow targeting of hostile bombs if (!iff_x_attacks_y(Player_ship->team, obj_team(A))) { continue; } if(hud_target_invalid_awacs(A)){ continue; } // check if ship type is bomber if ( !(Ship_info[Ships[A->instance].ship_info_index].flags & SIF_BOMBER) && !(A->flags & OF_TARGETABLE_AS_BOMB) ) { continue; } // check if ignore if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } // found a good one target_found = TRUE; set_target_objnum( aip, OBJ_INDEX(A) ); break; } } if ( !target_found ) { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // Return !0 if shipp can be scanned, otherwise return 0 int hud_target_ship_can_be_scanned(ship *shipp) { ship_info *sip; sip = &Ship_info[shipp->ship_info_index]; // ignore cargo that has already been scanned if (shipp->flags & SF_CARGO_REVEALED) return 0; // allow ships with scannable flag set if (shipp->flags & SF_SCANNABLE) return 1; // ignore ships that don't carry cargo if ((sip->class_type < 0) || !(Ship_types[sip->class_type].ship_bools & STI_SHIP_SCANNABLE)) return 0; return 1; } // target the next/prev uninspected cargo container void hud_target_uninspected_cargo(int next_flag) { object *A, *start, *start2; ship *shipp; int target_found = 0; if (Player_ai->target_objnum == -1) { start = &obj_used_list; } else { start = &Objects[Player_ai->target_objnum]; } start2 = advance_fb(start, next_flag); for ( A = start2; A != start; A = advance_fb(A, next_flag) ) { if ( A == &obj_used_list ) { continue; } if (A == Player_obj || (A->type != OBJ_SHIP) ) { continue; } shipp = &Ships[A->instance]; // get a pointer to the ship information if ( shipp->flags & TARGET_SHIP_IGNORE_FLAGS ) { continue; } // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } // if we've reached here, it is a valid next target if ( Player_ai->target_objnum != OBJ_INDEX(A) ) { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); } } if ( target_found == FALSE ) { snd_play( &Snds[SND_TARGET_FAIL]); } } // target the newest ship in the area void hud_target_newest_ship() { object *A, *player_target_objp; object *newest_obj=NULL; ship *shipp; ship_obj *so; uint current_target_arrived_time = 0xffffffff, newest_time = 0; if ( Player_ai->target_objnum >= 0 ) { player_target_objp = &Objects[Player_ai->target_objnum]; if ( player_target_objp->type == OBJ_SHIP ) { current_target_arrived_time = Ships[player_target_objp->instance].create_time; } } else { player_target_objp = NULL; } // If no target is selected, then simply target the closest uninspected cargo if ( Player_ai->target_objnum == -1 || timestamp_elapsed(Target_newest_ship_timestamp) ) { current_target_arrived_time = 0xffffffff; } Target_newest_ship_timestamp = timestamp(TL_RESET); for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // ignore navbuoys if ( Ship_info[shipp->ship_info_index].flags & SIF_NAVBUOY ) { continue; } if ( A == player_target_objp ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } if ( (shipp->create_time >= newest_time) && (shipp->create_time <= current_target_arrived_time) ) { newest_time = shipp->create_time; newest_obj = A; } } if (newest_obj) { set_target_objnum( Player_ai, OBJ_INDEX(newest_obj) ); // if BIG|HUGE and no selected subsystem, get sorted turret hud_maybe_set_sorted_turret_subsys(&Ships[newest_obj->instance]); hud_restore_subsystem_target(&Ships[newest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL]); } } #define TYPE_NONE 0 #define TYPE_FACING_BEAM 1 #define TYPE_FACING_FLAK 2 #define TYPE_FACING_MISSILE 3 #define TYPE_FACING_LASER 4 #define TYPE_NONFACING_BEAM 5 #define TYPE_NONFACING_FLAK 6 #define TYPE_NONFACING_MISSILE 7 #define TYPE_NONFACING_LASER 8 #define TYPE_NONFACING_INC 4 typedef struct eval_next_turret { ship_subsys *ss; int type; float dist; } eval_next_turret; int turret_compare_func(const void *e1, const void *e2) { eval_next_turret *p1 = (eval_next_turret*)e1; eval_next_turret *p2 = (eval_next_turret*)e2; Assert(p1->type != TYPE_NONE); Assert(p2->type != TYPE_NONE); if (p1->type != p2->type) { return (p1->type - p2->type); } else { float delta_dist = p1->dist - p2->dist; if (delta_dist < 0) { return -1; } else if (delta_dist > 0) { return 1; } else { return 0; } } } extern bool turret_weapon_has_flags(ship_weapon *swp, int flags); extern bool turret_weapon_has_subtype(ship_weapon *swp, int subtype); // target the next/prev live turret on the current target // auto_advance from hud_update_closest_turret void hud_target_live_turret(int next_flag, int auto_advance, int only_player_target) { ship_subsys *A; ship_subsys *live_turret=NULL; ship *target_shipp; object *objp; eval_next_turret ent[MAX_MODEL_SUBSYSTEMS]; int num_live_turrets = 0; // make sure we're targeting a ship if (Player_ai->target_objnum == -1 && !auto_advance) { snd_play(&Snds[SND_TARGET_FAIL]); return; } // only targeting subsystems on ship if ((Objects[Player_ai->target_objnum].type != OBJ_SHIP) && (!auto_advance)) { snd_play( &Snds[SND_TARGET_FAIL]); return; } // set some pointers objp = &Objects[Player_ai->target_objnum]; target_shipp = &Ships[objp->instance]; // set timestamp int timestamp_val = 0; if (!auto_advance) { timestamp_val = Target_next_turret_timestamp; Target_next_turret_timestamp = timestamp(TURRET_RESET); } // If no target is selected, then simply target the closest (or facing) turret int last_subsys_turret = FALSE; if (Player_ai->targeted_subsys != NULL) { if (Player_ai->targeted_subsys->system_info->type == SUBSYSTEM_TURRET) { if (Player_ai->targeted_subsys->weapons.num_primary_banks > 0 || Player_ai->targeted_subsys->weapons.num_secondary_banks > 0) { last_subsys_turret = TRUE; } } } // do we want the closest turret (or the one our ship is pointing at) int get_closest_turret = (auto_advance || !last_subsys_turret || timestamp_elapsed(timestamp_val)); // initialize eval struct memset(ent,0, sizeof(ent)); int use_straight_ahead_turret = FALSE; // go through list of turrets for (A=GET_FIRST(&target_shipp->subsys_list); A!=END_OF_LIST(&target_shipp->subsys_list); A=GET_NEXT(A)) { // get a turret if (A->system_info->type == SUBSYSTEM_TURRET) { // niffiwan: ignore untargetable turrets if ( A->flags & SSF_UNTARGETABLE ) { continue; } // check turret has hit points and has a weapon if ( (A->current_hits > 0) && (A->weapons.num_primary_banks > 0 || A->weapons.num_secondary_banks > 0) ) { if ( !only_player_target || (A->turret_enemy_objnum == OBJ_INDEX(Player_obj)) ) { vec3d gsubpos, vec_to_subsys; float distance, dot; // get world pos of subsystem and its distance get_subsystem_world_pos(objp, A, &gsubpos); distance = vm_vec_normalized_dir(&vec_to_subsys, &gsubpos, &View_position); // check if facing and in view int facing = ship_subsystem_in_sight(objp, A, &View_position, &gsubpos, 0); if (!auto_advance && get_closest_turret && !only_player_target) { // if within 3 degrees and not previous subsys, use subsys in front dot = vm_vec_dotprod(&vec_to_subsys, &Player_obj->orient.vec.fvec); if ((dot > 0.9986) && facing) { use_straight_ahead_turret = TRUE; break; } } // set weapon_type to allow sort of ent on type if (turret_weapon_has_flags(&A->weapons, WIF_BEAM)) { ent[num_live_turrets].type = TYPE_FACING_BEAM; } else if (turret_weapon_has_flags(&A->weapons, WIF_FLAK)) { ent[num_live_turrets].type = TYPE_FACING_FLAK; } else { if (turret_weapon_has_subtype(&A->weapons, WP_MISSILE)) { ent[num_live_turrets].type = TYPE_FACING_MISSILE; } else if (turret_weapon_has_subtype(&A->weapons, WP_LASER)) { ent[num_live_turrets].type = TYPE_FACING_LASER; } else { //Turret not live, bail continue; } } // fill out ent struct ent[num_live_turrets].ss = A; ent[num_live_turrets].dist = distance; if (!facing) { ent[num_live_turrets].type += TYPE_NONFACING_INC; } num_live_turrets++; } } } } // sort the list if we're not using turret straight ahead of us if (!use_straight_ahead_turret) { insertion_sort(ent, num_live_turrets, sizeof(eval_next_turret), turret_compare_func); } if (use_straight_ahead_turret) { // use the straight ahead turret live_turret = A; } else { // check if we have a currently targeted turret and find its position after the sort int i, start_index, next_index; if (get_closest_turret) { start_index = 0; } else { start_index = -1; for (i=0; i<num_live_turrets; i++) { if (ent[i].ss == Player_ai->targeted_subsys) { start_index = i; break; } } // check that we started with a turret if (start_index == -1) { start_index = 0; } } // set next live turret if (num_live_turrets == 0) { // no live turrets live_turret = NULL; } else if (num_live_turrets == 1 || get_closest_turret) { // only 1 live turret, so set it live_turret = ent[0].ss; } else { if (next_flag) { // advance to next closest turret next_index = start_index + 1; if (next_index == num_live_turrets) { next_index = 0; } } else { // go to next farther turret next_index = start_index - 1; if (next_index == -1) { next_index = num_live_turrets - 1; } } // set the next turret to be targeted based on next_index live_turret = ent[next_index].ss; } //if (live_turret) { // debug info // mprintf(("name %s, index: %d, type: %d\n", live_turret->system_info->subobj_name, next_index, ent[next_index].type)); //} } if ( live_turret != NULL ) { set_targeted_subsys(Player_ai, live_turret, Player_ai->target_objnum); target_shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } else { if (!auto_advance) { snd_play( &Snds[SND_TARGET_FAIL]); } } } // ------------------------------------------------------------------- // hud_target_closest_locked_missile() // // Target the closest locked missile that is locked on locked_obj // // input: locked_obj => pointer to object that you want to find // closest missile to // void hud_target_closest_locked_missile(object *locked_obj) { object *A, *nearest_obj=NULL; weapon *wp; weapon_info *wip; float nearest_dist, dist; int target_found = FALSE; missile_obj *mo; nearest_dist = 10000.0f; for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); A = &Objects[mo->objnum]; if (A->type != OBJ_WEAPON){ continue; } Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; wip = &Weapon_info[wp->weapon_info_index]; if ( wip->subtype != WP_MISSILE ){ continue; } if ( !(wip->wi_flags & WIF_HOMING ) ){ continue; } if (wp->lssm_stage==3){ continue; } if(hud_target_invalid_awacs(A)){ continue; } if (wp->homing_object == locked_obj) { dist = vm_vec_dist_quick(&A->pos, &locked_obj->pos); // Find distance! if (dist < nearest_dist) { nearest_obj = A; nearest_dist = dist; } } } // end for if (nearest_dist < 10000.0f) { Assert(nearest_obj); set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); target_found = TRUE; } if ( !target_found ){ snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // select a new target, by auto-targeting void hud_target_auto_target_next() { if ( Framecount < 2 ) { return; } // No auto-targeting after dead. if (Game_mode & (GM_DEAD | GM_DEAD_BLEW_UP)) return; // try target next ship in hotkey set, if any -- Backslash if ( Player->current_hotkey_set != -1 ) { hud_target_hotkey_select(Player->current_hotkey_set); } int valid_team_mask = iff_get_attackee_mask(Player_ship->team); // if none, try targeting closest hostile fighter/bomber if ( Player_ai->target_objnum == -1 ) { //-V581 hud_target_closest(valid_team_mask, -1, FALSE, TRUE); } // No fighter/bombers exists, so go ahead an target the closest hostile if ( Player_ai->target_objnum == -1 ) { //-V581 hud_target_closest(valid_team_mask, -1, FALSE); } // um, ok. Try targeting asteroids that are on a collision course for an escort ship if ( Player_ai->target_objnum == -1 ) { //-V581 asteroid_target_closest_danger(); } } // Given that object 'targeter' is targeting object 'targetee', // how far are they? This uses the point closest to the targeter // object on the targetee's bounding box. So if targeter is inside // targtee's bounding box, the distance is 0. float hud_find_target_distance( object *targetee, object *targeter ) { vec3d tmp_pnt; int model_num = -1; // Which model is it? switch( targetee->type ) { case OBJ_SHIP: model_num = Ship_info[Ships[targetee->instance].ship_info_index].model_num; break; case OBJ_DEBRIS: // model_num = Debris[targetee->instance].model_num; break; case OBJ_WEAPON: // Don't find model_num since circles would work better //model_num = Weapon_info[Weapons[targetee->instance].weapon_info_index].model_num; break; case OBJ_ASTEROID: // Don't find model_num since circles would work better //model_num = Asteroid_info[Asteroids[targetee->instance].type].model_num; break; case OBJ_JUMP_NODE: // Don't find model_num since circles would work better //model_num = Jump_nodes[targetee->instance].modelnum; break; } float dist = 0.0f; // New way, that uses bounding box. if ( model_num > -1 ) { dist = model_find_closest_point( &tmp_pnt, model_num, -1, &targetee->orient, &targetee->pos, &targeter->pos ); } else { // Old way, that uses radius. dist = vm_vec_dist_quick(&targetee->pos, &targeter->pos) - targetee->radius; if ( dist < 0.0f ) { dist = 0.0f; } } return dist; } // /// \brief evaluate a ship (and maybe turrets) as a potential target /// /// Check if shipp (or its turrets) is attacking attacked_objnum /// Provides a special case for player trying to select target (don't check if /// turrets are aimed at player) /// /// \param[in, out] *esct The Evaluate Ship as Closest Target (esct) that will /// be used to determine if a target is a valid, harmful /// target and, if so, sets the min_distance attribute /// to the distance of either the attacker or the /// closest attacker's turret. Otherwise, min_distance /// is set to FLT_MAX /// /// \return true if either the ship or one of it's turrets are attacking the /// player. Otherwise, returns false. bool evaluate_ship_as_closest_target(esct *esct) { int targeting_player, turret_is_attacking; ship_subsys *ss; float new_distance; // initialize esct->min_distance = FLT_MAX; esct->check_nearest_turret = FALSE; turret_is_attacking = FALSE; object *objp = &Objects[esct->shipp->objnum]; Assert(objp->type == OBJ_SHIP); if (objp->type != OBJ_SHIP) { return false; } // player being targeted, so we will want closest distance from player targeting_player = (esct->attacked_objnum == OBJ_INDEX(Player_obj)); // filter on team if ( !iff_matches_mask(esct->shipp->team, esct->team_mask) ) { return false; } // check if player or ignore ship if ( (esct->shipp->objnum == OBJ_INDEX(Player_obj)) || (esct->shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) { return false; } // bail if harmless if ( Ship_info[esct->shipp->ship_info_index].class_type > -1 && !(Ship_types[Ship_info[esct->shipp->ship_info_index].class_type].hud_bools & STI_HUD_TARGET_AS_THREAT)) { return false; } // only look at targets that are AWACS valid if (hud_target_invalid_awacs(&Objects[esct->shipp->objnum])) { return false; } // If filter is set, only target fighters and bombers if ( esct->filter ) { if ( !(Ship_info[esct->shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) ) { return false; } } // find closest turret to player if BIG or HUGE ship if (Ship_info[esct->shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) { for (ss=GET_FIRST(&esct->shipp->subsys_list); ss!=END_OF_LIST(&esct->shipp->subsys_list); ss=GET_NEXT(ss)) { if (ss->flags & SSF_UNTARGETABLE) continue; if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { if (esct->check_all_turrets || (ss->turret_enemy_objnum == esct->attacked_objnum)) { turret_is_attacking = 1; esct->check_nearest_turret = TRUE; if ( !esct->turret_attacking_target || (esct->turret_attacking_target && (ss->turret_enemy_objnum == esct->attacked_objnum)) ) { vec3d gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &objp->orient); vm_vec_add2(&gsubpos, &objp->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); /* // GET TURRET TYPE, FAVOR BEAM, FLAK, OTHER int turret_type = ss->system_info->turret_weapon_type; if (Weapon_info[turret_type].wi_flags & WIF_BEAM) { new_distance *= 0.3f; } else if (Weapon_info[turret_type].wi_flags & WIF_FLAK) { new_distance *= 0.6f; } */ // get the closest distance if (new_distance <= esct->min_distance) { esct->min_distance = new_distance; } } } } } } // If no turret is attacking, check if objp is actually targeting attacked_objnum // don't bail if targeting is for player if ( !targeting_player && !turret_is_attacking ) { ai_info *aip = &Ai_info[esct->shipp->ai_index]; if (aip->target_objnum != esct->attacked_objnum) { return false; } if ( (Game_mode & GM_NORMAL) && ( aip->mode != AIM_CHASE ) && (aip->mode != AIM_STRAFE) && (aip->mode != AIM_EVADE) && (aip->mode != AIM_EVADE_WEAPON) && (aip->mode != AIM_AVOID)) { return false; } } // consider the ship alone if there are no attacking turrets if ( !turret_is_attacking ) { //new_distance = hud_find_target_distance(objp, Player_obj); new_distance = vm_vec_dist_quick(&objp->pos, &Player_obj->pos); if (new_distance <= esct->min_distance) { esct->min_distance = new_distance; esct->check_nearest_turret = FALSE; } } return true; } /// \brief Sets the Players[Player_num].current_target to the closest ship to /// the player that matches the team passed as a paramater. /// /// The current algorithm is to simply iterate through the objects and /// calculate the magnitude of the vector that connects the player to the /// target. The smallest magnitude is tracked, and then used to locate the /// closest hostile ship. Note only the square of the magnitude is required, /// since we are only comparing magnitudes. /// /// \param[in] team_mask team of closest ship that should be targeted. /// Default value is -1, if team doesn't matter. /// /// \param[in] attacked_objnum object number of ship that is being attacked /// \param[in] play_fail_snd boolean, whether to play SND_TARGET_FAIL /// (needed, since function called repeatedly when /// auto-targeting is enabled, and we don't want a /// string of fail sounds playing). This is a /// default parameter with a value of TRUE. /// \param[in] filter OPTIONAL parameter (default value 0): when set /// to TRUE, only fighters and bombers are /// considered for new targets. /// \param[in] get_closest_turret_attacking_player Finds the closest turret /// attacking the player if true. Otherwise, only /// finds the closest attacking ship, targeting the /// turret closest to the player. /// /// \return: true (non-zero) if a target was acquired. Returns false (zero) if /// no target was acquired. int hud_target_closest(int team_mask, int attacked_objnum, int play_fail_snd, int filter, int get_closest_turret_attacking_player) { object *A; object *nearest_obj = &obj_used_list; ship *shipp; ship_obj *so; int check_nearest_turret = FALSE; // evaluate ship closest target struct esct esct; float min_distance = FLT_MAX; int target_found = FALSE; int player_obj_index = OBJ_INDEX(Player_obj); ship_subsys *ss; int initial_attacked_objnum = attacked_objnum; if ( (attacked_objnum >= 0) && (attacked_objnum != player_obj_index) ) { // bail if player does not have target if ( Player_ai->target_objnum == -1 ) { goto Target_closest_done; } if ( Objects[attacked_objnum].type != OBJ_SHIP ) { goto Target_closest_done; } // bail if ship is to be ignored if (Ships[Objects[attacked_objnum].instance].flags & TARGET_SHIP_IGNORE_FLAGS) { goto Target_closest_done; } } if (attacked_objnum == -1) { attacked_objnum = player_obj_index; } // check all turrets if for player. esct.check_all_turrets = (attacked_objnum == player_obj_index); esct.filter = filter; esct.team_mask = team_mask; esct.attacked_objnum = attacked_objnum; esct.turret_attacking_target = get_closest_turret_attacking_player; for ( so=GET_FIRST(&Ship_obj_list); so!=END_OF_LIST(&Ship_obj_list); so=GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information // fill in rest of esct esct.shipp = shipp; // Filter out any target that is not targeting the player --Mastadon if ( (initial_attacked_objnum == player_obj_index) && (Ai_info[shipp->ai_index].target_objnum != player_obj_index) ) { continue; } // check each shipp on list and update nearest obj and subsys evaluate_ship_as_closest_target(&esct); if (esct.min_distance < min_distance) { target_found = TRUE; min_distance = esct.min_distance; nearest_obj = A; check_nearest_turret = esct.check_nearest_turret; } } Target_closest_done: // maybe ignore target if too far away // DKA 9/8/99 Remove distance check /* if (target_found) { // get distance to nearest attacker float dist = vm_vec_dist_quick(&Objects[attacked_objnum].pos, &nearest_obj->pos); // no distance limit for player obj if ((attacked_objnum != player_obj_index) && (dist > MIN_DISTANCE_TO_CONSIDER_THREAT)) { target_found = FALSE; } } */ if (target_found) { set_target_objnum(Player_ai, OBJ_INDEX(nearest_obj)); if ( check_nearest_turret ) { // if former subobject was not a turret do, not change subsystem ss = Ships[nearest_obj->instance].last_targeted_subobject[Player_num]; if (ss == NULL || get_closest_turret_attacking_player) { // update nearest turret with later func hud_target_live_turret(1, 1, get_closest_turret_attacking_player); Ships[nearest_obj->instance].last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } } else { hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } } else { // no target found, maybe play fail sound if (play_fail_snd == TRUE) { snd_play(&Snds[SND_TARGET_FAIL]); } } return target_found; } // auto update closest turret to attack on big or huge ships void hud_update_closest_turret() { hud_target_live_turret(1, 1); /* float nearest_distance, new_distance; ship_subsys *ss, *closest_subsys; ship *shipp; object *objp; nearest_distance = FLT_MAX; objp = &Objects[Player_ai->target_objnum]; shipp = &Ships[objp->instance]; closest_subsys = NULL; Assert(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)); for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) { if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { // make sure turret is not "unused" if (ss->system_info->turret_weapon_type >= 0) { vec3d gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &objp->orient); vm_vec_add2(&gsubpos, &objp->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); // GET TURRET TYPE, FAVOR BEAM, FLAK, OTHER int turret_type = ss->system_info->turret_weapon_type; if (Weapon_info[turret_type].wi_flags & WIF_BEAM) { new_distance *= 0.3f; } else if (Weapon_info[turret_type].wi_flags & WIF_FLAK) { new_distance *= 0.6f; } // check if facing and in view int facing = ship_subsystem_in_sight(objp, ss, &View_position, &gsubpos, 0); if (facing) { new_distance *= 0.5f; } // get the closest distance if (new_distance <= nearest_distance) { nearest_distance = new_distance; closest_subsys = ss; } } } } // check if new subsys to target if (Player_ai->targeted_subsys != NULL) { set_targeted_subsys(Player_ai, closest_subsys, Player_ai->target_objnum); shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } */ } // -------------------------------------------------------------------- // hud_target_targets_target() // // Target your target's target. Your target is specified by objnum passed // as a parameter. // void hud_target_targets_target() { object *objp = NULL; object *tt_objp = NULL; int tt_objnum; if ( Player_ai->target_objnum < 0 || Player_ai->target_objnum >= MAX_OBJECTS ) { goto ttt_fail; } objp = &Objects[Player_ai->target_objnum]; if ( objp->type != OBJ_SHIP ) { goto ttt_fail; } tt_objnum = Ai_info[Ships[objp->instance].ai_index].target_objnum; if ( tt_objnum < 0 || tt_objnum >= MAX_OBJECTS ) { goto ttt_fail; } if ( tt_objnum == OBJ_INDEX(Player_obj) ) { goto ttt_fail; } tt_objp = &Objects[tt_objnum]; if (hud_target_invalid_awacs(tt_objp)) { goto ttt_fail; } if ( tt_objp->type != OBJ_SHIP ) { goto ttt_fail; } if ( Ships[tt_objp->instance].flags & TARGET_SHIP_IGNORE_FLAGS ) { goto ttt_fail; } // if we've reached here, found player target's target set_target_objnum( Player_ai, tt_objnum ); if (Objects[tt_objnum].type == OBJ_SHIP) { hud_maybe_set_sorted_turret_subsys(&Ships[Objects[tt_objnum].instance]); } hud_restore_subsystem_target(&Ships[Objects[tt_objnum].instance]); return; ttt_fail: snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } // Return !0 if target_objp is a valid object type for targeting in reticle, otherwise return 0 int object_targetable_in_reticle(object *target_objp) { int obj_type; SCP_list<CJumpNode>::iterator jnp; if (target_objp == Player_obj ) { return 0; } obj_type = target_objp->type; if ( (obj_type == OBJ_SHIP) || (obj_type == OBJ_DEBRIS) || (obj_type == OBJ_WEAPON) || (obj_type == OBJ_ASTEROID) ) { return 1; } else if ( obj_type == OBJ_JUMP_NODE ) { for (jnp = Jump_nodes.begin(); jnp != Jump_nodes.end(); ++jnp) { if(jnp->GetSCPObject() == target_objp) break; } if (!jnp->IsHidden()) return 1; } return 0; } // hud_target_in_reticle_new() will target the object that is closest to the player, and who is // intersected by a ray passed from the center of the reticle out along the forward vector of the // player. // // targeting of objects of type OBJ_SHIP and OBJ_DEBRIS are supported // // Method: A ray is cast from the center of the reticle, and we keep track of any eligible object // the ray intersects. We take the ship closest to us that intersects an object. // // Since this method may work poorly with objects that are far away, hud_target_in_reticle_old() // is called if no intersections are found. // // #define TARGET_IN_RETICLE_DISTANCE 10000.0f void hud_target_in_reticle_new() { vec3d terminus; object *A; mc_info mc; float dist; SCP_list<CJumpNode>::iterator jnp; hud_reticle_clear_list(&Reticle_cur_list); Reticle_save_timestamp = timestamp(RESET_TARGET_IN_RETICLE); // Get 3d vector through center of reticle vm_vec_scale_add(&terminus, &Eye_position, &Player_obj->orient.vec.fvec, TARGET_IN_RETICLE_DISTANCE); mc.model_instance_num = -1; mc.model_num = 0; for ( A = GET_FIRST(&obj_used_list); A !=END_OF_LIST(&obj_used_list); A = GET_NEXT(A) ) { if ( !object_targetable_in_reticle(A) ) { continue; } if ( A->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags2 & WIF2_CAN_BE_TARGETED) ) { if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ){ continue; } } if (Weapons[A->instance].lssm_stage==3){ continue; } } if ( A->type == OBJ_SHIP ) { if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } } if(hud_target_invalid_awacs(A)){ continue; } switch (A->type) { case OBJ_SHIP: mc.model_num = Ship_info[Ships[A->instance].ship_info_index].model_num; break; case OBJ_DEBRIS: mc.model_num = Debris[A->instance].model_num; break; case OBJ_WEAPON: mc.model_num = Weapon_info[Weapons[A->instance].weapon_info_index].model_num; break; case OBJ_ASTEROID: { int pof = 0; pof = Asteroids[A->instance].asteroid_subtype; mc.model_num = Asteroid_info[Asteroids[A->instance].asteroid_type].model_num[pof]; } break; case OBJ_JUMP_NODE: for (jnp = Jump_nodes.begin(); jnp != Jump_nodes.end(); ++jnp) { if(jnp->GetSCPObject() == A) break; } mc.model_num = jnp->GetModelNumber(); break; default: Int3(); // Illegal object type. } if (mc.model_num == -1) { // so just check distance of a point vec3d temp_v; float angle; vm_vec_sub(&temp_v, &A->pos, &Eye_position); vm_vec_normalize(&temp_v); angle = vm_vec_dot(&Player_obj->orient.vec.fvec, &temp_v); if (angle > 0.99f) { dist = vm_vec_mag_squared(&temp_v); hud_reticle_list_update(A, dist, 0); } } else { model_clear_instance( mc.model_num ); mc.orient = &A->orient; // The object's orient mc.pos = &A->pos; // The object's position mc.p0 = &Eye_position; // Point 1 of ray to check mc.p1 = &terminus; // Point 2 of ray to check mc.flags = MC_CHECK_MODEL; // | MC_ONLY_BOUND_BOX; // check the model, but only its bounding box model_collide(&mc); if ( mc.num_hits ) { dist = vm_vec_dist_squared(&mc.hit_point_world, &Eye_position); hud_reticle_list_update(A, dist, 0); } } } // end for (go to next object) hud_target_in_reticle_old(); // try the old method (works well with ships far away) } // hud_target_in_reticle_old() will target the object that is closest to the reticle center and inside // the reticle // // targeting of objects of type OBJ_SHIP and OBJ_DEBRIS are supported // // // Method: take the dot product of the foward vector and the vector to target. Take // the one that is closest to 1 and at least MIN_DOT_FOR_TARGET // // IMPORTANT: The MIN_DOT_FOR_TARGET value was arrived at by trial and error and // is only valid for the HUD reticle in use at that time. #define MIN_DOT_FOR_TARGET 0.9726// fov for targeting in reticle void hud_target_in_reticle_old() { object *A, *target_obj; float dot; vec3d vec_to_target; for ( A = GET_FIRST(&obj_used_list); A !=END_OF_LIST(&obj_used_list); A = GET_NEXT(A) ) { if ( !object_targetable_in_reticle(A) ) { continue; } if ( A->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags2 & WIF2_CAN_BE_TARGETED) ){ if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ){ continue; } } if (Weapons[A->instance].lssm_stage==3){ continue; } } if ( A->type == OBJ_SHIP ) { if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } } if(hud_target_invalid_awacs(A)){ continue; } if ( vm_vec_same( &A->pos, &Eye_position ) ) { continue; } vm_vec_normalized_dir(&vec_to_target, &A->pos, &Eye_position); dot = vm_vec_dot(&Player_obj->orient.vec.fvec, &vec_to_target); if ( dot > MIN_DOT_FOR_TARGET ) { hud_reticle_list_update(A, dot, 1); } } target_obj = hud_reticle_pick_target(); if ( target_obj != NULL ) { set_target_objnum( Player_ai, OBJ_INDEX(target_obj) ); if ( target_obj->type == OBJ_SHIP ) { // if BIG|HUGE, maybe set subsys to turret hud_maybe_set_sorted_turret_subsys(&Ships[target_obj->instance]); hud_restore_subsystem_target(&Ships[target_obj->instance]); } } else { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // hud_target_subsystem_in_reticle() will target the subsystem that is within the reticle and // is closest to the reticle center. The current target is the only object that is searched for // subsystems // // Method: take the dot product of the foward vector and the vector to target. Take // the one that is closest to 1 and at least MIN_DOT_FOR_TARGET // // IMPORTANT: The MIN_DOT_FOR_TARGET value was arrived at by trial and error and // is only valid for the HUD reticle in use at that time. // void hud_target_subsystem_in_reticle() { object* targetp; ship_subsys *subsys; ship_subsys *nearest_subsys = NULL; vec3d subobj_pos; float dot, best_dot; vec3d vec_to_target; best_dot = -1.0f; if ( Player_ai->target_objnum == -1){ hud_target_in_reticle_old(); } if ( Player_ai->target_objnum == -1) { //-V581 snd_play( &Snds[SND_TARGET_FAIL]); return; } targetp = &Objects[Player_ai->target_objnum]; if ( targetp->type != OBJ_SHIP ){ // only targeting subsystems on ship return; } int shipnum = targetp->instance; if ( targetp->type == OBJ_SHIP ) { if ( Ships[shipnum].flags & TARGET_SHIP_IGNORE_FLAGS ) { return; } } for (subsys = GET_FIRST(&Ships[shipnum].subsys_list); subsys != END_OF_LIST(&Ships[shipnum].subsys_list) ; subsys = GET_NEXT( subsys ) ) { //if the subsystem isn't targetable, skip it if (subsys->flags & SSF_UNTARGETABLE) continue; get_subsystem_world_pos(targetp, subsys, &subobj_pos); vm_vec_normalized_dir(&vec_to_target, &subobj_pos, &Eye_position); dot = vm_vec_dot(&Player_obj->orient.vec.fvec, &vec_to_target); if ( dot > best_dot ) { best_dot = dot; if ( best_dot > MIN_DOT_FOR_TARGET ) nearest_subsys = subsys; } Assert(best_dot <= 1.0f); } // end for if ( nearest_subsys != NULL ) { set_targeted_subsys(Player_ai, nearest_subsys, Player_ai->target_objnum); char r_name[NAME_LENGTH]; int i; strcpy_s(r_name, ship_subsys_get_name(Player_ai->targeted_subsys)); for (i = 0; r_name[i] > 0; i++) { if (r_name[i] == '|') r_name[i] = ' '; } HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Targeting subsystem %s.", 323), r_name); Ships[shipnum].last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } else { snd_play( &Snds[SND_TARGET_FAIL]); } } #define T_LENGTH 8 #define T_OFFSET_FROM_CIRCLE -13 #define T_BASE_LENGTH 4 // On entry: // color set void HudGaugeOrientationTee::renderOrientation(object *from_objp, object *to_objp, matrix *from_orientp) { float dot_product; vec3d target_to_obj; float x1,y1,x2,y2,x3,y3,x4,y4; vm_vec_sub(&target_to_obj, &from_objp->pos, &to_objp->pos); vm_vec_normalize(&target_to_obj); // calculate the dot product between the target_to_player vector and the targets forward vector // // 0 - vectors are perpendicular // 1 - vectors are collinear and in the same direction (target is facing player) // -1 - vectors are collinear and in the opposite direction (target is facing away from player) dot_product = vm_vec_dotprod(&from_orientp->vec.fvec, &target_to_obj); if (vm_vec_dotprod(&from_orientp->vec.rvec, &target_to_obj) >= 0) { if (dot_product >= 0){ dot_product = -PI_2*dot_product + PI; } else { dot_product = -PI_2*dot_product - PI; } } else { dot_product *= PI_2; //(range is now -PI/2 => PI/2) } y1 = (float)sin(dot_product) * (Radius - T_OFFSET_FROM_CIRCLE); x1 = (float)cos(dot_product) * (Radius - T_OFFSET_FROM_CIRCLE); y1 += position[1]; x1 += position[0]; x1 += HUD_offset_x; y1 += HUD_offset_y; y2 = (float)sin(dot_product) * (Radius - T_OFFSET_FROM_CIRCLE - T_LENGTH); x2 = (float)cos(dot_product) * (Radius - T_OFFSET_FROM_CIRCLE - T_LENGTH); y2 += position[1]; x2 += position[0]; x2 += HUD_offset_x; y2 += HUD_offset_y; x3 = x1 - T_BASE_LENGTH * (float)sin(dot_product); y3 = y1 + T_BASE_LENGTH * (float)cos(dot_product); x4 = x1 + T_BASE_LENGTH * (float)sin(dot_product); y4 = y1 - T_BASE_LENGTH * (float)cos(dot_product); // HACK! Should be antialiased! renderLine(fl2i(x3),fl2i(y3),fl2i(x4),fl2i(y4)); // bottom of T renderLine(fl2i(x1),fl2i(y1),fl2i(x2),fl2i(y2)); // part of T pointing towards center } void hud_tri(float x1,float y1,float x2,float y2,float x3,float y3) { int i; // Make the triangle always be the correct handiness so // the tmapper won't think its back-facing and throw it out. float det = (y2-y1)*(x3-x1) - (x2-x1)*(y3-y1); if ( det >= 0.0f ) { float tmp; // swap y1 & y3 tmp = y1; y1 = y3; y3 = tmp; // swap x1 & x3 tmp = x1; x1 = x3; x3 = tmp; } vertex * vertlist[3]; vertex verts[3]; // zero verts[] out, this is a faster way (nods to Kazan) to make sure that // the specular colors are set to 0 to avoid rendering problems - taylor memset(verts, 0, sizeof(vertex)*3); for (i=0; i<3; i++ ) vertlist[i] = &verts[i]; verts[0].screen.xyw.x = x1; verts[0].screen.xyw.y = y1; verts[0].screen.xyw.w = 0.0f; verts[0].texture_position.u = 0.0f; verts[0].texture_position.v = 0.0f; verts[0].flags = PF_PROJECTED; verts[0].codes = 0; verts[0].r = (ubyte)gr_screen.current_color.red; verts[0].g = (ubyte)gr_screen.current_color.green; verts[0].b = (ubyte)gr_screen.current_color.blue; verts[0].a = (ubyte)gr_screen.current_color.alpha; verts[1].screen.xyw.x = x2; verts[1].screen.xyw.y = y2; verts[1].screen.xyw.w = 0.0f; verts[1].texture_position.u = 0.0f; verts[1].texture_position.v = 0.0f; verts[1].flags = PF_PROJECTED; verts[1].codes = 0; verts[1].r = (ubyte)gr_screen.current_color.red; verts[1].g = (ubyte)gr_screen.current_color.green; verts[1].b = (ubyte)gr_screen.current_color.blue; verts[1].a = (ubyte)gr_screen.current_color.alpha; verts[2].screen.xyw.x = x3; verts[2].screen.xyw.y = y3; verts[2].screen.xyw.w = 0.0f; verts[2].texture_position.u = 0.0f; verts[2].texture_position.v = 0.0f; verts[2].flags = PF_PROJECTED; verts[2].codes = 0; verts[2].r = (ubyte)gr_screen.current_color.red; verts[2].g = (ubyte)gr_screen.current_color.green; verts[2].b = (ubyte)gr_screen.current_color.blue; verts[2].a = (ubyte)gr_screen.current_color.alpha; for (i=0; i<3; i++) gr_resize_screen_posf(&verts[i].screen.xyw.x, &verts[i].screen.xyw.y); uint saved_mode = gr_zbuffer_get(); int cull = gr_set_cull(0); gr_zbuffer_set( GR_ZBUFF_NONE ); //gr_tmapper( 3, vertlist, TMAP_FLAG_TRILIST ); g3_draw_poly_constant_sw(3, vertlist, TMAP_FLAG_GOURAUD | TMAP_FLAG_RGB | TMAP_FLAG_ALPHA, 0.1f); gr_zbuffer_set( saved_mode ); gr_set_cull(cull); } void hud_tri_empty(float x1,float y1,float x2,float y2,float x3,float y3) { gr_line(fl2i(x1),fl2i(y1),fl2i(x2),fl2i(y2)); gr_line(fl2i(x2),fl2i(y2),fl2i(x3),fl2i(y3)); gr_line(fl2i(x3),fl2i(y3),fl2i(x1),fl2i(y1)); } HudGaugeReticleTriangle::HudGaugeReticleTriangle(): HudGauge(HUD_OBJECT_HOSTILE_TRI, HUD_HOSTILE_TRIANGLE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } HudGaugeReticleTriangle::HudGaugeReticleTriangle(int _gauge_object, int _gauge_config): HudGauge(_gauge_object, _gauge_config, true, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeReticleTriangle::initRadius(int length) { Radius = length; } void HudGaugeReticleTriangle::initTriBase(float length) { Target_triangle_base = length; } void HudGaugeReticleTriangle::initTriHeight(float h) { Target_triangle_height = h; } void HudGaugeReticleTriangle::render(float frametime) { } // Render a missile warning triangle that has a tail on it to indicate distance void HudGaugeReticleTriangle::renderTriangleMissileTail(float ang, float xpos, float ypos, float cur_dist, int draw_solid, int draw_inside) { float x1=0.0f; float x2=0.0f; float y1=0.0f; float y2=0.0f; float xtail=0.0f; float ytail=0.0f; float sin_ang, cos_ang, tail_len; float max_tail_len=20.0f; sin_ang=(float)sin(ang); cos_ang=(float)cos(ang); if ( cur_dist < Min_warning_missile_dist ) { tail_len = 0.0f; } else if ( cur_dist > Max_warning_missile_dist ) { tail_len = max_tail_len; } else { tail_len = cur_dist/Max_warning_missile_dist * max_tail_len; } if ( draw_inside ) { x1 = xpos - Target_triangle_base * -sin_ang; y1 = ypos + Target_triangle_base * cos_ang; x2 = xpos + Target_triangle_base * -sin_ang; y2 = ypos - Target_triangle_base * cos_ang; xpos -= Target_triangle_height * cos_ang; ypos += Target_triangle_height * sin_ang; if ( tail_len > 0 ) { xtail = xpos - tail_len * cos_ang; ytail = ypos + tail_len * sin_ang; } } else { x1 = xpos - Target_triangle_base * -sin_ang; y1 = ypos + Target_triangle_base * cos_ang; x2 = xpos + Target_triangle_base * -sin_ang; y2 = ypos - Target_triangle_base * cos_ang; xpos += Target_triangle_height * cos_ang; ypos -= Target_triangle_height * sin_ang; if ( tail_len > 0 ) { xtail = xpos + tail_len * cos_ang; ytail = ypos - tail_len * sin_ang; } } gr_set_screen_scale(base_w, base_h); if (draw_solid) { hud_tri(xpos,ypos,x1,y1,x2,y2); } else { hud_tri_empty(xpos,ypos,x1,y1,x2,y2); } // draw the tail indicating length if ( tail_len > 0 ) { gr_line(fl2i(xpos), fl2i(ypos), fl2i(xtail), fl2i(ytail)); } gr_reset_screen_scale(); } // Render a triangle on the outside of the targeting circle. // Must be inside a g3_start_frame(). // If aspect_flag !0, then render filled, indicating aspect lock. // If show_interior !0, then point inwards to positions inside reticle void HudGaugeReticleTriangle::renderTriangle(vec3d *hostile_pos, int aspect_flag, int show_interior, int split_tri) { vertex hostile_vertex; float ang; float xpos,ypos,cur_dist,sin_ang,cos_ang; int draw_inside=0; // determine if the given object is within the targeting reticle // (which means the triangle is not drawn) cur_dist = vm_vec_dist_quick(&Player_obj->pos, hostile_pos); g3_rotate_vertex(&hostile_vertex, hostile_pos); g3_project_vertex(&hostile_vertex); if (hostile_vertex.codes == 0) { // on screen int projected_x, projected_y; if (!(hostile_vertex.flags & PF_OVERFLOW)) { // make sure point projected int mag_squared; projected_x = fl2i(hostile_vertex.screen.xyw.x); projected_y = fl2i(hostile_vertex.screen.xyw.y); unsize(&projected_x, &projected_y); mag_squared = (projected_x - position[0]) * (projected_x - position[0]) + (projected_y - position[1]) * (projected_y - position[1]); if ( mag_squared < Radius*Radius ) { if ( show_interior ) { draw_inside=1; } else { return; } } } } int HUD_nose_scaled_x = HUD_nose_x; int HUD_nose_scaled_y = HUD_nose_y; gr_resize_screen_pos(&HUD_nose_scaled_x, &HUD_nose_scaled_y); unsize( &hostile_vertex.world.xyz.x, &hostile_vertex.world.xyz.y ); ang = atan2_safe(hostile_vertex.world.xyz.y,hostile_vertex.world.xyz.x); sin_ang=(float)sin(ang); cos_ang=(float)cos(ang); if ( draw_inside ) { xpos = position[0] + cos_ang*(Radius-7); ypos = position[1] - sin_ang*(Radius-7); } else { xpos = position[0] + cos_ang*(Radius+4); ypos = position[1] - sin_ang*(Radius+4); } xpos += HUD_offset_x + HUD_nose_x; ypos += HUD_offset_y + HUD_nose_y; if ( split_tri ) { // renderTriangleMissileSplit(ang, xpos, ypos, cur_dist, aspect_flag, draw_inside); renderTriangleMissileTail(ang, xpos, ypos, cur_dist, aspect_flag, draw_inside); } else { float x1=0.0f; float x2=0.0f; float y1=0.0f; float y2=0.0f; if ( draw_inside ) { x1 = xpos - Target_triangle_base * -sin_ang; y1 = ypos + Target_triangle_base * cos_ang; x2 = xpos + Target_triangle_base * -sin_ang; y2 = ypos - Target_triangle_base * cos_ang; xpos -= Target_triangle_height * cos_ang; ypos += Target_triangle_height * sin_ang; } else { x1 = xpos - Target_triangle_base * -sin_ang; y1 = ypos + Target_triangle_base * cos_ang; x2 = xpos + Target_triangle_base * -sin_ang; y2 = ypos - Target_triangle_base * cos_ang; xpos += Target_triangle_height * cos_ang; ypos -= Target_triangle_height * sin_ang; } //renderPrintf(position[0], position[1], "%d", fl2i((360*ang)/(2*PI))); gr_set_screen_scale(base_w, base_h); if (aspect_flag) { hud_tri(xpos,ypos,x1,y1,x2,y2); } else { hud_tri_empty(xpos,ypos,x1,y1,x2,y2); } gr_reset_screen_scale(); } } // Show all homing missiles locked onto the player. // Also, play the beep! void hud_process_homing_missiles() { object *A; missile_obj *mo; weapon *wp; float dist, nearest_dist; int closest_is_aspect=0; nearest_dist = Homing_beep.max_cycle_dist; for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { A = &Objects[mo->objnum]; Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; if (wp->homing_object == Player_obj) { dist = vm_vec_dist_quick(&A->pos, &Player_obj->pos); if (dist < nearest_dist) { nearest_dist = dist; if ( Weapon_info[wp->weapon_info_index].wi_flags & WIF_LOCKED_HOMING ) { closest_is_aspect=1; } else { closest_is_aspect=0; } } } } // See if need to play warning beep. if (nearest_dist < Homing_beep.max_cycle_dist ) { float delta_time; float cycle_time; delta_time = f2fl(Missiontime - Homing_beep.last_time_played); // figure out the cycle time by doing a linear interpretation cycle_time = Homing_beep.min_cycle_time + (nearest_dist-Homing_beep.min_cycle_dist) * Homing_beep.precalced_interp; // play a new 'beep' if cycle time has elapsed if ( (delta_time*1000) > cycle_time ) { Homing_beep.last_time_played = Missiontime; if ( snd_is_playing(Homing_beep.snd_handle) ) { snd_stop(Homing_beep.snd_handle); } if ( closest_is_aspect ) { Homing_beep.snd_handle = snd_play(&Snds[ship_get_sound(Player_obj, SND_PROXIMITY_ASPECT_WARNING)]); } else { Homing_beep.snd_handle = snd_play(&Snds[ship_get_sound(Player_obj, SND_PROXIMITY_WARNING)]); } } } } HudGaugeMissileTriangles::HudGaugeMissileTriangles(): HudGaugeReticleTriangle(HUD_OBJECT_MISSILE_TRI, HUD_MISSILE_WARNING_ARROW) { } void HudGaugeMissileTriangles::render(float frametime) { object *A; missile_obj *mo; weapon *wp; bool in_frame = g3_in_frame() > 0; if(!in_frame) g3_start_frame(0); gr_set_screen_scale(base_w, base_h); gr_set_color_fast(&HUD_color_homing_indicator); for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { A = &Objects[mo->objnum]; Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; if (wp->homing_object == Player_obj) { renderTriangle(&A->pos, Weapon_info[wp->weapon_info_index].wi_flags & WIF_LOCKED_HOMING, 1, 1); } } gr_reset_screen_scale(); if(!in_frame) g3_end_frame(); } HudGaugeOrientationTee::HudGaugeOrientationTee(): HudGauge(HUD_OBJECT_ORIENTATION_TEE, HUD_ORIENTATION_TEE, true, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeOrientationTee::initRadius(int length) { Radius = length; } void HudGaugeOrientationTee::pageIn() { } // hud_show_orientation_tee() will draw the orientation gauge that orbits the inside of the // outer reticle ring. If the T is at 12 o'clock, the target is facing the player, if the T // is at 6 o'clock the target is facing away from the player. If the T is at 3 or 9 o'clock // the target is facing 90 away from the player. void HudGaugeOrientationTee::render(float frametime) { object* targetp; if (Player_ai->target_objnum == -1 || Player->target_is_dying) return; targetp = &Objects[Player_ai->target_objnum]; if ( maybeFlashSexp() == 1 ) { hud_set_iff_color( targetp ); } else { hud_set_iff_color( targetp, 1); } renderOrientation(targetp, Player_obj, &targetp->orient); } // routine to draw a bounding box around a remote detonate missile and distance to void hud_process_remote_detonate_missile() { missile_obj *mo; object *mobjp; vertex target_point; // check for currently locked missiles (highest precedence) for ( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); mobjp = &Objects[mo->objnum]; if ((Player_obj != NULL) && (mobjp->parent_sig == Player_obj->parent_sig)) { if (Weapon_info[Weapons[mobjp->instance].weapon_info_index].wi_flags & WIF_REMOTE) { // get box center point g3_rotate_vertex(&target_point,&mobjp->pos); // project vertex g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected switch ( mobjp->type ) { case OBJ_WEAPON: hud_target_add_display_list(mobjp, &target_point, &mobjp->pos, 0, iff_get_color(IFF_COLOR_MESSAGE, 1), NULL, TARGET_DISPLAY_DIST); break; default: Int3(); // should never happen return; } // do only for the first remote detonate missile break; } } } } } // routine to possibly draw a bounding box around a ship sending a message to the player void hud_show_message_sender() { object *targetp; vertex target_point; // temp vertex used to find screen position for 3-D object; // don't draw brackets if no ship sending a message if ( Message_shipnum == -1 ) return; targetp = &Objects[Ships[Message_shipnum].objnum]; Assert ( targetp != NULL ); Assert ( targetp->type == OBJ_SHIP ); // Don't do this for the ship you're flying! if ( targetp == Player_obj ) { return; } // Goober5000 - don't draw if primitive sensors if ( Ships[Player_obj->instance].flags2 & SF2_PRIMITIVE_SENSORS ) { return; } // Karajorma - If we've gone to all the trouble to make our friendly ships stealthed they shouldn't then give away // their position cause they're feeling chatty if ( Ships[Message_shipnum].flags2 & SF2_FRIENDLY_STEALTH_INVIS ) { return; } Assert ( targetp->instance >=0 && targetp->instance < MAX_SHIPS ); // check the object flags to see if this ship is gone. If so, then don't do this stuff anymore if ( targetp->flags & OF_SHOULD_BE_DEAD ) { Message_shipnum = -1; return; } // find the current target vertex g3_rotate_vertex(&target_point, &targetp->pos); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected hud_target_add_display_list(targetp, &target_point, &targetp->pos, 10, iff_get_color(IFF_COLOR_MESSAGE, 1), NULL, 0); } else if (target_point.codes != 0) { // target center is not on screen // draw the offscreen indicator at the edge of the screen where the target is closest to // AL 11-19-97: only show offscreen indicator if player sensors are functioning if ( (OBJ_INDEX(targetp) != Player_ai->target_objnum) || (Message_shipnum == Objects[Player_ai->target_objnum].instance) ) { if ( hud_sensors_ok(Player_ship, 0) ) { hud_target_add_display_list(targetp, &target_point, &targetp->pos, 0, iff_get_color(IFF_COLOR_MESSAGE, 1), NULL, TARGET_DISPLAY_DIST); } } } } // hud_prune_hotkeys() // // Check for ships that are dying, departed or dead. These should be removed from the player's // hotkey lists. void hud_prune_hotkeys() { int i; htarget_list *hitem, *plist; object *objp; ship *sp; for ( i = 0; i < MAX_KEYED_TARGETS; i++ ) { plist = &(Players[Player_num].keyed_targets[i]); if ( EMPTY( plist ) ) // no items in list, then do nothing continue; hitem = GET_FIRST(plist); while ( hitem != END_OF_LIST(plist) ) { int remove_item; remove_item = 0; objp = hitem->objp; Assert ( objp != NULL ); if ( objp->type == OBJ_SHIP ) { Assert ( objp->instance >=0 && objp->instance < MAX_SHIPS ); sp = &Ships[objp->instance]; } else { // if the object isn't a ship, it shouldn't be on the list, so remove it without question remove_item = 1; sp = NULL; } // check to see if the object is dying -- if so, remove it from the list // check to see if the ship is departing -- if so, remove it from the list if ( remove_item || (objp->flags & OF_SHOULD_BE_DEAD) || (sp->flags & (SF_DEPARTING|SF_DYING)) ) { if ( sp != NULL ) { nprintf(("Network", "Hotkey: Pruning %s\n", sp->ship_name)); } htarget_list *temp; temp = GET_NEXT(hitem); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; hitem = temp; continue; } hitem = GET_NEXT( hitem ); } // end while } // end for // save the hotkey sets with mission time reaches a certain point. Code was put here because this // function always called for both single/multiplayer. Maybe not the best location, but whatever. mission_hotkey_maybe_save_sets(); } int HUD_drew_selection_bracket_on_target; // hud_show_selection_set draws some indicator around all the ships in the current selection set. No // indicators will be drawn if there is only 1 ship in the set. void hud_show_selection_set() { htarget_list *hitem, *plist; object *targetp; int set, count; vertex target_point; // temp vertex used to find screen position for 3-D object; HUD_drew_selection_bracket_on_target = 0; set = Players[Player_num].current_hotkey_set; if ( set == -1 ) return; Assert ( (set >= 0) && (set < MAX_KEYED_TARGETS) ); plist = &(Players[Player_num].keyed_targets[set]); count = 0; for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) count++; if ( count == 0 ) { // only one ship, do nothing Players[Player_num].current_hotkey_set = -1; return; } for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { targetp = hitem->objp; Assert ( targetp != NULL ); ship *target_shipp = NULL; Assert ( targetp->type == OBJ_SHIP ); Assert ( targetp->instance >=0 && targetp->instance < MAX_SHIPS ); target_shipp = &Ships[targetp->instance]; if ( (Game_mode & GM_MULTIPLAYER) && (target_shipp == Player_ship) ) { continue; } // Goober5000 - don't draw indicators for non-visible ships, per Mantis #1972 // (the only way we could get here is if the hotkey set contained a mix of visible // and invisible ships) if (awacs_get_level(targetp, Player_ship, 1) < 1) { continue; } // find the current target vertex // g3_rotate_vertex(&target_point,&targetp->pos); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected switch ( targetp->type ) { case OBJ_SHIP: break; default: Int3(); // should never happen return; } if ( OBJ_INDEX(targetp) == Player_ai->target_objnum ) { hud_target_add_display_list(targetp, &target_point, &targetp->pos, 5, iff_get_color(IFF_COLOR_SELECTION, 1), NULL, 0); HUD_drew_selection_bracket_on_target = 1; } else if ( Cmdline_targetinfo ) { //Backslash -- show the distance and a lead indicator hud_target_add_display_list(targetp, &target_point, &targetp->pos, 5, iff_get_color(IFF_COLOR_SELECTION, 1), NULL, TARGET_DISPLAY_DIST | TARGET_DISPLAY_LEAD); } else { hud_target_add_display_list(targetp, &target_point, &targetp->pos, 5, iff_get_color(IFF_COLOR_SELECTION, 1), NULL, 0); } } if (target_point.codes != 0) { // target center is not on screen // draw the offscreen indicator at the edge of the screen where the target is closest to // AL 11-19-97: only show offscreen indicator if player sensors are functioning if ( OBJ_INDEX(targetp) != Player_ai->target_objnum ) { if ( hud_sensors_ok(Player_ship, 0) ) { hud_target_add_display_list(targetp, &target_point, &targetp->pos, 5, iff_get_color(IFF_COLOR_SELECTION, 1), NULL, 0); } } } } } // hud_show_targeting_gauges() will display the targeting information on the HUD. Called once per frame. // // Must be inside a g3_start_frame() // input: frametime => time in seconds since last update // in_cockpit => flag (default value 1) indicating whether viewpoint is from cockpit or external void hud_show_targeting_gauges(float frametime) { vertex target_point; // temp vertex used to find screen position for 3-D object; vec3d target_pos; hud_show_hostile_triangle(); if (Player_ai->target_objnum == -1) return; object * targetp = &Objects[Player_ai->target_objnum]; Players[Player_num].lead_indicator_active = 0; // check to see if there is even a current target if ( targetp == &obj_used_list ) { return; } // AL 1/20/97: Point to targted subsystem if one exists if ( Player_ai->targeted_subsys != NULL ) { get_subsystem_world_pos(targetp, Player_ai->targeted_subsys, &target_pos); } else { target_pos = targetp->pos; } // find the current target vertex // // The 2D screen pos depends on the current viewer position and orientation. g3_rotate_vertex(&target_point,&target_pos); hud_set_iff_color( targetp, 1 ); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected if (target_point.codes == 0) { // target center is not on screen int target_display_flags; if(Cmdline_targetinfo) { target_display_flags = TARGET_DISPLAY_DIST | TARGET_DISPLAY_DOTS | TARGET_DISPLAY_SUBSYS | TARGET_DISPLAY_NAME | TARGET_DISPLAY_CLASS; } else { target_display_flags = TARGET_DISPLAY_DIST | TARGET_DISPLAY_DOTS | TARGET_DISPLAY_SUBSYS; } hud_target_add_display_list(targetp, &target_point, &targetp->pos, 0, NULL, NULL, target_display_flags); } } else { Hud_target_w = 0; Hud_target_h = 0; } // update cargo scanning hud_cargo_scan_update(targetp, frametime); // display the lock indicator if (!Player->target_is_dying) { hud_do_lock_indicator(frametime); // update and render artillery hud_artillery_update(); hud_artillery_render(); } if (target_point.codes != 0) { // draw the offscreen indicator at the edge of the screen where the target is closest to Assert(Player_ai->target_objnum >= 0); // AL 11-11-97: don't draw the indicator if the ship is messaging, the indicator is drawn // in the message sending color in hud_show_message_sender() if ( Message_shipnum != Objects[Player_ai->target_objnum].instance ) { hud_target_add_display_list(targetp, &target_point, &targetp->pos, 0, NULL, NULL, 0); } } } // hud_show_hostile_triangle() will draw an empty triangle that oribits around the outer // circle of the reticle. It will point to the closest enemy that is firing on the player. // Currently, it points to the closest enemy that has the player as its target_objnum and has // SM_ATTACK or SM_SUPER_ATTACK as its ai submode. void hud_show_hostile_triangle() { object* A; float min_distance=1e20f; float new_distance=0.0f; object* nearest_obj = &obj_used_list; ai_info *aip; ship_obj *so; ship *sp; ship_subsys *ss; int player_obj_index = OBJ_INDEX(Player_obj); int turret_is_attacking = 0; hostile_obj = NULL; for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; sp = &Ships[A->instance]; // only look at ships who attack us if ( (A == Player_obj) || !(iff_x_attacks_y(Ships[A->instance].team, Player_ship->team)) ) { continue; } aip = &Ai_info[Ships[A->instance].ai_index]; // don't look at ignore ships if ( sp->flags & TARGET_SHIP_IGNORE_FLAGS ) { continue; } // always ignore cargo containers and navbuoys if ( Ship_info[sp->ship_info_index].class_type > -1 && !(Ship_types[Ship_info[sp->ship_info_index].class_type].hud_bools & STI_HUD_SHOW_ATTACK_DIRECTION) ) { continue; } // check if ship is stealthy if (awacs_get_level(&Objects[sp->objnum], Player_ship, 1) < 1) { continue; } turret_is_attacking = 0; // check if any turrets on ship are firing at the player (only on non fighter-bombers) if ( !(Ship_info[sp->ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ) { for (ss = GET_FIRST(&sp->subsys_list); ss != END_OF_LIST(&sp->subsys_list); ss = GET_NEXT(ss) ) { if (ss->flags & SSF_UNTARGETABLE) continue; if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { if ( ss->turret_enemy_objnum == player_obj_index ) { turret_is_attacking = 1; vec3d gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &A->orient); vm_vec_add2(&gsubpos, &A->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } } } } if ( !turret_is_attacking ) { // check for ships attacking the player if ( aip->target_objnum != Player_ship->objnum ) { continue; } // ignore enemy if not in chase mode if ( (Game_mode & GM_NORMAL) && (aip->mode != AIM_CHASE) ) { continue; } new_distance = vm_vec_dist_quick(&A->pos, &Player_obj->pos); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } } if ( nearest_obj == &obj_used_list ) { return; } if ( min_distance > MIN_DISTANCE_TO_CONSIDER_THREAT ) { return; } hostile_obj = nearest_obj; // hook to maybe warn player about this attacking ship ship_maybe_warn_player(&Ships[nearest_obj->instance], min_distance); } HudGaugeHostileTriangle::HudGaugeHostileTriangle(): HudGaugeReticleTriangle(HUD_OBJECT_HOSTILE_TRI, HUD_HOSTILE_TRIANGLE) { } void HudGaugeHostileTriangle::render(float frametime) { if (hostile_obj && maybeFlashSexp() != 1) { bool in_frame = g3_in_frame() > 0; if(!in_frame) g3_start_frame(0); // hud_set_iff_color( TEAM_HOSTILE, 1 ); // Note: This should really be TEAM_HOSTILE, not opposite of Player_ship->team. hud_set_iff_color( hostile_obj, 1 ); renderTriangle(&hostile_obj->pos, 0, 1, 0); if(!in_frame) g3_end_frame(); } } void hud_calculate_lead_pos(vec3d *lead_target_pos, vec3d *target_pos, object *targetp, weapon_info *wip, float dist_to_target, vec3d *rel_pos) { vec3d target_moving_direction; vec3d last_delta_vector; float time_to_target, target_moved_dist; if(wip->max_speed != 0) { time_to_target = dist_to_target / wip->max_speed; } else { time_to_target = 0; } target_moved_dist = targetp->phys_info.speed * time_to_target; target_moving_direction = targetp->phys_info.vel; if(The_mission.ai_profile->flags & AIPF_USE_ADDITIVE_WEAPON_VELOCITY) vm_vec_sub2(&target_moving_direction, &Player_obj->phys_info.vel); // test if the target is moving at all if ( vm_vec_mag_quick(&target_moving_direction) < 0.1f ) { // Find distance! *lead_target_pos = *target_pos; } else { vm_vec_normalize(&target_moving_direction); vm_vec_scale(&target_moving_direction, target_moved_dist); vm_vec_add(lead_target_pos, target_pos, &target_moving_direction ); polish_predicted_target_pos(wip, targetp, target_pos, lead_target_pos, dist_to_target, &last_delta_vector, 1); // Not used:, float time_to_enemy) if(rel_pos) { // needed for quick lead indicators, not needed for normal lead indicators. vm_vec_add2(lead_target_pos, rel_pos); } } } // Return the bank number for the primary weapon that can fire the farthest, from // the number of active primary weapons // input: range => output parameter... it is the range of the selected bank int hud_get_best_primary_bank(float *range) { int i, best_bank, bank_to_fire, num_to_test; float weapon_range, farthest_weapon_range; ship_weapon *swp; weapon_info *wip; swp = &Player_ship->weapons; farthest_weapon_range = 0.0f; best_bank = -1; if ( Player_ship->flags & SF_PRIMARY_LINKED ) { num_to_test = swp->num_primary_banks; } else { num_to_test = MIN(1, swp->num_primary_banks); } for ( i = 0; i < num_to_test; i++ ) { bank_to_fire = (swp->current_primary_bank + i) % swp->num_primary_banks; // calculate the range of the weapon, and only display the lead target indicator // if the weapon can actually hit the target Assert(bank_to_fire >= 0 && bank_to_fire < swp->num_primary_banks); Assert(swp->primary_bank_weapons[bank_to_fire] < MAX_WEAPON_TYPES); if (swp->primary_bank_weapons[bank_to_fire] < 0) continue; wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; weapon_range = MIN((wip->max_speed * wip->lifetime), wip->weapon_range); // don't consider this primary if it's a ballistic that's out of ammo - Goober5000 if ( wip->wi_flags2 & WIF2_BALLISTIC ) { if ( swp->primary_bank_ammo[bank_to_fire] <= 0) { continue; } } if ( weapon_range > farthest_weapon_range ) { best_bank = bank_to_fire; farthest_weapon_range = weapon_range; } } *range = farthest_weapon_range; return best_bank; } // ----------------------------------------------------------------------------- // polish_predicted_target_pos() // // Called by the draw lead indicator code to predict where the enemy is going to be // void polish_predicted_target_pos(weapon_info *wip, object *targetp, vec3d *enemy_pos, vec3d *predicted_enemy_pos, float dist_to_enemy, vec3d *last_delta_vec, int num_polish_steps) { int iteration; vec3d player_pos = Player_obj->pos; float time_to_enemy; vec3d last_predicted_enemy_pos = *predicted_enemy_pos; float weapon_speed = wip->max_speed; vm_vec_zero(last_delta_vec); // additive velocity stuff // not just the player's main target vec3d enemy_vel = targetp->phys_info.vel; if (The_mission.ai_profile->flags & AIPF_USE_ADDITIVE_WEAPON_VELOCITY) { vm_vec_sub2( &enemy_vel, &Player_obj->phys_info.vel ); } for (iteration=0; iteration < num_polish_steps; iteration++) { dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos); time_to_enemy = dist_to_enemy/weapon_speed; vm_vec_scale_add(predicted_enemy_pos, enemy_pos, &enemy_vel, time_to_enemy); vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos); last_predicted_enemy_pos= *predicted_enemy_pos; } } HudGaugeLeadIndicator::HudGaugeLeadIndicator(): HudGauge(HUD_OBJECT_LEAD, HUD_LEAD_INDICATOR, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeLeadIndicator::initHalfSize(float w, float h) { Lead_indicator_half[0] = w; Lead_indicator_half[1] = h; } void HudGaugeLeadIndicator::initBitmaps(char *fname) { Lead_indicator_gauge.first_frame = bm_load_animation(fname, &Lead_indicator_gauge.num_frames); if ( Lead_indicator_gauge.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeLeadIndicator::pageIn() { bm_page_in_aabitmap(Lead_indicator_gauge.first_frame, Lead_indicator_gauge.num_frames); } // determine the correct frame to draw for the lead indicator // 0 -> center only (in secondary range only) // 1 -> full (in secondary and primary range) // 2 -> oustide only (in primary range only) // // input: prange => range of current primary weapon // srange => range of current secondary weapon // dist_to_target => current dist to target // // exit: 0-2 => frame offset // -1 => don't draw anything int HudGaugeLeadIndicator::pickFrame(float prange, float srange, float dist_to_target) { int frame_offset=-1; int in_prange=0, in_srange=0; if ( dist_to_target < prange ) { in_prange=1; } if ( dist_to_target < srange ) { in_srange=1; } if ( in_prange && in_srange ) { frame_offset=1; } else if ( in_prange && !in_srange ) { frame_offset=2; } else if ( !in_prange && in_srange ) { frame_offset=0; } else { frame_offset=-1; } return frame_offset; } void HudGaugeLeadIndicator::render(float frametime) { if(Player->target_is_dying) { return; } bool in_frame = g3_in_frame() > 0; if(!in_frame) g3_start_frame(0); // first render the current target the player has selected. renderLeadCurrentTarget(); // if extra targeting info is enabled, render lead indicators for objects in the target display list. for(size_t i = 0; i < target_display_list.size(); i++) { if ( (target_display_list[i].flags & TARGET_DISPLAY_LEAD) && target_display_list[i].objp ) { // set the color if( target_display_list[i].bracket_clr.red && target_display_list[i].bracket_clr.green && target_display_list[i].bracket_clr.blue ) { gr_set_color_fast(&target_display_list[i].bracket_clr); } else { // use IFF colors if none defined. hud_set_iff_color(target_display_list[i].objp, 1); } renderLeadQuick(&target_display_list[i].target_pos, target_display_list[i].objp); } } if(!in_frame) g3_end_frame(); } void HudGaugeLeadIndicator::renderIndicator(int frame_offset, object *targetp, vec3d *lead_target_pos) { vertex lead_target_vertex; int sx, sy; g3_rotate_vertex(&lead_target_vertex, lead_target_pos); if (lead_target_vertex.codes == 0) { // on screen g3_project_vertex(&lead_target_vertex); if (!(lead_target_vertex.flags & PF_OVERFLOW)) { if ( maybeFlashSexp() == 1 ) { hud_set_iff_color(targetp, 0); } else { hud_set_iff_color(targetp, 1); } if ( Lead_indicator_gauge.first_frame + frame_offset >= 0 ) { sx = fl2i(lead_target_vertex.screen.xyw.x); sy = fl2i(lead_target_vertex.screen.xyw.y); unsize(&sx, &sy); renderBitmap(Lead_indicator_gauge.first_frame + frame_offset, fl2i(sx - Lead_indicator_half[0]), fl2i(sy - Lead_indicator_half[1])); } } } } // HudGaugeLeadIndicator::renderTargetLead() determine where to draw the lead target box and display it void HudGaugeLeadIndicator::renderLeadCurrentTarget() { vec3d target_pos; vec3d source_pos; vec3d *rel_pos; vec3d lead_target_pos; object *targetp; polymodel *pm; ship_weapon *swp; weapon_info *wip; weapon_info *tmp=NULL; float dist_to_target, prange, srange; int bank_to_fire, frame_offset; if (Player_ai->target_objnum == -1) return; targetp = &Objects[Player_ai->target_objnum]; if ( (targetp->type != OBJ_SHIP) && (targetp->type != OBJ_WEAPON) && (targetp->type != OBJ_ASTEROID) ) { return; } // only allow bombs to have lead indicator displayed if ( targetp->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags2 & WIF2_CAN_BE_TARGETED) ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags & WIF_BOMB) ) { return; } } } // If the target is out of range, then draw the correct frame for the lead indicator if ( Lead_indicator_gauge.first_frame == -1 ) { Int3(); return; } // AL 1/20/97: Point to targted subsystem if one exists if ( Player_ai->targeted_subsys != NULL ) { get_subsystem_world_pos(targetp, Player_ai->targeted_subsys, &target_pos); } else { target_pos = targetp->pos; } pm = model_get(Ship_info[Player_ship->ship_info_index].model_num); swp = &Player_ship->weapons; // Added to take care of situation where there are no primary banks on the player ship // (this may not be possible, depending on what we decide for the weapons loadout rules) if ( swp->num_primary_banks == 0 ) return; bank_to_fire = hud_get_best_primary_bank(&prange); if ( bank_to_fire < 0 ) return; wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; if (pm->n_guns && bank_to_fire != -1 ) { rel_pos = &pm->gun_banks[bank_to_fire].pnt[0]; } else { rel_pos = NULL; } // source_pos will contain the world coordinate of where to base the lead indicator prediction // from. Normally, this will be the world pos of the gun turret of the currently selected primary // weapon. source_pos = Player_obj->pos; if (rel_pos != NULL) { vec3d gun_point; vm_vec_unrotate(&gun_point, rel_pos, &Player_obj->orient); vm_vec_add2(&source_pos, &gun_point); } // Determine "accurate" distance to target. This is the distance from the player ship // to the closest point on the bounding box of the target dist_to_target = hud_find_target_distance(targetp, Player_obj); srange = ship_get_secondary_weapon_range(Player_ship); if ( swp->current_secondary_bank >= 0 ) { int bank = swp->current_secondary_bank; tmp = &Weapon_info[swp->secondary_bank_weapons[bank]]; if ( !(tmp->wi_flags & WIF_HOMING) && !(tmp->wi_flags & WIF_LOCKED_HOMING && Player->target_in_lock_cone) ) { //The secondary lead indicator is handled farther below if it is a non-locking type srange = -1.0f; } } frame_offset = pickFrame(prange, srange, dist_to_target); if ( frame_offset < 0 ) { return; } hud_calculate_lead_pos(&lead_target_pos, &target_pos, targetp, wip, dist_to_target); renderIndicator(frame_offset, targetp, &lead_target_pos); //do dumbfire lead indicator - color is orange (255,128,0) - bright, (192,96,0) - dim //phreak changed 9/01/02 if(swp->current_secondary_bank>=0) { int bank=swp->current_secondary_bank; wip=&Weapon_info[swp->secondary_bank_weapons[bank]]; //get out of here if the secondary weapon is a homer or if its out of range if ( wip->wi_flags & WIF_HOMING ) return; double max_dist = MIN((wip->lifetime * wip->max_speed), wip->weapon_range); if (dist_to_target > max_dist) return; } hud_calculate_lead_pos(&lead_target_pos, &target_pos, targetp, wip, dist_to_target); renderIndicator(0, targetp, &lead_target_pos); } //Backslash // A stripped-down version of the lead indicator, only shows primary weapons // and works for a specified target (not just the current selected target). // Ideally I'd like to later turn this into something (or make a new function) that would actually WORK with gun convergence/normals // instead of the existing code (copied from above) that does some calculations and then is ignored ;-) // (Go look, what's it actually DO with source_pos?) // And also, something that could be called for multiple weapons, ITTS style. void HudGaugeLeadIndicator::renderLeadQuick(vec3d *target_world_pos, object *targetp) { vec3d source_pos; vec3d *rel_pos; vec3d lead_target_pos; polymodel *pm; ship_weapon *swp; weapon_info *wip; float dist_to_target, prange; int bank_to_fire, frame_offset; if ( (targetp->type != OBJ_SHIP) && (targetp->type != OBJ_WEAPON) && (targetp->type != OBJ_ASTEROID) ) { return; } // only allow bombs to have lead indicator displayed if ( targetp->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags2 & WIF2_CAN_BE_TARGETED) ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags & WIF_BOMB) ) { return; } } } // If the target is out of range, then draw the correct frame for the lead indicator if ( Lead_indicator_gauge.first_frame == -1 ) { Int3(); return; } pm = model_get(Ship_info[Player_ship->ship_info_index].model_num); swp = &Player_ship->weapons; // Added to take care of situation where there are no primary banks on the player ship // (this may not be possible, depending on what we decide for the weapons loadout rules) if ( swp->num_primary_banks == 0 ) return; bank_to_fire = hud_get_best_primary_bank(&prange); //Backslash note: this! if ( bank_to_fire < 0 ) return; wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; if (pm->n_guns && bank_to_fire != -1 ) { rel_pos = &pm->gun_banks[bank_to_fire].pnt[0]; } else { rel_pos = NULL; } // vec3d firing_vec; // vm_vec_unrotate(&firing_vec, &po->gun_banks[bank_to_fire].norm[pt], &obj->orient); // vm_vector_2_matrix(&firing_orient, &firing_vec, NULL, NULL); // source_pos will contain the world coordinate of where to base the lead indicator prediction // from. Normally, this will be the world pos of the gun turret of the currently selected primary // weapon. source_pos = Player_obj->pos; if (rel_pos != NULL) { vec3d gun_point; vm_vec_unrotate(&gun_point, rel_pos, &Player_obj->orient); vm_vec_add2(&source_pos, &gun_point); } // Determine "accurate" distance to target. This is the distance from the player ship // to the closest point on the bounding box of the target dist_to_target = hud_find_target_distance(targetp, Player_obj); frame_offset = pickFrame(prange, -1.0f, dist_to_target); if ( frame_offset < 0 ) { return; } hud_calculate_lead_pos(&lead_target_pos, target_world_pos, targetp, wip, dist_to_target, rel_pos); renderIndicator(frame_offset, targetp, &lead_target_pos); } HudGaugeLeadSight::HudGaugeLeadSight(): HudGauge(HUD_OBJECT_LEAD_SIGHT, HUD_LEAD_INDICATOR, true, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeLeadSight::initBitmaps(char *fname) { Lead_sight.first_frame = bm_load_animation(fname, &Lead_sight.num_frames); if ( Lead_sight.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } else { int w, h; bm_get_info(Lead_sight.first_frame, &w, &h); Lead_sight_half[0] = fl2i(w * 0.5f); Lead_sight_half[1] = fl2i(h * 0.5f); } } void HudGaugeLeadSight::renderSight(int frame_offset, vec3d *target_pos, vec3d *lead_target_pos) { vertex target_vertex; float target_sx; float target_sy; vertex lead_target_vertex; float target_lead_sx; float target_lead_sy; // first see if the lead is on screen g3_rotate_vertex(&lead_target_vertex, lead_target_pos); if (lead_target_vertex.codes != 0) return; g3_project_vertex(&lead_target_vertex); if (lead_target_vertex.flags & PF_OVERFLOW) return; target_lead_sx = lead_target_vertex.screen.xyw.x; target_lead_sy = lead_target_vertex.screen.xyw.y; // now see if the target is on screen g3_rotate_vertex(&target_vertex, target_pos); if (target_vertex.codes != 0) return; g3_project_vertex(&target_vertex); if (target_vertex.flags & PF_OVERFLOW) return; target_sx = target_vertex.screen.xyw.x; target_sy = target_vertex.screen.xyw.y; // render the lead sight if ( Lead_sight.first_frame >= 0 ) { unsize(&target_lead_sx, &target_lead_sy); unsize(&target_sx, &target_sy); float reticle_target_sx = target_sx - Lead_sight_half[0] - target_lead_sx; float reticle_target_sy = target_sy - Lead_sight_half[1] - target_lead_sy; reticle_target_sx += position[0] + 0.5f; reticle_target_sy += position[1] + 0.5f; setGaugeColor(); renderBitmap(Lead_sight.first_frame + frame_offset, fl2i(reticle_target_sx) + fl2i(HUD_offset_x), fl2i(reticle_target_sy) + fl2i(HUD_offset_y)); } } void HudGaugeLeadSight::pageIn() { bm_page_in_aabitmap(Lead_sight.first_frame, Lead_sight.num_frames); } void HudGaugeLeadSight::render(float frametime) { vec3d target_pos; vec3d source_pos; vec3d *rel_pos; vec3d lead_target_pos; object *targetp; polymodel *pm; ship_weapon *swp; weapon_info *wip; weapon_info *tmp=NULL; float dist_to_target, prange, srange; int bank_to_fire; if (Player_ai->target_objnum == -1) return; targetp = &Objects[Player_ai->target_objnum]; if ( (targetp->type != OBJ_SHIP) && (targetp->type != OBJ_WEAPON) && (targetp->type != OBJ_ASTEROID) ) { return; } // only allow bombs to have lead indicator displayed if ( targetp->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags & WIF_BOMB) ) { return; } } // If the target is out of range, then draw the correct frame for the lead indicator if ( Lead_sight.first_frame == -1 ) { Int3(); return; } // AL 1/20/97: Point to targeted subsystem if one exists if ( Player_ai->targeted_subsys != NULL ) { get_subsystem_world_pos(targetp, Player_ai->targeted_subsys, &target_pos); } else { target_pos = targetp->pos; } pm = model_get(Ship_info[Player_ship->ship_info_index].model_num); swp = &Player_ship->weapons; // Added to take care of situation where there are no primary banks on the player ship // (this may not be possible, depending on what we decide for the weapons loadout rules) if ( swp->num_primary_banks == 0 ) return; bank_to_fire = hud_get_best_primary_bank(&prange); if ( bank_to_fire < 0 ) return; wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; if (pm->n_guns && bank_to_fire != -1 ) { rel_pos = &pm->gun_banks[bank_to_fire].pnt[0]; } else { rel_pos = NULL; } // source_pos will contain the world coordinate of where to base the lead indicator prediction // from. Normally, this will be the world pos of the gun turret of the currently selected primary // weapon. source_pos = Player_obj->pos; if (rel_pos != NULL) { vec3d gun_point; vm_vec_unrotate(&gun_point, rel_pos, &Player_obj->orient); vm_vec_add2(&source_pos, &gun_point); } // Determine "accurate" distance to target. This is the distance from the player ship // to the closest point on the bounding box of the target dist_to_target = hud_find_target_distance(targetp, Player_obj); srange = ship_get_secondary_weapon_range(Player_ship); if ( swp->current_secondary_bank >= 0 ) { int bank = swp->current_secondary_bank; tmp = &Weapon_info[swp->secondary_bank_weapons[bank]]; if ( !(tmp->wi_flags & WIF_HOMING) && !(tmp->wi_flags & WIF_LOCKED_HOMING && Player->target_in_lock_cone) ) { //The secondary lead indicator is handled farther below if it is a non-locking type srange = -1.0f; } } bool in_frame; if ( dist_to_target < prange ) { // fire it up in_frame = g3_in_frame() > 0; if(!in_frame) { g3_start_frame(0); } hud_calculate_lead_pos(&lead_target_pos, &target_pos, targetp, wip, dist_to_target); renderSight(1, &target_pos, &lead_target_pos); // render the primary weapon lead sight if(!in_frame) { g3_end_frame(); } } //do dumbfire lead indicator - color is orange (255,128,0) - bright, (192,96,0) - dim //phreak changed 9/01/02 if(swp->current_secondary_bank>=0) { int bank=swp->current_secondary_bank; wip=&Weapon_info[swp->secondary_bank_weapons[bank]]; //get out of here if the secondary weapon is a homer or if its out of range if ( wip->wi_flags & WIF_HOMING ) { return; } double max_dist = MIN((wip->lifetime * wip->max_speed), wip->weapon_range); if (dist_to_target > max_dist) { return; } } else { return; } // fire it up in_frame = g3_in_frame() > 0; if(!in_frame) { g3_start_frame(0); } //give it the "in secondary range frame hud_calculate_lead_pos(&lead_target_pos, &target_pos, targetp, wip, dist_to_target); renderSight(0, &target_pos, &lead_target_pos); // now render the secondary weapon lead sight if(!in_frame) { g3_end_frame(); } } // hud_cease_subsystem_targeting() will cease targeting the current targets subsystems // void hud_cease_subsystem_targeting(int print_message) { int ship_index; ship_index = Objects[Player_ai->target_objnum].instance; if ( ship_index < 0 ) return; Ships[ship_index].last_targeted_subobject[Player_num] = NULL; Player_ai->targeted_subsys = NULL; Player_ai->targeted_subsys_parent = -1; if ( print_message ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Deactivating sub-system targeting", 324)); } hud_stop_looped_locking_sounds(); hud_lock_reset(); } // hud_cease_targeting() will cease all targeting (main target and subsystem) // void hud_cease_targeting() { set_target_objnum( Player_ai, -1 ); Players[Player_num].flags &= ~PLAYER_FLAGS_AUTO_TARGETING; hud_cease_subsystem_targeting(0); HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Deactivating targeting system", 325)); hud_lock_reset(); } // hud_restore_subsystem_target() will remember the last targeted subsystem // on a target. // void hud_restore_subsystem_target(ship* shipp) { // check if there was a previously targeted sub-system for this target if ( shipp->last_targeted_subobject[Player_num] != NULL ) { Player_ai->targeted_subsys = shipp->last_targeted_subobject[Player_num]; Player_ai->targeted_subsys_parent = Player_ai->target_objnum; } else { Player_ai->targeted_subsys = NULL; Player_ai->targeted_subsys_parent = -1; } } // -------------------------------------------------------------------------------- // get_subsystem_world_pos() returns the world position for a given subsystem on a ship // vec3d* get_subsystem_world_pos(object* parent_obj, ship_subsys* subsys, vec3d* world_pos) { get_subsystem_pos(world_pos, parent_obj, subsys); return world_pos; } // ---------------------------------------------------------------------------- // hud_target_change_check() // // called once per frame to account for when the target changes // void hud_target_change_check() { float current_speed=0.0f; // Check if player subsystem target has changed, and reset necessary player flag if ( Player_ai->targeted_subsys != Player_ai->last_subsys_target ) { Player->subsys_in_view=-1; } // check if the main target has changed if (Player_ai->last_target != Player_ai->target_objnum) { if ( Player_ai->target_objnum != -1){ snd_play( &Snds[ship_get_sound(Player_obj, SND_TARGET_ACQUIRE)], 0.0f ); } // if we have a hotkey set active, see if new target is in set. If not in // set, deselect the current hotkey set. if ( Player->current_hotkey_set != -1 ) { htarget_list *hitem, *plist; plist = &(Player->keyed_targets[Player->current_hotkey_set]); for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( OBJ_INDEX(hitem->objp) == Player_ai->target_objnum ){ break; } } if ( hitem == END_OF_LIST(plist) ){ Player->current_hotkey_set = -1; } } player_stop_cargo_scan_sound(); hud_shield_hit_reset(); hud_targetbox_init_flash(); hud_targetbox_start_flash(TBOX_FLASH_NAME); hud_gauge_popup_start(HUD_TARGET_MINI_ICON); Player->cargo_inspect_time=0; Player->locking_subsys=NULL; Player->locking_on_center=0; Player->locking_subsys_parent=-1; Player_ai->current_target_dist_trend = NO_CHANGE; Player_ai->current_target_speed_trend = NO_CHANGE; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { Players[Player_num].flags &= ~PLAYER_FLAGS_MATCH_TARGET; // player_match_target_speed("", "", XSTR("Matching speed of newly acquired target",-1)); player_match_target_speed(); } else { if ( Players[Player_num].flags & PLAYER_FLAGS_MATCH_TARGET ) Players[Player_num].flags &= ~PLAYER_FLAGS_MATCH_TARGET; // no more target matching. } hud_lock_reset(); if ( Player_ai->target_objnum != -1) { if ( Objects[Player_ai->target_objnum].type == OBJ_SHIP ) { hud_restore_subsystem_target(&Ships[Objects[Player_ai->target_objnum].instance]); } } } else { if (Player_ai->current_target_distance < Player_ai->last_dist-0.01){ Player_ai->current_target_dist_trend = DECREASING; } else if (Player_ai->current_target_distance > Player_ai->last_dist+0.01){ Player_ai->current_target_dist_trend = INCREASING; } else { Player_ai->current_target_dist_trend = NO_CHANGE; } current_speed = Objects[Player_ai->target_objnum].phys_info.speed; if (current_speed < Player_ai->last_speed-0.01){ Player_ai->current_target_speed_trend = DECREASING; } else if (current_speed > Player_ai->last_speed+0.01) { Player_ai->current_target_speed_trend = INCREASING; } else { Player_ai->current_target_speed_trend = NO_CHANGE; } if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { if ( !(Players[Player_num].flags & PLAYER_FLAGS_MATCH_TARGET) ) { // player_match_target_speed("", "", XSTR("Matching target speed",-1)); player_match_target_speed(); } } } Player_ai->last_dist = Player_ai->current_target_distance; Player_ai->last_speed = current_speed; Player_ai->last_target = Player_ai->target_objnum; Player_ai->last_subsys_target = Player_ai->targeted_subsys; } HudGaugeTargetTriangle::HudGaugeTargetTriangle(): HudGaugeReticleTriangle(HUD_OBJECT_TARGET_TRI, HUD_TARGET_TRIANGLE) { } void HudGaugeTargetTriangle::render(float frametime) { if ( Player_ai->target_objnum == -1) return; bool in_frame = g3_in_frame() > 0; if(!in_frame) g3_start_frame(0); object *targetp = &Objects[Player_ai->target_objnum]; // draw the targeting triangle that orbits the outside of the outer circle of the reticle if (!Player->target_is_dying && maybeFlashSexp() != 1) { hud_set_iff_color(targetp, 1); renderTriangle(&targetp->pos, 1, 0, 0); } if(!in_frame) g3_end_frame(); } // start the weapon line (on the HUD) flashing void hud_start_flash_weapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } if ( timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { Weapon_flash_info.flash_next[index] = timestamp(TBOX_FLASH_INTERVAL); Weapon_flash_info.is_bright &= ~(1<<index); } Weapon_flash_info.flash_duration[index] = timestamp(TBOX_FLASH_DURATION); } // maybe change the text color for the weapon line indicated by index void hud_maybe_flash_weapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } // hud_set_default_color(); hud_set_gauge_color(HUD_WEAPONS_GAUGE); if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { if ( timestamp_elapsed(Weapon_flash_info.flash_next[index]) ) { Weapon_flash_info.flash_next[index] = timestamp(TBOX_FLASH_INTERVAL); Weapon_flash_info.is_bright ^= (1<<index); } if ( Weapon_flash_info.is_bright & (1<<index) ) { hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_BRIGHT); // hud_set_bright_color(); } else { hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_DIM); // hud_set_dim_color(); } } } /** * @brief Check if targeting is possible based on sensors strength */ int hud_sensors_ok(ship *sp, int show_msg) { float sensors_str; // If playing on lowest skill level, sensors don't affect targeting // If dead, still allow player to target, despite any subsystem damage // If i'm a multiplayer observer, allow me to target if ( (Game_skill_level == 0) || (Game_mode & GM_DEAD) || ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_OBSERVER)) ) { return 1; } // if the ship is currently being affected by EMP if(emp_active_local()){ return 0; } // ensure targeting functions are not disabled through damage sensors_str = ship_get_subsystem_strength( sp, SUBSYSTEM_SENSORS ); if ( (sensors_str < MIN_SENSOR_STR_TO_TARGET) || (ship_subsys_disrupted(sp, SUBSYSTEM_SENSORS)) ) { if ( show_msg ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Targeting is disabled due to sensors damage", 330)); snd_play(&Snds[SND_TARGET_FAIL]); } return 0; } else { return 1; } } extern bool Sexp_Messages_Scrambled; int hud_communications_state(ship *sp) { float str; // If playing on the lowest skill level, communications always ok // If dead, still allow player to communicate, despite any subsystem damage if ( Game_skill_level == 0 || (Game_mode & GM_DEAD) ) { return COMM_OK; } // Goober5000 - if the ship is the player, and he's dying, return OK (so laments can be played) if ((sp == Player_ship) && (sp->flags & SF_DYING)) return COMM_OK; // Goober5000 - check for scrambled communications if ( Sexp_Messages_Scrambled || emp_active_local() ) return COMM_SCRAMBLED; str = ship_get_subsystem_strength( sp, SUBSYSTEM_COMMUNICATION ); if ( (str <= 0.01) || ship_subsys_disrupted(sp, SUBSYSTEM_COMMUNICATION) ) { return COMM_DESTROYED; } else if ( str < MIN_COMM_STR_TO_MESSAGE ) { return COMM_DAMAGED; } return COMM_OK; } // target the next or previous hostile/friendly ship void hud_target_next_list(int hostile, int next_flag, int team_mask, int attacked_objnum, int play_fail_snd, int filter, int get_closest_turret_attacking_player) { int timestamp_val, valid_team_mask; if ( hostile ) { timestamp_val = Tl_hostile_reset_timestamp; Tl_hostile_reset_timestamp = timestamp(TL_RESET); if ( team_mask == -1 ) { valid_team_mask = iff_get_attackee_mask(Player_ship->team); } else { valid_team_mask = team_mask; } } else { // everyone hates a traitor including other traitors so the friendly target option shouldn't work for them if (Player_ship->team == Iff_traitor) { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); return; } timestamp_val = Tl_friendly_reset_timestamp; Tl_friendly_reset_timestamp = timestamp(TL_RESET); valid_team_mask = iff_get_mask(Player_ship->team); } // If no target is selected, then simply target the closest ship if ( Player_ai->target_objnum == -1 || timestamp_elapsed(timestamp_val) ) { hud_target_closest(valid_team_mask, attacked_objnum, play_fail_snd, filter, get_closest_turret_attacking_player); return; } object *nearest_object = select_next_target_by_distance((next_flag != 0), valid_team_mask, attacked_objnum); if (nearest_object != NULL) { // set new target set_target_objnum( Player_ai, OBJ_INDEX(nearest_object) ); // maybe set new turret subsystem hud_maybe_set_sorted_turret_subsys(&Ships[nearest_object->instance]); hud_restore_subsystem_target(&Ships[nearest_object->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } HudGaugeAutoTarget::HudGaugeAutoTarget(): HudGauge(HUD_OBJECT_AUTO_TARGET, HUD_AUTO_TARGET, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255) { } void HudGaugeAutoTarget::initAutoTextOffsets(int x, int y) { Auto_text_offsets[0] = x; Auto_text_offsets[1] = y; } void HudGaugeAutoTarget::initTargetTextOffsets(int x, int y) { Target_text_offsets[0] = x; Target_text_offsets[1] = y; } void HudGaugeAutoTarget::initBitmaps(char *fname) { Toggle_frame.first_frame = bm_load_animation(fname, &Toggle_frame.num_frames); if ( Toggle_frame.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeAutoTarget::initOnColor(int r, int g, int b, int a) { if ( r == -1 || g == -1 || b == -1 || a == -1 ) { Use_on_color = false; gr_init_alphacolor(&On_color, 0, 0, 0, 0); return; } Use_on_color = true; gr_init_alphacolor(&On_color, r, g, b, a); } void HudGaugeAutoTarget::initOffColor(int r, int g, int b, int a) { if ( r == -1 || g == -1 || b == -1 || a == -1 ) { Use_off_color = false; gr_init_alphacolor(&Off_color, 0, 0, 0, 0); return; } Use_off_color = true; gr_init_alphacolor(&Off_color, r, g, b, a); } void HudGaugeAutoTarget::render(float frametime) { if (Player_ship->flags2 & SF2_PRIMITIVE_SENSORS) return; int frame_offset; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_TARGETING ) { frame_offset = 1; } else { frame_offset = 0; } // draw the box background setGaugeColor(); renderBitmap(Toggle_frame.first_frame+frame_offset, position[0], position[1]); // draw the text on top if (frame_offset == 1) { //static color text_color; //gr_init_alphacolor(&text_color, 0, 0, 0, Toggle_text_alpha); if ( Use_on_color ) { gr_set_color_fast(&On_color); } } else if ( Use_off_color ) { gr_set_color_fast(&Off_color); } renderString(position[0] + Auto_text_offsets[0], position[1] + Auto_text_offsets[1], XSTR("auto", 1463)); renderString(position[0] + Target_text_offsets[0], position[1] + Target_text_offsets[1], XSTR("target", 1465)); } void HudGaugeAutoTarget::pageIn() { bm_page_in_aabitmap(Toggle_frame.first_frame, Toggle_frame.num_frames); } HudGaugeAutoSpeed::HudGaugeAutoSpeed(): HudGauge(HUD_OBJECT_AUTO_SPEED, HUD_AUTO_SPEED, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255) { } void HudGaugeAutoSpeed::initAutoTextOffsets(int x, int y) { Auto_text_offsets[0] = x; Auto_text_offsets[1] = y; } void HudGaugeAutoSpeed::initSpeedTextOffsets(int x, int y) { Speed_text_offsets[0] = x; Speed_text_offsets[1] = y; } void HudGaugeAutoSpeed::initBitmaps(char *fname) { Toggle_frame.first_frame = bm_load_animation(fname, &Toggle_frame.num_frames); if ( Toggle_frame.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeAutoSpeed::initOnColor(int r, int g, int b, int a) { if ( r == -1 || g == -1 || b == -1 || a == -1 ) { Use_on_color = false; gr_init_alphacolor(&On_color, 0, 0, 0, 0); return; } Use_on_color = true; gr_init_alphacolor(&On_color, r, g, b, a); } void HudGaugeAutoSpeed::initOffColor(int r, int g, int b, int a) { if ( r == -1 || g == -1 || b == -1 || a == -1 ) { Use_off_color = false; gr_init_alphacolor(&Off_color, 0, 0, 0, 0); return; } Use_off_color = true; gr_init_alphacolor(&Off_color, r, g, b, a); } void HudGaugeAutoSpeed::render(float frametime) { if (Player_ship->flags2 & SF2_PRIMITIVE_SENSORS) return; int frame_offset; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { frame_offset = 3; } else { frame_offset = 2; } setGaugeColor(); renderBitmap(Toggle_frame.first_frame+frame_offset, position[0], position[1]); // draw the text on top if (frame_offset == 3) { //static color text_color; //gr_init_alphacolor(&text_color, 0, 0, 0, Toggle_text_alpha); if ( Use_on_color ) { gr_set_color_fast(&On_color); } } else if ( Use_off_color ) { gr_set_color_fast(&Off_color); } renderString(position[0] + Auto_text_offsets[0], position[1] + Auto_text_offsets[1], XSTR("auto", 1463)); renderString(position[0] + Speed_text_offsets[0], position[1] + Speed_text_offsets[1], XSTR("speed", 1464)); } void HudGaugeAutoSpeed::pageIn() { bm_page_in_aabitmap(Toggle_frame.first_frame, Toggle_frame.num_frames); } // Set the player target to the closest friendly repair ship // input: goal_objnum => Try to find repair ship where aip->goal_objnum matches this // output: 1 => A repair ship was targeted // 0 => No targeting change int hud_target_closest_repair_ship(int goal_objnum) { object *A; object *nearest_obj=&obj_used_list; ship *shipp; ship_obj *so; float min_distance=1e20f; float new_distance=0.0f; int rval=0; for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information // ignore all ships that aren't repair ships if ( !(Ship_info[shipp->ship_info_index].flags & SIF_SUPPORT) ) { continue; } if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // only consider friendly ships if ( !(Player_ship->team == shipp->team)) { continue; } if(hud_target_invalid_awacs(A)){ continue; } if ( goal_objnum >= 0 ) { if ( Ai_info[shipp->ai_index].goal_objnum != goal_objnum ) { continue; } } new_distance = hud_find_target_distance(A,Player_obj); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } if (nearest_obj != &obj_used_list) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); rval=1; } else { // inform player how to get a support ship if ( goal_objnum == -1 ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "No support ships in area. Use messaging to call one in.", 332)); } rval=0; } return rval; } void hud_target_toggle_hidden_from_sensors() { if ( TARGET_SHIP_IGNORE_FLAGS & SF_HIDDEN_FROM_SENSORS ) { TARGET_SHIP_IGNORE_FLAGS &= ~SF_HIDDEN_FROM_SENSORS; HUD_sourced_printf(HUD_SOURCE_HIDDEN, NOX("Target hiding from sensors disabled")); } else { TARGET_SHIP_IGNORE_FLAGS |= SF_HIDDEN_FROM_SENSORS; HUD_sourced_printf(HUD_SOURCE_HIDDEN, NOX("Target hiding from sensors enabled")); } } // target the closest uninspected object void hud_target_closest_uninspected_object() { object *A, *nearest_obj = NULL; ship *shipp; ship_obj *so; float min_distance = 1e20f; float new_distance = 0.0f; for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ){ continue; } if(hud_target_invalid_awacs(A)){ continue; } // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } new_distance = hud_find_target_distance(A,Player_obj); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } if (nearest_obj != NULL) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL] ); } } // target the next or previous uninspected/unscanned object void hud_target_uninspected_object(int next_flag) { object *A, *min_obj, *max_obj, *nearest_obj; ship *shipp; ship_obj *so; float cur_dist, min_dist, max_dist, new_dist, nearest_dist, diff; // If no target is selected, then simply target the closest uninspected cargo if ( Player_ai->target_objnum == -1 || timestamp_elapsed(Target_next_uninspected_object_timestamp) ) { Target_next_uninspected_object_timestamp = timestamp(TL_RESET); hud_target_closest_uninspected_object(); return; } Target_next_uninspected_object_timestamp = timestamp(TL_RESET); cur_dist = hud_find_target_distance(&Objects[Player_ai->target_objnum], Player_obj); min_obj = max_obj = nearest_obj = NULL; min_dist = 1e20f; max_dist = 0.0f; if ( next_flag ) { nearest_dist = 1e20f; } else { nearest_dist = 0.0f; } for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } // don't use object if it is already a target if ( OBJ_INDEX(A) == Player_ai->target_objnum ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } new_dist = hud_find_target_distance(A, Player_obj); if (new_dist <= min_dist) { min_dist = new_dist; min_obj = A; } if (new_dist >= max_dist) { max_dist = new_dist; max_obj = A; } if ( next_flag ) { diff = new_dist - cur_dist; if ( diff > 0 ) { if ( diff < ( nearest_dist - cur_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } else { diff = cur_dist - new_dist; if ( diff > 0 ) { if ( diff < ( cur_dist - nearest_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } } if ( nearest_obj == NULL ) { if ( next_flag ) { if ( min_obj != NULL ) { nearest_obj = min_obj; } } else { if ( max_obj != NULL ) { nearest_obj = max_obj; } } } if (nearest_obj != NULL) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL] ); } } // ---------------------------------------------------------------- // // Target Last Transmission Sender code START // // ---------------------------------------------------------------- typedef struct transmit_target { int objnum; int objsig; } transmit_target; static int Transmit_target_next_slot = 0; static int Transmit_target_current_slot = -1; static int Transmit_target_reset_timer = timestamp(0); #define MAX_TRANSMIT_TARGETS 10 static transmit_target Transmit_target_list[MAX_TRANSMIT_TARGETS]; // called once per level to initialize the target last transmission sender list void hud_target_last_transmit_level_init() { int i; for ( i = 0; i < MAX_TRANSMIT_TARGETS; i++ ) { Transmit_target_list[i].objnum = -1; Transmit_target_list[i].objsig = -1; } Transmit_target_next_slot = 0; Transmit_target_current_slot = 0; Transmit_target_reset_timer = timestamp(0); } // internal function only.. used to find index for last recorded ship transmission int hud_target_last_transmit_newest() { int latest_slot; latest_slot = Transmit_target_next_slot - 1; if ( latest_slot < 0 ) { latest_slot = MAX_TRANSMIT_TARGETS - 1; } return latest_slot; } // called externally to set the player target to the last ship which sent a transmission to the player void hud_target_last_transmit() { int i; if ( Transmit_target_current_slot < 0 ) { Transmit_target_current_slot = hud_target_last_transmit_newest(); } // If timed out, then simply target the last ship to transmit if ( timestamp_elapsed(Transmit_target_reset_timer) ) { Transmit_target_current_slot = hud_target_last_transmit_newest(); } Transmit_target_reset_timer = timestamp(TL_RESET); int play_fail_sound = 1; int transmit_index = Transmit_target_current_slot; Assert(transmit_index >= 0); for ( i = 0; i < MAX_TRANSMIT_TARGETS; i++ ) { if ( Transmit_target_list[transmit_index].objnum >= 0 ) { int transmit_objnum = Transmit_target_list[transmit_index].objnum; if ( Player_ai->target_objnum == transmit_objnum ) { play_fail_sound = 0; } else { if ( Transmit_target_list[transmit_index].objsig == Objects[Transmit_target_list[transmit_index].objnum].signature ) { if ( !(Ships[Objects[transmit_objnum].instance].flags & TARGET_SHIP_IGNORE_FLAGS) ) { Transmit_target_current_slot = transmit_index-1; if ( Transmit_target_current_slot < 0 ) { Transmit_target_current_slot = MAX_TRANSMIT_TARGETS - 1; } break; } } } } transmit_index--; if ( transmit_index < 0 ) { transmit_index = MAX_TRANSMIT_TARGETS - 1; } } if ( i == MAX_TRANSMIT_TARGETS ) { if ( play_fail_sound ) { snd_play( &Snds[SND_TARGET_FAIL] ); } Transmit_target_current_slot = -1; return; } if(hud_target_invalid_awacs(&Objects[Transmit_target_list[transmit_index].objnum])){ return; } // target new ship! // Fix bug in targeting due to Alt-Y (target last ship sending transmission). // Was just bogus code in the call to hud_restore_subsystem_target(). -- MK, 9/15/99, 1:59 pm. int targeted_objnum; targeted_objnum = Transmit_target_list[transmit_index].objnum; Assert((targeted_objnum >= 0) && (targeted_objnum < MAX_OBJECTS)); if ((targeted_objnum >= 0) && (targeted_objnum < MAX_OBJECTS)) { set_target_objnum( Player_ai, Transmit_target_list[transmit_index].objnum ); hud_restore_subsystem_target(&Ships[Objects[Transmit_target_list[transmit_index].objnum].instance]); } } // called externally to add a message sender to the list void hud_target_last_transmit_add(int ship_num) { object *ship_objp; int ship_objnum; ship_objnum = Ships[ship_num].objnum; Assert(ship_objnum >= 0 && ship_objnum < MAX_OBJECTS); ship_objp = &Objects[ship_objnum]; Assert(ship_objp->type == OBJ_SHIP); // don't add ourselves to the list if (Player_obj == ship_objp) { return; } Transmit_target_list[Transmit_target_next_slot].objnum = ship_objnum; Transmit_target_list[Transmit_target_next_slot].objsig = ship_objp->signature; Transmit_target_next_slot++; if ( Transmit_target_next_slot >= MAX_TRANSMIT_TARGETS ) { Transmit_target_next_slot = 0; } } // target a random ship (useful for EMP stuff) void hud_target_random_ship() { int shipnum; int objnum; shipnum = ship_get_random_targetable_ship(); if((shipnum < 0) || (Ships[shipnum].objnum < 0)){ return; } objnum = Ships[shipnum].objnum; if((objnum >= 0) && (Player_ai != NULL) && !hud_target_invalid_awacs(&Objects[objnum])){ // never target yourself if(objnum == OBJ_INDEX(Player_obj)){ set_target_objnum(Player_ai, -1); } else { set_target_objnum(Player_ai, objnum); } } } // ---------------------------------------------------------------- // // Target Last Transmission Sender code END // // ---------------------------------------------------------------- void hudtarget_page_in() { int i; for ( i = 0; i < NUM_WEAPON_GAUGES; i++ ) { bm_page_in_aabitmap( Weapon_gauges[ballistic_hud_index][i].first_frame, Weapon_gauges[ballistic_hud_index][i].num_frames); } bm_page_in_aabitmap( New_weapon.first_frame, New_weapon.num_frames ); weapon_info* wip; for(i = 0; i < Num_weapon_types; i++) { wip = &Weapon_info[i]; if(strlen(wip->hud_filename)) { wip->hud_image_index = bm_load(wip->hud_filename); } } } void hud_stuff_ship_name(char *ship_name_text, ship *shipp) { // print ship name if ( ((Iff_info[shipp->team].flags & IFFF_WING_NAME_HIDDEN) && (shipp->wingnum != -1)) || (shipp->flags2 & SF2_HIDE_SHIP_NAME) ) { *ship_name_text = 0; } else { strcpy(ship_name_text, shipp->ship_name); // handle hash symbol end_string_at_first_hash_symbol(ship_name_text); // handle translation if (Lcl_gr) { lcl_translate_targetbox_name(ship_name_text); } } } extern char Fred_callsigns[MAX_SHIPS][NAME_LENGTH+1]; void hud_stuff_ship_callsign(char *ship_callsign_text, ship *shipp) { // only fighters and bombers have callsigns if ( !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ) { *ship_callsign_text = 0; return; } // handle multiplayer callsign if (Game_mode & GM_MULTIPLAYER) { // get a player num from the object, then get a callsign from the player structure. int pn = multi_find_player_by_object( &Objects[shipp->objnum] ); if (pn >= 0) { strcpy(ship_callsign_text, Net_players[pn].m_player->short_callsign); return; } } // try to get callsign if (Fred_running) { strcpy(ship_callsign_text, Fred_callsigns[shipp-Ships]); } else { *ship_callsign_text = 0; if (shipp->callsign_index >= 0) { mission_parse_lookup_callsign_index(shipp->callsign_index, ship_callsign_text); } } // handle hash symbol end_string_at_first_hash_symbol(ship_callsign_text); // handle translation if (Lcl_gr) { lcl_translate_targetbox_name(ship_callsign_text); } } extern char Fred_alt_names[MAX_SHIPS][NAME_LENGTH+1]; void hud_stuff_ship_class(char *ship_class_text, ship *shipp) { // try to get alt name if (Fred_running) { strcpy(ship_class_text, Fred_alt_names[shipp-Ships]); } else { *ship_class_text = 0; if (shipp->alt_type_index >= 0) { mission_parse_lookup_alt_index(shipp->alt_type_index, ship_class_text); } } // maybe get ship class if (!*ship_class_text) { strcpy(ship_class_text, (Ship_info[shipp->ship_info_index].alt_name[0]) ? Ship_info[shipp->ship_info_index].alt_name : Ship_info[shipp->ship_info_index].name); } // handle hash symbol end_string_at_first_hash_symbol(ship_class_text); // handle translation if (Lcl_gr) { lcl_translate_targetbox_name(ship_class_text); } } HudGaugeCmeasures::HudGaugeCmeasures(): HudGauge(HUD_OBJECT_CMEASURES, HUD_CMEASURE_GAUGE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeCmeasures::initCountTextOffsets(int x, int y) { Cm_text_offsets[0] = x; Cm_text_offsets[1] = y; } void HudGaugeCmeasures::initCountValueOffsets(int x, int y) { Cm_text_val_offsets[0] = x; Cm_text_val_offsets[1] = y; } void HudGaugeCmeasures::initBitmaps(char *fname) { Cmeasure_gauge.first_frame = bm_load_animation(fname, &Cmeasure_gauge.num_frames); if ( Cmeasure_gauge.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeCmeasures::pageIn() { bm_page_in_aabitmap(Cmeasure_gauge.first_frame, Cmeasure_gauge.num_frames); } void HudGaugeCmeasures::render(float frametime) { if ( Cmeasure_gauge.first_frame == -1) { Int3(); // failed to load coutermeasure gauge background return; } ship_info *sip = &Ship_info[Player_ship->ship_info_index]; if(sip->cmeasure_max < 0 || sip->cmeasure_type < 0){ return; } // hud_set_default_color(); setGaugeColor(); // blit the background renderBitmap(Cmeasure_gauge.first_frame, position[0], position[1]); // blit text renderString(position[0] + Cm_text_offsets[0], position[1] + Cm_text_offsets[1], XSTR( "cm.", 327)); if ( !Player_ship ) { Int3(); // player ship doesn't exist? return; } renderPrintf(position[0] + Cm_text_val_offsets[0], position[1] + Cm_text_val_offsets[1], NOX("%02d"), Player_ship->cmeasure_count); } HudGaugeAfterburner::HudGaugeAfterburner(): HudGauge(HUD_OBJECT_AFTERBURNER, HUD_AFTERBURNER_ENERGY, true, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255) { } void HudGaugeAfterburner::initEnergyHeight(int h) { Energy_h = h; } void HudGaugeAfterburner::initBitmaps(char *fname) { Energy_bar.first_frame = bm_load_animation(fname, &Energy_bar.num_frames); if ( Energy_bar.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } // Render the HUD afterburner energy gauge void HudGaugeAfterburner::render(float frametime) { float percent_left; int clip_h,w,h; if ( Energy_bar.first_frame == -1 ){ return; } Assert(Player_ship); if ( !(Ship_info[Player_ship->ship_info_index].flags & SIF_AFTERBURNER) ) { // Goober5000 - instead of drawing an empty burner gauge, don't draw the gauge at all return; } else { percent_left = Player_ship->afterburner_fuel/Ship_info[Player_ship->ship_info_index].afterburner_fuel_capacity; } if ( percent_left > 1 ) { percent_left = 1.0f; } clip_h = fl2i( (1.0f - percent_left) * Energy_h + 0.5f ); bm_get_info(Energy_bar.first_frame,&w,&h); setGaugeColor(); if ( clip_h > 0) { renderBitmapEx(Energy_bar.first_frame, position[0], position[1],w,clip_h,0,0); } if ( clip_h <= Energy_h ) { renderBitmapEx(Energy_bar.first_frame+1, position[0], position[1] + clip_h,w,h-clip_h,0,clip_h); } } void HudGaugeAfterburner::pageIn() { bm_page_in_aabitmap( Energy_bar.first_frame, Energy_bar.num_frames); } HudGaugeWeaponEnergy::HudGaugeWeaponEnergy(): HudGauge(HUD_OBJECT_WEAPON_ENERGY, HUD_WEAPONS_ENERGY, true, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255) { } void HudGaugeWeaponEnergy::initTextOffsets(int x, int y) { Wenergy_text_offsets[0] = x; Wenergy_text_offsets[1] = y; } void HudGaugeWeaponEnergy::initEnergyHeight(int h) { Wenergy_h = h; } void HudGaugeWeaponEnergy::initAlignments(int text_align, int armed_align) { Text_alignment = text_align; Armed_alignment = armed_align; } void HudGaugeWeaponEnergy::initArmedOffsets(int x, int y, int h, bool show) { Armed_name_offsets[0] = x; Armed_name_offsets[1] = y; Show_armed = show; Armed_name_h = h; } void HudGaugeWeaponEnergy::initAlwaysShowText(bool show_text) { Always_show_text = show_text; } void HudGaugeWeaponEnergy::initMoveText(bool move_text) { Moving_text = move_text; } void HudGaugeWeaponEnergy::initShowBallistics(bool show_ballistics) { Show_ballistic = show_ballistics; } void HudGaugeWeaponEnergy::initBitmaps(char *fname) { Energy_bar.first_frame = bm_load_animation(fname, &Energy_bar.num_frames); if ( Energy_bar.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeWeaponEnergy::pageIn() { bm_page_in_aabitmap( Energy_bar.first_frame, Energy_bar.num_frames); } void HudGaugeWeaponEnergy::render(float frametime) { int x; bool use_new_gauge = false; // Goober5000 - only check for the new gauge in case of command line + a ballistic-capable ship if (Cmdline_ballistic_gauge && Ship_info[Player_ship->ship_info_index].flags & SIF_BALLISTIC_PRIMARIES) { for(x = 0; x < Player_ship->weapons.num_primary_banks; x++) { if(Weapon_info[Player_ship->weapons.primary_bank_weapons[x]].wi_flags2 & WIF2_BALLISTIC) { use_new_gauge = true; break; } } } if(use_new_gauge) { int currentx, currenty; int y; int max_w = 100; float remaining; currentx = position[0] + 10; currenty = position[1]; if(gr_screen.max_w_unscaled == 640) { max_w = 60; } //*****ENERGY GAUGE if(Weapon_info[Player_ship->weapons.current_primary_bank].energy_consumed > 0.0f) setGaugeColor(HUD_C_BRIGHT); //Draw name renderString(currentx, currenty, "Energy"); currenty += 10; //Draw background setGaugeColor(HUD_C_DIM); renderRect(currentx, currenty, max_w, 10); //Draw gauge bar setGaugeColor(HUD_C_NORMAL); remaining = max_w * ((float)Player_ship->weapon_energy/(float)Ship_info[Player_ship->ship_info_index].max_weapon_reserve); if(remaining > 0) { setGaugeColor(HUD_C_BRIGHT); for(y = 0; y < 10; y++) { renderGradientLine(currentx, currenty + y, currentx + fl2i(remaining), currenty + y); } } currenty += 12; char shortened_name[NAME_LENGTH]; //*****BALLISTIC GAUGES for(x = 0; x < Player_ship->weapons.num_primary_banks; x++) { //Skip all pure-energy weapons if(!(Weapon_info[Player_ship->weapons.primary_bank_weapons[x]].wi_flags2 & WIF2_BALLISTIC)) continue; //Draw the weapon bright or normal depending if it's active or not. if(x == Player_ship->weapons.current_primary_bank || (Player_ship->flags & SF_PRIMARY_LINKED)) { setGaugeColor(HUD_C_BRIGHT); } else { setGaugeColor(HUD_C_NORMAL); } if(gr_screen.max_w_unscaled == 640) { gr_force_fit_string(shortened_name, NAME_LENGTH, 55); renderString(currentx, currenty, shortened_name); } else { renderString(currentx, currenty, Weapon_info[Player_ship->weapons.primary_bank_weapons[x]].name); } //Next 'line' currenty += 10; //Draw the background for the gauge setGaugeColor(HUD_C_DIM); renderRect(currentx, currenty, max_w, 10); //Reset to normal brightness setGaugeColor(HUD_C_NORMAL); //Draw the bar graph remaining = (max_w - 4) * ((float) Player_ship->weapons.primary_bank_ammo[x] / (float) Player_ship->weapons.primary_bank_start_ammo[x]); if(remaining > 0) { renderRect(currentx + 2, currenty + 2, fl2i(remaining), 6); } //Increment for next 'line' currenty += 12; } } else { float percent_left; int ballistic_ammo = 0; int max_ballistic_ammo = 0; int clip_h, w, h, i; weapon_info *wip; ship_weapon *sw; char buf[40] = ""; if ( Energy_bar.first_frame == -1 ) { return; } if ( Player_ship->weapons.num_primary_banks <= 0 ) { return; } sw = &Player_ship->weapons; // show ballistic ammunition in energy gauge if need be if ( Show_ballistic && Ship_info[Player_ship->ship_info_index].flags & SIF_BALLISTIC_PRIMARIES ) { if ( Player_ship->flags & SF_PRIMARY_LINKED ) { // go through all ballistic primaries and add up their ammunition totals and max capacities for ( i = 0; i < sw->num_primary_banks; i++ ) { // skip all pure-energy weapons if( ! ( Weapon_info[sw->primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC ) ) { continue; } ballistic_ammo += sw->primary_bank_ammo[i]; max_ballistic_ammo += sw->primary_bank_start_ammo[i]; } } else { ballistic_ammo = sw->primary_bank_ammo[sw->current_primary_bank]; max_ballistic_ammo = sw->primary_bank_start_ammo[sw->current_primary_bank]; } percent_left = i2fl(ballistic_ammo) / i2fl(max_ballistic_ammo); } else { // also leave if no energy can be stored for weapons - Goober5000 if (!ship_has_energy_weapons(Player_ship)) return; percent_left = Player_ship->weapon_energy/Ship_info[Player_ship->ship_info_index].max_weapon_reserve; if ( percent_left > 1 ) { percent_left = 1.0f; } } clip_h = fl2i( (1.0f - percent_left) * Wenergy_h + 0.5f ); if ( percent_left <= 0.3 || Show_ballistic || Always_show_text ) { int delta_y = 0, delta_x = 0; if ( percent_left < 0.1 ) { gr_set_color_fast(&Color_bright_red); } else { setGaugeColor(); } if ( Show_ballistic ) { sprintf(buf, "%d", ballistic_ammo); } else { sprintf(buf,XSTR( "%d%%", 326), fl2i(percent_left*100+0.5f)); } if ( Moving_text ) { delta_y = clip_h; } hud_num_make_mono(buf); if ( Text_alignment ) { gr_get_string_size(&w, &h, buf); delta_x = -w; } renderString(position[0] + Wenergy_text_offsets[0] + delta_x, position[1] + Wenergy_text_offsets[1] + delta_y, buf); } setGaugeColor(); // list currently armed primary banks if we have to if ( Show_armed ) { if ( Player_ship->flags & SF_PRIMARY_LINKED ) { // show all primary banks for ( i = 0; i < Player_ship->weapons.num_primary_banks; i++ ) { wip = &Weapon_info[sw->primary_bank_weapons[i]]; strcpy_s(buf, (wip->alt_name[0]) ? wip->alt_name : wip->name); if ( Armed_alignment ) { gr_get_string_size(&w, &h, buf); } else { w = 0; } renderString(position[0] + Armed_name_offsets[0] - w, position[1] + Armed_name_offsets[1] + Armed_name_h * i, buf); } } else { // just show the current armed bank i = Player_ship->weapons.current_primary_bank; wip = &Weapon_info[sw->primary_bank_weapons[i]]; strcpy_s(buf, (wip->alt_name[0]) ? wip->alt_name : wip->name); if ( Armed_alignment ) { gr_get_string_size(&w, &h, buf); } else { w = 0; } renderString(position[0] + Armed_name_offsets[0] - w, position[1] + Armed_name_offsets[1], buf); } } for ( i = 0; i < sw->num_primary_banks; i++ ) { if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[i]) ) { if ( Weapon_flash_info.is_bright & (1<<i) ) { // hud_set_bright_color(); setGaugeColor(HUD_C_BRIGHT); break; } } } bm_get_info(Energy_bar.first_frame+2,&w,&h); if ( clip_h > 0 ) { renderBitmapEx(Energy_bar.first_frame+2, position[0], position[1], w,clip_h,0,0); } if ( clip_h <= Wenergy_h ) { renderBitmapEx(Energy_bar.first_frame+3, position[0], position[1] + clip_h, w,h-clip_h,0,clip_h); } // hud_set_default_color(); } } HudGaugeWeapons::HudGaugeWeapons(): HudGauge(HUD_OBJECT_WEAPONS, HUD_WEAPONS_GAUGE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeWeapons::initTopOffsetX(int x, int x_b) { top_offset_x[0] = x; top_offset_x[1] = x_b; } void HudGaugeWeapons::initHeaderOffsets(int x, int y, int x_b, int y_b) { Weapon_header_offsets[0][0] = x; Weapon_header_offsets[0][1] = y; Weapon_header_offsets[1][0] = x_b; Weapon_header_offsets[1][1] = y_b; } void HudGaugeWeapons::initFrameOffsetX(int x, int x_b) { frame_offset_x[0] = x; frame_offset_x[1] = x_b; } void HudGaugeWeapons::initPrimaryWeaponOffsets(int link_x, int name_x, int ammo_x) { Weapon_plink_offset_x = link_x; Weapon_pname_offset_x = name_x; Weapon_pammo_offset_x = ammo_x; } void HudGaugeWeapons::initSecondaryWeaponOffsets(int ammo_x, int name_x, int reload_x, int linked_x, int unlinked_x) { Weapon_sammo_offset_x = ammo_x; Weapon_sname_offset_x = name_x; Weapon_sreload_offset_x = reload_x; Weapon_slinked_offset_x = linked_x; Weapon_sunlinked_offset_x = unlinked_x; } void HudGaugeWeapons::initStartNameOffsetsY(int p_y, int s_y) { pname_start_offset_y = p_y; sname_start_offset_y = s_y; } void HudGaugeWeapons::initPrimaryHeights(int top_h, int text_h) { top_primary_h = top_h; primary_text_h = text_h; } void HudGaugeWeapons::initSecondaryHeights(int top_h, int text_h) { top_secondary_h = top_h; secondary_text_h = text_h; } void HudGaugeWeapons::initBitmapsPrimaryTop(char *fname, char *fname_ballistic) { // load the graphics for the top portion of the weapons gauge primary_top[0].first_frame = bm_load_animation(fname, &primary_top[0].num_frames); if(primary_top[0].first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } primary_top[1].first_frame = bm_load_animation(fname_ballistic, &primary_top[1].num_frames); if(primary_top[1].first_frame < 0) { primary_top[1].first_frame = primary_top[0].first_frame; primary_top[1].num_frames = primary_top[0].num_frames; } } void HudGaugeWeapons::initBitmapsPrimaryMiddle(char *fname, char *fname_ballistic) { // load the graphics for the middle portion of the primary weapons listing primary_middle[0].first_frame = bm_load_animation(fname, &primary_middle[0].num_frames); if(primary_middle[0].first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } primary_middle[1].first_frame = bm_load_animation(fname_ballistic, &primary_middle[1].num_frames); if(primary_middle[1].first_frame < 0) { primary_middle[1].first_frame = primary_middle[0].first_frame; primary_middle[1].num_frames = primary_middle[0].num_frames; } } void HudGaugeWeapons::initBitmapsPrimaryLast(char *fname, char *fname_ballistic) { // load the graphics for the bottom portion of the primary weapons listing if there is one. // Don't bother the user if there isn't one since retail doesn't use this. primary_last[0].first_frame = bm_load_animation(fname, &primary_last[0].num_frames); primary_last[1].first_frame = bm_load_animation(fname_ballistic, &primary_last[1].num_frames); if(primary_last[1].first_frame < 0) { primary_last[1].first_frame = primary_last[0].first_frame; primary_last[1].num_frames = primary_last[0].num_frames; } } void HudGaugeWeapons::initBitmapsSecondaryTop(char *fname, char *fname_ballistic) { // top portion of the secondary weapons gauge secondary_top[0].first_frame = bm_load_animation(fname, &secondary_top[0].num_frames); if(secondary_top[0].first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } secondary_top[1].first_frame = bm_load_animation(fname_ballistic, &secondary_top[1].num_frames); if(secondary_top[1].first_frame < 0) { secondary_top[1].first_frame = secondary_top[0].first_frame; secondary_top[1].num_frames = secondary_top[0].num_frames; } } void HudGaugeWeapons::initBitmapsSecondaryMiddle(char *fname, char *fname_ballistic) { // middle portion of the secondary weapons gauge secondary_middle[0].first_frame = bm_load_animation(fname, &secondary_middle[0].num_frames); if(secondary_middle[0].first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } secondary_middle[1].first_frame = bm_load_animation(fname_ballistic, &secondary_middle[1].num_frames); if(secondary_middle[1].first_frame < 0) { secondary_middle[1].first_frame = secondary_middle[0].first_frame; secondary_middle[1].num_frames = secondary_middle[0].num_frames; } } void HudGaugeWeapons::initBitmapsSecondaryBottom(char *fname, char *fname_ballistic) { // bottom portion of the entire weapons gauge secondary_bottom[0].first_frame = bm_load_animation(fname, &secondary_bottom[0].num_frames); if(secondary_bottom[0].first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } secondary_bottom[1].first_frame = bm_load_animation(fname_ballistic, &secondary_bottom[1].num_frames); if(secondary_bottom[1].first_frame < 0) { secondary_bottom[1].first_frame = secondary_bottom[0].first_frame; secondary_bottom[1].num_frames = secondary_bottom[0].num_frames; } } void HudGaugeWeapons::pageIn() { if(primary_top[0].first_frame > -1) { bm_page_in_aabitmap(primary_top[0].first_frame,primary_top[0].num_frames); } if(primary_top[1].first_frame > -1) { bm_page_in_aabitmap(primary_top[1].first_frame,primary_top[1].num_frames); } if(primary_middle[0].first_frame > -1) { bm_page_in_aabitmap(primary_middle[0].first_frame,primary_middle[0].num_frames); } if(primary_middle[1].first_frame > -1) { bm_page_in_aabitmap(primary_middle[1].first_frame, primary_middle[1].num_frames); } if(primary_last[1].first_frame > -1) { bm_page_in_aabitmap(primary_last[1].first_frame, primary_last[1].num_frames); } if(secondary_top[0].first_frame > -1) { bm_page_in_aabitmap(secondary_top[0].first_frame, secondary_top[0].num_frames); } if(secondary_top[1].first_frame > -1) { bm_page_in_aabitmap(secondary_top[1].first_frame, secondary_top[1].num_frames); } if(secondary_middle[0].first_frame > -1) { bm_page_in_aabitmap(secondary_middle[0].first_frame, secondary_middle[0].num_frames); } if(secondary_middle[1].first_frame >-1) { bm_page_in_aabitmap(secondary_middle[0].first_frame, secondary_middle[0].num_frames); } if(secondary_bottom[0].first_frame > -1) { bm_page_in_aabitmap(secondary_bottom[0].first_frame, secondary_bottom[0].num_frames); } if(secondary_bottom[1].first_frame > -1) { bm_page_in_aabitmap(secondary_bottom[0].first_frame, secondary_bottom[0].num_frames); } } void HudGaugeWeapons::render(float frametime) { ship_weapon *sw; int np, ns; // np == num primary, ns == num secondary char name[NAME_LENGTH]; if(Player_obj->type == OBJ_OBSERVER) return; Assert(Player_obj->type == OBJ_SHIP); Assert(Player_obj->instance >= 0 && Player_obj->instance < MAX_SHIPS); sw = &Ships[Player_obj->instance].weapons; np = sw->num_primary_banks; ns = sw->num_secondary_banks; setGaugeColor(); // draw top of primary display renderBitmap(primary_top[ballistic_hud_index].first_frame, position[0] + top_offset_x[ballistic_hud_index], position[1]); // render the header of this gauge renderString(position[0] + Weapon_header_offsets[ballistic_hud_index][0], position[1] + Weapon_header_offsets[ballistic_hud_index][1], EG_WEAPON_TITLE, XSTR( "weapons", 328)); char ammo_str[32]; int i, w, h; int y = position[1] + top_primary_h; int name_y = position[1] + pname_start_offset_y; // render primaries for(i = 0; i < np; i++) { setGaugeColor(); // choose which background to draw for additional primaries. // Note, we don't draw a background for the first primary. // It is assumed that the top primary wep frame already has this rendered. if(i == 1) { // used to draw the second primary weapon background renderBitmap(primary_middle[ballistic_hud_index].first_frame, position[0] + frame_offset_x[ballistic_hud_index], y); } else if(i != 0) { // used to draw the the third, fourth, fifth, etc... if(primary_last[ballistic_hud_index].first_frame != -1) renderBitmap(primary_last[ballistic_hud_index].first_frame, position[0] + frame_offset_x[ballistic_hud_index], y); } strcpy_s(name, (Weapon_info[sw->primary_bank_weapons[i]].alt_name[0]) ? Weapon_info[sw->primary_bank_weapons[i]].alt_name : Weapon_info[sw->primary_bank_weapons[i]].name); if (Lcl_gr) { lcl_translate_wep_name(name); } // maybe modify name here to fit // do we need to flash the text? if (HudGauge::maybeFlashSexp() == i ) { setGaugeColor(HUD_C_BRIGHT); } else { maybeFlashWeapon(i); } // indicate if this is linked or currently armed if ( ((sw->current_primary_bank == i) && !(Player_ship->flags & SF_PRIMARY_LINKED)) || ((Player_ship->flags & SF_PRIMARY_LINKED) && !(Weapon_info[sw->primary_bank_weapons[i]].wi_flags3 & WIF3_NOLINK))) { renderPrintf(position[0] + Weapon_plink_offset_x, name_y, EG_NULL, "%c", Lcl_special_chars + 2); } // either render this primary's image or its name if(Weapon_info[sw->primary_bank_weapons[0]].hud_image_index != -1) { renderBitmap(Weapon_info[sw->primary_bank_weapons[i]].hud_image_index, position[0] + Weapon_pname_offset_x, name_y); } else { renderPrintf(position[0] + Weapon_pname_offset_x, name_y, EG_WEAPON_P2, "%s", name); } // if this is a ballistic primary with ammo, render the ammo count if (Weapon_info[sw->primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC) { // print out the ammo right justified sprintf(ammo_str, "%d", sw->primary_bank_ammo[i]); // get rid of # end_string_at_first_hash_symbol(ammo_str); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); renderString(position[0] + Weapon_pammo_offset_x - w, name_y, EG_NULL, ammo_str); } if(i != 0) { y += primary_text_h; } name_y += primary_text_h; } weapon_info *wip; char weapon_name[NAME_LENGTH + 10]; if ( HudGauge::maybeFlashSexp() == i ) { setGaugeColor(HUD_C_BRIGHT); } renderBitmap(secondary_top[ballistic_hud_index].first_frame, position[0] + frame_offset_x[ballistic_hud_index], y); name_y = y + sname_start_offset_y; y += top_secondary_h; for(i = 0; i < ns; i++) { setGaugeColor(); wip = &Weapon_info[sw->secondary_bank_weapons[i]]; if(i!=0) { renderBitmap(secondary_middle[ballistic_hud_index].first_frame, position[0] + frame_offset_x[ballistic_hud_index], y); } maybeFlashWeapon(np+i); // HACK - make Cluster Bomb fit on the HUD. if(!stricmp(wip->name,"cluster bomb")){ strcpy_s(weapon_name, NOX("Cluster")); } else { strcpy_s(weapon_name, (wip->alt_name[0]) ? wip->alt_name : wip->name); } // get rid of # end_string_at_first_hash_symbol(weapon_name); if ( sw->current_secondary_bank == i ) { // show that this is the current secondary armed renderPrintf(position[0] + Weapon_sunlinked_offset_x, name_y, EG_NULL, "%c", Lcl_special_chars + 2); // indicate if this is linked if ( Player_ship->flags & SF_SECONDARY_DUAL_FIRE ) { renderPrintf(position[0] + Weapon_slinked_offset_x, name_y, EG_NULL, "%c", Lcl_special_chars + 2); } // show secondary weapon's image or print its name if(wip->hud_image_index != -1) { renderBitmap(wip->hud_image_index, position[0] + Weapon_sname_offset_x, name_y); } else { renderString(position[0] + Weapon_sname_offset_x, name_y, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); } // show the cooldown time if ( (sw->secondary_bank_ammo[i] > 0) && (sw->current_secondary_bank >= 0) ) { int ms_till_fire = timestamp_until(sw->next_secondary_fire_stamp[sw->current_secondary_bank]); if ( (ms_till_fire >= 500) && ((wip->fire_wait >= 1 ) || (ms_till_fire > wip->fire_wait*1000)) ) { renderPrintf(position[0] + Weapon_sreload_offset_x, name_y, EG_NULL, "%d", fl2i(ms_till_fire/1000.0f +0.5f)); } } } else { // just print the weapon's name since this isn't armed renderString(position[0] + Weapon_sname_offset_x, name_y, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); } int ammo=sw->secondary_bank_ammo[i]; // print out the ammo right justified sprintf(ammo_str, "%d", ammo); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); renderString(position[0] + Weapon_sammo_offset_x - w, name_y, EG_NULL, ammo_str); if(i != 0) { y += secondary_text_h; } name_y += secondary_text_h; } // a bit lonely here with no secondaries so just print "<none>" if(ns==0) { renderString(position[0] + Weapon_pname_offset_x, name_y, EG_WEAPON_S1, XSTR( "<none>", 329)); } y -= 0; // finish drawing the background renderBitmap(secondary_bottom[ballistic_hud_index].first_frame, position[0] + frame_offset_x[ballistic_hud_index], y); } void hud_update_weapon_flash() { ship_weapon *sw; int num_weapons; sw = &Ships[Player_obj->instance].weapons; num_weapons = sw->num_primary_banks + sw->num_secondary_banks; if ( num_weapons > MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } for(int i = 0; i < num_weapons; i++) { if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[i]) ) { if ( timestamp_elapsed(Weapon_flash_info.flash_next[i]) ) { Weapon_flash_info.flash_next[i] = timestamp(TBOX_FLASH_INTERVAL); Weapon_flash_info.is_bright ^= (1<<i); } } } } void HudGaugeWeapons::maybeFlashWeapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } // hud_set_default_color(); setGaugeColor(); if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { if ( Weapon_flash_info.is_bright & (1<<index) ) { setGaugeColor(HUD_C_BRIGHT); // hud_set_bright_color(); } else { setGaugeColor(HUD_C_DIM); // hud_set_dim_color(); } } } void hud_target_add_display_list(object *objp, vertex *target_point, vec3d *target_pos, int correction, color *bracket_clr, char* name, int flags) { target_display_info element; element.objp = objp; element.target_point = *target_point; element.target_pos = *target_pos; element.correction = correction; element.flags = flags; if(bracket_clr) { element.bracket_clr = *bracket_clr; } else { // no color given, so this will tell the target display gauges to use IFF colors. gr_init_color(&element.bracket_clr, 0, 0, 0); } if(name) { strcpy_s(element.name, name); } else { strcpy_s(element.name, ""); } target_display_list.push_back(element); } void hud_target_clear_display_list() { target_display_list.clear(); } HudGaugeOffscreen::HudGaugeOffscreen(): HudGauge(HUD_OBJECT_OFFSCREEN, HUD_OFFSCREEN_INDICATOR, false, true, VM_DEAD_VIEW | VM_OTHER_SHIP, 255, 255, 255) { } void HudGaugeOffscreen::initMaxTriSeperation(float length) { Max_offscreen_tri_seperation = length; } void HudGaugeOffscreen::initMaxFrontSeperation(float length) { Max_front_seperation = length; } void HudGaugeOffscreen::initTriBase(float length) { Offscreen_tri_base = length; } void HudGaugeOffscreen::initTriHeight(float length) { Offscreen_tri_height = length; } void HudGaugeOffscreen::pageIn() { } void HudGaugeOffscreen::render(float frametime) { // don't show offscreen indicator if we're warping out. if ( Player->control_mode != PCM_NORMAL ) { return; } bool in_frame = g3_in_frame() > 0; if(!in_frame) g3_start_frame(0); gr_set_screen_scale(base_w, base_h); for(size_t i = 0; i < target_display_list.size(); i++) { if(target_display_list[i].target_point.codes != 0) { float dist = 0.0f; if(target_display_list[i].objp) { dist = hud_find_target_distance( target_display_list[i].objp, Player_obj ); } else { // if we don't have a corresponding object, use given position to figure out distance dist = vm_vec_dist_quick(&Player_obj->pos, &target_display_list[i].target_pos); } if( target_display_list[i].bracket_clr.red && target_display_list[i].bracket_clr.green && target_display_list[i].bracket_clr.blue ) { gr_set_color_fast(&target_display_list[i].bracket_clr); } else { // use IFF colors if none defined. if(target_display_list[i].objp) { hud_set_iff_color(target_display_list[i].objp, 1); } else { // no object so this must mean it's a nav point. but for some odd reason someone forgot to include a color. gr_set_color_fast(&target_display_list[i].bracket_clr); } } renderOffscreenIndicator(&target_display_list[i].target_point, &target_display_list[i].target_pos, dist); } } gr_reset_screen_scale(); if(!in_frame) g3_end_frame(); } void HudGaugeOffscreen::renderOffscreenIndicator(vertex* target_point, vec3d *tpos, float distance, int draw_solid) { char buf[32]; int w = 0, h = 0; int on_top, on_right, on_left, on_bottom; float xpos,ypos; // points to draw triangles float x1=0.0f; float y1=0.0f; float x2=0.0f; float y2=0.0f; float x3=0.0f; float y3=0.0f; float x4=0.0f; float y4=0.0f; float x5=0.0f; float y5=0.0f; float x6=0.0f; float y6=0.0f; vec3d targ_to_player; float dist_behind; float triangle_sep; float half_gauge_length, half_triangle_sep; float displayed_distance; // scale by distance modifier from hud_guages.tbl for display purposes displayed_distance = distance * Hud_unit_multiplier; // calculate the dot product between the players forward vector and the vector connecting // the player to the target. Normalize targ_to_player since we want the dot product // to range between 0 -> 1. vm_vec_sub(&targ_to_player, &Player_obj->pos, tpos); vm_vec_normalize(&targ_to_player); dist_behind = vm_vec_dot(&Player_obj->orient.vec.fvec, &targ_to_player); if (dist_behind < 0) { // still in front of player, but not in view dist_behind = dist_behind + 1.0f; if (dist_behind > 0.2 ){ triangle_sep = ( dist_behind ) * Max_front_seperation; } else { triangle_sep = 0.0f; } } else { triangle_sep = dist_behind * Max_offscreen_tri_seperation + Max_offscreen_tri_seperation; } if ( triangle_sep > Max_offscreen_tri_seperation + Max_front_seperation){ triangle_sep = Max_offscreen_tri_seperation + Max_front_seperation; } // calculate these values only once, since it will be used in several places half_triangle_sep = 0.5f * triangle_sep; half_gauge_length = half_triangle_sep + Offscreen_tri_base; // We need to find the screen (x,y) for where to draw the offscreen indicator // // The best way I've found is to draw a line from the eye_pos to the target, and // then use clip_line() to find the screen (x,y) for where the line hits the edge // of the screen. // // The weird thing about clip_line() is that is flips around the two verticies, // so I use eye_vertex->sx and eye_vertex->sy for the off-screen indicator (x,y) // vertex *eye_vertex = NULL; vertex real_eye_vertex; eye_vertex = &real_eye_vertex; // this is needed since clip line takes a **vertex vec3d eye_pos; vm_vec_add( &eye_pos, &Eye_position, &View_matrix.vec.fvec); g3_rotate_vertex(eye_vertex, &eye_pos); ubyte codes_or; codes_or = (ubyte)(target_point->codes | eye_vertex->codes); clip_line(&target_point,&eye_vertex,codes_or,0); if (!(target_point->flags&PF_PROJECTED)) g3_project_vertex(target_point); if (!(eye_vertex->flags&PF_PROJECTED)) g3_project_vertex(eye_vertex); if (eye_vertex->flags&PF_OVERFLOW) { Int3(); // This is unlikely to happen, but can if a clip goes through the player's eye. Player_ai->target_objnum = -1; return; } if (target_point->flags & PF_TEMP_POINT) free_temp_point(target_point); if (eye_vertex->flags & PF_TEMP_POINT) free_temp_point(eye_vertex); xpos = eye_vertex->screen.xyw.x; ypos = eye_vertex->screen.xyw.y; // we need it unsized here and it will be fixed when things are acutally drawn gr_unsize_screen_posf(&xpos, &ypos); on_left = on_right = on_top = on_bottom = 0; xpos = (xpos<1) ? 0 : xpos; ypos = (ypos<1) ? 0 : ypos; if ( xpos <= gr_screen.clip_left_unscaled ) { xpos = i2fl(gr_screen.clip_left_unscaled); on_left = TRUE; if ( ypos < (half_gauge_length - gr_screen.clip_top_unscaled) ) ypos = half_gauge_length; if ( ypos > (gr_screen.clip_bottom_unscaled - half_gauge_length) ) ypos = gr_screen.clip_bottom_unscaled - half_gauge_length; } else if ( xpos >= gr_screen.clip_right_unscaled) { xpos = i2fl(gr_screen.clip_right_unscaled); on_right = TRUE; if ( ypos < (half_gauge_length - gr_screen.clip_top_unscaled) ) ypos = half_gauge_length; if ( ypos > (gr_screen.clip_bottom_unscaled - half_gauge_length) ) ypos = gr_screen.clip_bottom_unscaled - half_gauge_length; } else if ( ypos <= gr_screen.clip_top_unscaled ) { ypos = i2fl(gr_screen.clip_top_unscaled); on_top = TRUE; if ( xpos < ( half_gauge_length - gr_screen.clip_left_unscaled) ) xpos = half_gauge_length; if ( xpos > (gr_screen.clip_right_unscaled - half_gauge_length) ) xpos = gr_screen.clip_right_unscaled - half_gauge_length; } else if ( ypos >= gr_screen.clip_bottom_unscaled ) { ypos = i2fl(gr_screen.clip_bottom_unscaled); on_bottom = TRUE; if ( xpos < ( half_gauge_length - gr_screen.clip_left_unscaled) ) xpos = half_gauge_length; if ( xpos > (gr_screen.clip_right_unscaled - half_gauge_length) ) xpos = gr_screen.clip_right_unscaled - half_gauge_length; } else { Int3(); return; } // The offscreen target triangles are drawn according the the diagram below // // // // x3 x3 // / | | \. // / | | \. // x1___x2 x2___x1 // | | // ......|...........|...............(xpos,ypos) // | | // x4___x5 x5___x4 // \ | | / // \ | | / // x6 x6 // // xpos = (float)floor(xpos); ypos = (float)floor(ypos); if (displayed_distance > 0.0f) { sprintf(buf, "%d", fl2i(displayed_distance + 0.5f)); hud_num_make_mono(buf); gr_get_string_size(&w, &h, buf); } else { buf[0] = 0; } if (on_right) { x1 = x4 = (xpos+2); x2 = x3 = x5 = x6 = x1 - Offscreen_tri_height; y1 = y2 = ypos - half_triangle_sep; y3 = y2 - Offscreen_tri_base; y4 = y5 = ypos + half_triangle_sep; y6 = y5 + Offscreen_tri_base; if ( buf[0] ) { gr_string( fl2i(xpos - w - 10), fl2i(ypos - h/2.0f+0.5f), buf); } } else if (on_left) { x1 = x4 = (xpos-1); x2 = x3 = x5 = x6 = x1 + Offscreen_tri_height; y1 = y2 = ypos - half_triangle_sep; y3 = y2 - Offscreen_tri_base; y4 = y5 = ypos + half_triangle_sep; y6 = y5 + Offscreen_tri_base; if ( buf[0] ) { gr_string(fl2i(xpos + 10), fl2i(ypos - h/2.0f+0.5f), buf); } } else if (on_top) { y1 = y4 = (ypos-1); y2 = y3 = y5 = y6 = y1 + Offscreen_tri_height; x1 = x2 = xpos - half_triangle_sep; x3 = x2 - Offscreen_tri_base; x4 = x5 = xpos + half_triangle_sep; x6 = x5 + Offscreen_tri_base; if ( buf[0] ) { gr_string(fl2i(xpos - w/2.0f+0.5f), fl2i(ypos+10), buf); } } else if (on_bottom) { y1 = y4 = (ypos+2); y2 = y3 = y5 = y6 = y1 - Offscreen_tri_height; x1 = x2 = xpos - half_triangle_sep; x3 = x2 - Offscreen_tri_base; x4 = x5 = xpos + half_triangle_sep; x6 = x5 + Offscreen_tri_base; if ( buf[0] ) { gr_string(fl2i(xpos - w/2.0f+0.5f), fl2i(ypos-h-10), buf); } } if (draw_solid) { hud_tri(x3,y3,x2,y2,x1,y1); hud_tri(x4,y4,x5,y5,x6,y6); } else { hud_tri_empty(x3,y3,x2,y2,x1,y1); hud_tri_empty(x4,y4,x5,y5,x6,y6); } if (on_right || on_bottom){ gr_line(fl2i(x2),fl2i(y2),fl2i(x5),fl2i(y5)); } else if (on_left) { gr_line(fl2i(x2-1),fl2i(y2),fl2i(x5-1),fl2i(y5)); } else { gr_line(fl2i(x2),fl2i(y2-1),fl2i(x5),fl2i(y5-1)); } } HudGaugeWarheadCount::HudGaugeWarheadCount(): HudGauge(HUD_OBJECT_WARHEAD_COUNT, HUD_WEAPONS_GAUGE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY, 255, 255, 255) { } void HudGaugeWarheadCount::initBitmap(char *fname) { Warhead.first_frame = bm_load_animation(fname, &Warhead.num_frames); if ( Warhead.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeWarheadCount::initNameOffsets(int x, int y) { Warhead_name_offsets[0] = x; Warhead_name_offsets[1] = y; } void HudGaugeWarheadCount::initCountOffsets(int x, int y) { Warhead_count_offsets[0] = x; Warhead_count_offsets[1] = y; } void HudGaugeWarheadCount::initCountSizes(int w, int h) { Warhead_count_size[0] = w; Warhead_count_size[1] = h; } void HudGaugeWarheadCount::initMaxSymbols(int count) { Max_symbols = count; } void HudGaugeWarheadCount::initMaxColumns(int count) { Max_columns = count; } void HudGaugeWarheadCount::initTextAlign(int align) { Text_align = align; } void HudGaugeWarheadCount::pageIn() { bm_page_in_aabitmap(Warhead.first_frame, Warhead.num_frames); } void HudGaugeWarheadCount::render(float frametime) { if(Player_obj->type == OBJ_OBSERVER) { return; } Assert(Player_obj->type == OBJ_SHIP); Assert(Player_obj->instance >= 0 && Player_obj->instance < MAX_SHIPS); ship_weapon *sw = &Ships[Player_obj->instance].weapons; // don't bother displaying anything if we have no secondaries if ( sw->num_secondary_banks <= 0 ) { return; } int wep_num = sw->current_secondary_bank; weapon_info *wip = &Weapon_info[sw->secondary_bank_weapons[wep_num]]; int ammo = sw->secondary_bank_ammo[wep_num]; // don't bother displaying anything if we have no ammo. if ( ammo <= 0 ) { return; } char weapon_name[NAME_LENGTH + 10]; strcpy_s(weapon_name, (wip->alt_name[0]) ? wip->alt_name : wip->name); end_string_at_first_hash_symbol(weapon_name); setGaugeColor(); // display the weapon name if ( Text_align ) { int w, h; gr_get_string_size(&w, &h, weapon_name); renderString(position[0] + Warhead_name_offsets[0] - w, position[1] + Warhead_name_offsets[1], weapon_name); } else { renderString(position[0] + Warhead_name_offsets[0], position[1] + Warhead_name_offsets[1], weapon_name); } setGaugeColor(HUD_C_BRIGHT); // if ammo is greater than the icon display limit, just show a numeric if ( ammo > Max_symbols ) { char ammo_str[32]; sprintf(ammo_str, "%d", ammo); hud_num_make_mono(ammo_str); if ( Text_align ) { int w, h; gr_get_string_size(&w, &h, ammo_str); renderString(position[0] + Warhead_count_offsets[0] - w, position[1] + Warhead_count_offsets[1], ammo_str); } else { renderString(position[0] + Warhead_count_offsets[0], position[1] + Warhead_count_offsets[1], ammo_str); } return; } int delta_x = 0, delta_y = 0; if ( Text_align ) { delta_x = -Warhead_count_size[0]; } else { delta_x = Warhead_count_size[0]; } int i, column; for ( i = 0; i < ammo; i++ ) { if ( Max_columns > 0 ) { delta_y = Warhead_count_size[1] * (i / Max_columns); column = i % Max_columns; } else { column = i; } renderBitmap(Warhead.first_frame, position[0] + Warhead_count_offsets[0] + column * delta_x, position[1] + Warhead_count_offsets[1] + delta_y); } } HudGaugeWeaponList::HudGaugeWeaponList(int gauge_object): HudGauge(gauge_object, HUD_WEAPONS_GAUGE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY, 255, 255, 255) { } void HudGaugeWeaponList::initBitmaps(char *fname_first, char *fname_entry, char *fname_last) { _background_first.first_frame = bm_load_animation(fname_first, &_background_first.num_frames); if(_background_first.first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname_first); } _background_entry.first_frame = bm_load_animation(fname_entry, &_background_entry.num_frames); if(_background_entry.first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname_entry); } _background_last.first_frame = bm_load_animation(fname_last, &_background_last.num_frames); if(_background_last.first_frame < 0) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname_last); } } void HudGaugeWeaponList::initBgFirstOffsetX(int x) { _bg_first_offset_x = x; } void HudGaugeWeaponList::initBgEntryOffsetX(int x) { _bg_entry_offset_x = x; } void HudGaugeWeaponList::initBgLastOffsetX(int x) { _bg_last_offset_x = x; } void HudGaugeWeaponList::initBgLastOffsetY(int y) { _bg_last_offset_y = y; } void HudGaugeWeaponList::initBgFirstHeight(int h) { _background_first_h = h; } void HudGaugeWeaponList::initBgEntryHeight(int h) { _background_entry_h = h; } void HudGaugeWeaponList::initHeaderText(char *text) { strcpy_s(header_text, text); } void HudGaugeWeaponList::initHeaderOffsets(int x, int y) { _header_offsets[0] = x; _header_offsets[1] = y; } void HudGaugeWeaponList::initEntryStartY(int y) { _entry_start_y = y; } void HudGaugeWeaponList::initEntryHeight(int h) { _entry_h = h; } void HudGaugeWeaponList::pageIn() { if ( _background_first.first_frame >= 0 ) { bm_page_in_aabitmap(_background_first.first_frame, _background_first.num_frames); } if ( _background_entry.first_frame >= 0 ) { bm_page_in_aabitmap(_background_entry.first_frame, _background_entry.num_frames); } if ( _background_last.first_frame >= 0 ) { bm_page_in_aabitmap(_background_last.first_frame, _background_last.num_frames); } } void HudGaugeWeaponList::maybeFlashWeapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } // hud_set_default_color(); setGaugeColor(); if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { if ( Weapon_flash_info.is_bright & (1<<index) ) { setGaugeColor(HUD_C_BRIGHT); // hud_set_bright_color(); } else { setGaugeColor(HUD_C_DIM); // hud_set_dim_color(); } } } void HudGaugeWeaponList::render(float frametime) { } HudGaugePrimaryWeapons::HudGaugePrimaryWeapons(): HudGaugeWeaponList(HUD_OBJECT_PRIMARY_WEAPONS) { } void HudGaugePrimaryWeapons::initPrimaryLinkOffsetX(int x) { _plink_offset_x = x; } void HudGaugePrimaryWeapons::initPrimaryNameOffsetX(int x) { _pname_offset_x = x; } void HudGaugePrimaryWeapons::initPrimaryAmmoOffsetX(int x) { _pammo_offset_x = x; } void HudGaugePrimaryWeapons::render(float frametime) { ship_weapon *sw; int ship_is_ballistic; int num_primaries; // np == num primary char name[NAME_LENGTH]; if(Player_obj->type == OBJ_OBSERVER) return; Assert(Player_obj->type == OBJ_SHIP); Assert(Player_obj->instance >= 0 && Player_obj->instance < MAX_SHIPS); sw = &Ships[Player_obj->instance].weapons; ship_is_ballistic = (Ship_info[Ships[Player_obj->instance].ship_info_index].flags & SIF_BALLISTIC_PRIMARIES); num_primaries = sw->num_primary_banks; setGaugeColor(); renderBitmap(_background_first.first_frame, position[0], position[1]); // render the header of this gauge renderString(position[0] + _header_offsets[0], position[1] + _header_offsets[1], EG_WEAPON_TITLE, header_text); char ammo_str[32]; int i, w, h; int bg_y_offset = _background_first_h; int text_y_offset = _entry_start_y; for ( i = 0; i < num_primaries; ++i ) { setGaugeColor(); renderBitmap(_background_entry.first_frame, position[0], position[1] + bg_y_offset); strcpy_s(name, (Weapon_info[sw->primary_bank_weapons[i]].alt_name[0]) ? Weapon_info[sw->primary_bank_weapons[i]].alt_name : Weapon_info[sw->primary_bank_weapons[i]].name); if (Lcl_gr) { lcl_translate_wep_name(name); } if (HudGauge::maybeFlashSexp() == i ) { setGaugeColor(HUD_C_BRIGHT); } else { maybeFlashWeapon(i); } // indicate if this is linked or currently armed if ( (sw->current_primary_bank == i) || (Player_ship->flags & SF_PRIMARY_LINKED) ) { renderPrintf(position[0] + _plink_offset_x, position[1] + text_y_offset, EG_NULL, "%c", Lcl_special_chars + 2); } // either render this primary's image or its name if(Weapon_info[sw->primary_bank_weapons[0]].hud_image_index != -1) { renderBitmap(Weapon_info[sw->primary_bank_weapons[i]].hud_image_index, position[0] + _pname_offset_x, text_y_offset); } else { renderPrintf(position[0] + _pname_offset_x, position[1] + text_y_offset, EG_WEAPON_P2, "%s", name); } // if this is a ballistic primary with ammo, render the ammo count if (Weapon_info[sw->primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC) { // print out the ammo right justified sprintf(ammo_str, "%d", sw->primary_bank_ammo[i]); // get rid of # end_string_at_first_hash_symbol(ammo_str); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); renderString(position[0] + _pammo_offset_x - w, position[1] + text_y_offset, EG_NULL, ammo_str); } text_y_offset += _entry_h; bg_y_offset += _background_entry_h; } if ( num_primaries == 0 ) { renderBitmap(_background_entry.first_frame, position[0], position[1] + bg_y_offset); renderString(position[0] + _pname_offset_x, position[1] + text_y_offset, EG_WEAPON_P1, XSTR( "<none>", 329)); bg_y_offset += _background_entry_h; } renderBitmap(_background_last.first_frame, position[0], position[1] + bg_y_offset + _bg_last_offset_y); } HudGaugeSecondaryWeapons::HudGaugeSecondaryWeapons(): HudGaugeWeaponList(HUD_OBJECT_SECONDARY_WEAPONS) { } void HudGaugeSecondaryWeapons::initSecondaryAmmoOffsetX(int x) { _sammo_offset_x = x; } void HudGaugeSecondaryWeapons::initSecondaryNameOffsetX(int x) { _sname_offset_x = x; } void HudGaugeSecondaryWeapons::initSecondaryReloadOffsetX(int x) { _sreload_offset_x = x; } void HudGaugeSecondaryWeapons::initSecondaryLinkedOffsetX(int x) { _slinked_offset_x = x; } void HudGaugeSecondaryWeapons::initSecondaryUnlinkedOffsetX(int x) { _sunlinked_offset_x = x; } void HudGaugeSecondaryWeapons::render(float frametime) { ship_weapon *sw; int ship_is_ballistic; int num_primaries, num_secondaries; Assert(Player_obj->type == OBJ_SHIP); Assert(Player_obj->instance >= 0 && Player_obj->instance < MAX_SHIPS); sw = &Ships[Player_obj->instance].weapons; ship_is_ballistic = (Ship_info[Ships[Player_obj->instance].ship_info_index].flags & SIF_BALLISTIC_PRIMARIES); num_primaries = sw->num_primary_banks; num_secondaries = sw->num_secondary_banks; setGaugeColor(); renderBitmap(_background_first.first_frame, position[0], position[1]); // render the header of this gauge renderString(position[0] + _header_offsets[0], position[1] + _header_offsets[1], EG_WEAPON_TITLE, header_text); weapon_info *wip; char weapon_name[NAME_LENGTH + 10]; char ammo_str[32]; int i, w, h; int bg_y_offset = _background_first_h; int text_y_offset = _entry_start_y; for ( i = 0; i < num_secondaries; ++i ) { setGaugeColor(); wip = &Weapon_info[sw->secondary_bank_weapons[i]]; renderBitmap(_background_entry.first_frame, position[0], position[1] + bg_y_offset); maybeFlashWeapon(num_primaries+i); strcpy_s(weapon_name, (wip->alt_name[0]) ? wip->alt_name : wip->name); end_string_at_first_hash_symbol(weapon_name); if ( sw->current_secondary_bank == i ) { // show that this is the current secondary armed renderPrintf(position[0] + _sunlinked_offset_x, position[1] + text_y_offset, EG_NULL, "%c", Lcl_special_chars + 2); // indicate if this is linked if ( Player_ship->flags & SF_SECONDARY_DUAL_FIRE ) { renderPrintf(position[0] + _slinked_offset_x, position[1] + text_y_offset, EG_NULL, "%c", Lcl_special_chars + 2); } // show secondary weapon's image or print its name if(wip->hud_image_index != -1) { renderBitmap(wip->hud_image_index, position[0] + _sname_offset_x, position[1] + text_y_offset); } else { renderString(position[0] + _sname_offset_x, position[1] + text_y_offset, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); } // show the cooldown time if ( (sw->secondary_bank_ammo[i] > 0) && (sw->current_secondary_bank >= 0) ) { int ms_till_fire = timestamp_until(sw->next_secondary_fire_stamp[sw->current_secondary_bank]); if ( (ms_till_fire >= 500) && ((wip->fire_wait >= 1 ) || (ms_till_fire > wip->fire_wait*1000)) ) { renderPrintf(position[0] + _sreload_offset_x, position[1] + text_y_offset, EG_NULL, "%d", fl2i(ms_till_fire/1000.0f +0.5f)); } } } else { renderString(position[0] + _sname_offset_x, position[1] + text_y_offset, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); } int ammo = sw->secondary_bank_ammo[i]; // print out the ammo right justified sprintf(ammo_str, "%d", ammo); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); renderString(position[0] + _sammo_offset_x - w, position[1] + text_y_offset, EG_NULL, ammo_str); bg_y_offset += _background_entry_h; text_y_offset += _entry_h; } if ( num_secondaries == 0 ) { renderBitmap(_background_entry.first_frame, position[0], position[1] + bg_y_offset); renderString(position[0] + _sname_offset_x, position[1] + text_y_offset, EG_WEAPON_S1, XSTR( "<none>", 329)); bg_y_offset += _background_entry_h; } // finish drawing the background renderBitmap(_background_last.first_frame, position[0], position[1] + bg_y_offset + _bg_last_offset_y); } HudGaugeHardpoints::HudGaugeHardpoints(): HudGauge(HUD_OBJECT_HARDPOINTS, HUD_WEAPONS_GAUGE, false, false, VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY, 255, 255, 255) { } void HudGaugeHardpoints::initSizes(int w, int h) { _size[0] = w; _size[1] = h; } void HudGaugeHardpoints::initLineWidth(float w) { _line_width = w; } void HudGaugeHardpoints::initViewDir(int dir) { _view_direction = dir; } void HudGaugeHardpoints::initDrawOptions(bool primary_models, bool secondary_models) { draw_primary_models = primary_models; draw_secondary_models = secondary_models; } void HudGaugeHardpoints::render(float frametime) { int sx, sy; ship *sp; ship_info *sip; object *objp = Player_obj; sp = &Ships[objp->instance]; sip = &Ship_info[sp->ship_info_index]; sx = position[0]; sy = position[1]; bool g3_yourself = !g3_in_frame(); angles top_view = {-PI_2,0.0f,0.0f}; angles front_view = {PI_2*2.0f,PI_2*2.0f,0.0f}; matrix object_orient; switch ( _view_direction ) { case TOP: vm_angles_2_matrix(&object_orient, &top_view); break; case FRONT: vm_angles_2_matrix(&object_orient, &front_view); break; } gr_screen.clip_width = _size[0]; gr_screen.clip_height = _size[1]; //Fire it up if(g3_yourself) g3_start_frame(1); hud_save_restore_camera_data(1); setClip(sx, sy, _size[0], _size[1]); model_set_detail_level(1); g3_set_view_matrix( &sip->closeup_pos, &vmd_identity_matrix, sip->closeup_zoom*1.5f); if (!Cmdline_nohtl) { gr_set_proj_matrix(Proj_fov, gr_screen.clip_aspect, Min_draw_distance, Max_draw_distance); gr_set_view_matrix(&Eye_position, &Eye_matrix); } setGaugeColor(); //We're ready to show stuff int cull = gr_set_cull(0); gr_stencil_clear(); gr_stencil_set(GR_STENCIL_WRITE); int zbuffer = gr_zbuffer_set(GR_ZBUFF_NONE); gr_set_color_buffer(0); ship_model_start(objp); model_render( sip->model_num, &object_orient, &vmd_zero_vector, MR_NO_LIGHTING | MR_LOCK_DETAIL | MR_AUTOCENTER | MR_NO_FOGGING | MR_NO_TEXTURING | MR_NO_CULL); gr_set_color_buffer(1); gr_stencil_set(GR_STENCIL_READ); gr_set_cull(cull); gr_set_line_width(_line_width*2.0f); model_set_alpha( gr_screen.current_color.alpha / 255.0f ); model_set_forced_texture(0); model_render( sip->model_num, &object_orient, &vmd_zero_vector, MR_NO_LIGHTING | MR_LOCK_DETAIL | MR_AUTOCENTER | MR_NO_FOGGING | MR_NO_TEXTURING | MR_SHOW_OUTLINE_HTL | MR_NO_POLYS | MR_NO_ZBUFFER | MR_NO_CULL | MR_ALL_XPARENT ); ship_model_stop( objp ); gr_stencil_set(GR_STENCIL_NONE); gr_zbuffer_set(zbuffer); gr_set_line_width(1.0f); // draw weapon models int i, k; ship_weapon *swp = &sp->weapons; vertex draw_point; vec3d subobj_pos; g3_start_instance_matrix(&vmd_zero_vector, &object_orient, true); int render_flags = MR_NO_LIGHTING | MR_LOCK_DETAIL | MR_AUTOCENTER | MR_NO_FOGGING | MR_NO_TEXTURING | MR_NO_ZBUFFER; setGaugeColor(); model_set_alpha( gr_screen.current_color.alpha / 255.0f ); //secondary weapons int num_secondaries_rendered = 0; vec3d secondary_weapon_pos; w_bank* bank; if ( draw_secondary_models ) { for (i = 0; i < swp->num_secondary_banks; i++) { if (Weapon_info[swp->secondary_bank_weapons[i]].external_model_num == -1 || !sip->draw_secondary_models[i]) continue; bank = &(model_get(sip->model_num))->missile_banks[i]; if (Weapon_info[swp->secondary_bank_weapons[i]].wi_flags2 & WIF2_EXTERNAL_WEAPON_LNCH) { for(k = 0; k < bank->num_slots; k++) { model_render(Weapon_info[swp->secondary_bank_weapons[i]].external_model_num, &vmd_identity_matrix, &bank->pnt[k], render_flags); } } else { num_secondaries_rendered = 0; for(k = 0; k < bank->num_slots; k++) { secondary_weapon_pos = bank->pnt[k]; if (num_secondaries_rendered >= sp->weapons.secondary_bank_ammo[i]) break; if(sp->secondary_point_reload_pct[i][k] <= 0.0) continue; if ( swp->current_secondary_bank == i && ( swp->secondary_next_slot[i] == k || ( swp->secondary_next_slot[i]+1 == k && sp->flags & SF_SECONDARY_DUAL_FIRE ) ) ) { gr_set_color_fast(&Color_bright_blue); } else { gr_set_color_fast(&Color_bright_white); } num_secondaries_rendered++; vm_vec_scale_add2(&secondary_weapon_pos, &vmd_z_vector, -(1.0f-sp->secondary_point_reload_pct[i][k]) * model_get(Weapon_info[swp->secondary_bank_weapons[i]].external_model_num)->rad); model_render(Weapon_info[swp->secondary_bank_weapons[i]].external_model_num, &vmd_identity_matrix, &secondary_weapon_pos, render_flags); } } } } g3_done_instance(true); resetClip(); model_set_forced_texture(0); setGaugeColor(HUD_C_BRIGHT); //primary weapons if ( draw_primary_models ) { for ( i = 0; i < swp->num_primary_banks; i++ ) { w_bank *bank = &model_get(sip->model_num)->gun_banks[i]; for ( k = 0; k < bank->num_slots; k++ ) { if ( ( Weapon_info[swp->primary_bank_weapons[i]].external_model_num == -1 || !sip->draw_primary_models[i] ) ) { vm_vec_unrotate(&subobj_pos, &bank->pnt[k], &object_orient); //vm_vec_sub(&subobj_pos, &Eye_position, &subobj_pos); //g3_rotate_vertex(&draw_point, &bank->pnt[k]); g3_rotate_vertex(&draw_point, &subobj_pos); g3_project_vertex(&draw_point); //resize(&width, &height); //unsize(&xc, &yc); //unsize(&draw_point.screen.xyw.x, &draw_point.screen.xyw.y); renderCircle((int)draw_point.screen.xyw.x + position[0], (int)draw_point.screen.xyw.y + position[1], 10); //renderCircle(xc, yc, 25); } else { polymodel* pm = model_get(Weapon_info[swp->primary_bank_weapons[i]].external_model_num); pm->gun_submodel_rotation = sp->primary_rotate_ang[i]; model_render(Weapon_info[swp->primary_bank_weapons[i]].external_model_num, &vmd_identity_matrix, &bank->pnt[k], render_flags); pm->gun_submodel_rotation = 0.0f; } } } } //We're done if(!Cmdline_nohtl) { gr_end_view_matrix(); gr_end_proj_matrix(); } if(g3_yourself) g3_end_frame(); hud_save_restore_camera_data(0); }
[ "chief1983@387891d4-d844-0410-90c0-e4c51a9137d3" ]
chief1983@387891d4-d844-0410-90c0-e4c51a9137d3
960c6f2a3b420a98a6a424139adf6dd8aa3be7c8
a1fbf16243026331187b6df903ed4f69e5e8c110
/cs/engine/utils/xrQSlim/src/mixvops.h
da36b8fc911c9b5c721ed9ec0a116d3a51f4a5c8
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
OpenXRay/xray-15
ca0031cf1893616e0c9795c670d5d9f57ca9beff
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
refs/heads/xd_dev
2023-07-17T23:42:14.693841
2021-09-01T23:25:34
2021-09-01T23:25:34
23,224,089
64
23
NOASSERTION
2019-04-03T17:50:18
2014-08-22T12:09:41
C++
UTF-8
C++
false
false
4,294
h
#ifndef MIXVOPS_INCLUDED // -*- C++ -*- #define MIXVOPS_INCLUDED // #endif // WARNING: Multiple inclusions allowed /************************************************************************ Low-level vector math operations. This header file is intended for internal library use only. You should understand what's going on in here before trying to use it yourself. Using the magic __LINKAGE macro, this file can be compiled either as a set of templated functions, or as a series of inline functions whose argument type is determined by the __T macro. My rationale for this is that some compilers either don't support templated functions or are incapable of inlining them. PUBLIC APOLOGY: I really do apologize for the ugliness of the code in this header. In order to accommodate various types of compilation and to avoid lots of typing, I've made pretty heavy use of macros. Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details. $Id: mixvops.h,v 1.12 1999/11/30 02:39:02 garland Exp $ ************************************************************************/ #include "MxDefines.h" #ifdef MIXVOPS_DEFAULT_DIM # define __DIM const int N=MIXVOPS_DEFAULT_DIM #else # define __DIM const int N #endif #if !defined(MIXVOPS_USE_TEMPLATES) # ifndef __T # define __T double # endif # define __LINKAGE inline #else # ifdef __T # undef __T # endif # define __LINKAGE template<class __T>inline #endif #define __OP __LINKAGE __T * #define forall(i, N) for(unsigned int i=0; i<(unsigned int)N; i++) #define def3(name, op) __OP name(__T *r, const __T *u, const __T *v, __DIM) { forall(i,N) op; return r; } #define def2(name, op) __OP name(__T *r, const __T *u, __DIM) { forall(i,N) op; return r; } #define def1(name, op) __OP name(__T *r, __DIM) { forall(i,N) op; return r; } #define def2s(name, op) __OP name(__T *r, const __T *u, __T d, __DIM) { forall(i,N) op; return r; } #define def1s(name, op) __OP name(__T *r, __T d, __DIM) { forall(i,N) op; return r; } def3(mxv_add, r[i] = u[i] + v[i]) def3(mxv_sub, r[i] = u[i] - v[i]) def3(mxv_mul, r[i] = u[i] * v[i]) def3(mxv_div, r[i] = u[i] / v[i]) def3(mxv_min, r[i] = u[i]<v[i]?u[i]:v[i];) def3(mxv_max, r[i] = u[i]>v[i]?u[i]:v[i];) def2(mxv_addinto, r[i] += u[i]) def2(mxv_subfrom, r[i] -= u[i]) def2(mxv_mulby, r[i] *= u[i]) def2(mxv_divby, r[i] /= u[i]) def2(mxv_set, r[i] = u[i]) def1(mxv_neg, r[i] = -r[i]) def2(mxv_neg, r[i] = -u[i]) def1s(mxv_set, r[i]=d) def1s(mxv_scale, r[i] *= d) def1s(mxv_invscale, r[i] /= d) def2s(mxv_scale, r[i] = u[i]*d) def2s(mxv_invscale, r[i] = u[i]/d) __LINKAGE __T mxv_dot(const __T *u, const __T *v, __DIM) { __T dot=0.0; forall(i, N) dot+=u[i]*v[i]; return dot; } __OP mxv_cross3(__T *r, const __T *u, const __T *v) { r[0] = u[1]*v[2] - v[1]*u[2]; r[1] = -u[0]*v[2] + v[0]*u[2]; r[2] = u[0]*v[1] - v[0]*u[1]; return r; } __OP mxv_lerp(__T *r, const __T *u, const __T *v, __T t, __DIM) { forall(i, N) { r[i] = t*u[i] + (1-t)*v[i]; } return r; } __LINKAGE __T mxv_norm(const __T *v, __DIM) { return _sqrt(mxv_dot(v,v,N)); } __LINKAGE __T mxv_norm2(const __T *v, __DIM) { return mxv_dot(v,v,N); } __LINKAGE __T mxv_unitize(__T *v, __DIM) { __T l = mxv_norm2(v, N); if( l!=1.0 && l!=0.0 ) { l = _sqrt(l); mxv_invscale(v, l, N); } return l; } __LINKAGE __T mxv_Linf(const __T *u, const __T *v, __DIM) { __T d=0.0; forall(i, N) { __T p=_abs(u[i]-v[i]); d=_min(d, p); } return d; } __LINKAGE __T mxv_L1(const __T *u, const __T *v, __DIM) { __T d = 0.0; forall(i, N) d+=_abs(u[i]-v[i]); return d; } __LINKAGE __T mxv_L2(const __T *u, const __T *v, __DIM) { __T d = 0.0; forall(i, N) { __T p=u[i]-v[i]; d+=p*p; } return d; } __LINKAGE bool mxv_eql(const __T *u, const __T *v, __DIM) { bool e=true; for(unsigned int i=0; e && i<(unsigned int)N; i++) e = e && (u[i]==v[i]); return e; } __LINKAGE bool mxv_equal(const __T *u, const __T *v, __DIM) { return mxv_L2(u, v, N) < FEQ_EPS2; } __OP mxv_basis(__T *r, unsigned int b, __DIM) { forall(i, N) r[i] = (i==b)?__T(1.0):__T(0.0); return r; } #undef __T #undef __DIM #undef __LINKAGE #undef __OP #undef forall #undef def3 #undef def2 #undef def1 #undef def2s #undef def1s // MIXVOPS_INCLUDED
[ "paul-kv@yandex.ru" ]
paul-kv@yandex.ru
56a8f809d5e431628867f041e7255ad19f40e28e
1142765797be6e0ef7f92be923467c418460ae3b
/client/srcs/Datagram.cpp
b139ac7a863cd98fe8981d2c22039f866bec01da
[]
no_license
tle-huu/mappy
5c4211d039f9d1e4c280cd704a6b63dd62f87943
efbe5a330dc09d0e6104e6696b60c2a69df56ecd
refs/heads/master
2020-03-25T06:15:14.907339
2018-10-02T11:07:18
2018-12-25T19:51:26
143,491,734
0
2
null
null
null
null
UTF-8
C++
false
false
1,183
cpp
#include "Datagram.hpp" /* ** ================== CONSTRUCTORS DESTRUCTORS ================== */ Datagram::Datagram() : _header("EMPTY"), _message("EMPTY") {} Datagram::Datagram(std::string header, std::string message) : _header(header), _message(message) {} Datagram::~Datagram() {} Datagram::Datagram(Datagram const &src) { this->_header = src._header; this->_message = src._message; } Datagram & Datagram::operator=(Datagram const & src) { this->_header = src._header; this->_message = src._message; return (*this); } /* ** ================== PUBLIC ================== */ std::string Datagram::getHeader() const { return (this->_header); } std::string Datagram::getMessage() const { return (this->_message); } void Datagram::setHeader(std::string header) { this->_header = header; } void Datagram::setMessage(std::string message) { this->_message = message; } /* ** ================== OVERLOAD OUTSIDE CLASS OPERATORS ================== */ std::ostream & operator<<( std::ostream & o, Datagram const & rhs) { o << "<header> [" << rhs.getHeader() << "];; <message> [" << rhs.getMessage() << "]"<< std::endl; return (o); }
[ "tlehuu@hotmail.fr" ]
tlehuu@hotmail.fr
b684e363b926d914a6b3534f16271a4b14e51ee5
abaacd6382e4165bb9059340fc60b7ef4ff55675
/2018_1_16/post_lTree.cpp
751466d6125f7580b9ff5f433a62bb08419c0bfb
[]
no_license
lanke0720/data_struct
3ab49a0ec82a6c88e636c11fe140dfe35dea6b0f
1677eb77319b089ab45293833daefbac93992d70
refs/heads/master
2021-01-23T10:20:25.631429
2018-03-13T15:25:13
2018-03-13T15:25:13
93,051,248
0
0
null
null
null
null
GB18030
C++
false
false
611
cpp
class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { int n = sequence.size(); if (n == 0) return false; int i = 0; while (n--) { while(sequence[i++]<sequence[n]); while(sequence[i++]>sequence[n]); if (i < n) return false; i = 0; } return true; } }; 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
[ "1600977813@qq.com" ]
1600977813@qq.com
88be8b1647ab9ea57d7b5f70f31b025bae988391
a8e5155ecc010b57fddf83b1451ca7206da2623d
/SDK/ES2_BP_Condition_Utility_KinematicMode_PhysicsEnabled_parameters.hpp
1fffbe905f5016a980a7e490d17169d5db86058d
[]
no_license
RussellJerome/EverSpace2-SDK
3d1c114ddcf79633ce6999aa8de735df6f3dc947
bb52c5ddf14aef595bb2c43310dc5ee0bc71732b
refs/heads/master
2022-12-12T04:59:55.403652
2020-08-30T00:56:25
2020-08-30T00:56:25
291,374,170
0
0
null
null
null
null
UTF-8
C++
false
false
401
hpp
#pragma once // Everspace2_Prototype SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ES2_BP_Condition_Utility_KinematicMode_PhysicsEnabled_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "darkmanvoo@gmail.com" ]
darkmanvoo@gmail.com
d6f5b8cd237678d333f50d88caf8075fa97fe561
c8420955b0b2b7893ac2353fa680be9637d910fc
/export/windows/cpp/obj/src/haxe/Resource.cpp
8016209ff571f011f51684274da1aa017ba2e41a
[ "Unlicense" ]
permissive
Misto423/ColorWheelGame
056cbc4f5b3ea32b841ba3eca7f6bfe6a039398d
cbbe986c6cdcd27919e45f7484a8d293a6d67811
refs/heads/master
2021-01-22T02:40:44.760389
2014-12-07T18:24:08
2014-12-07T18:24:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
cpp
#include <hxcpp.h> #ifndef INCLUDED_haxe_Resource #include <haxe/Resource.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif namespace haxe{ Void Resource_obj::__construct() { return null(); } //Resource_obj::~Resource_obj() { } Dynamic Resource_obj::__CreateEmpty() { return new Resource_obj; } hx::ObjectPtr< Resource_obj > Resource_obj::__new() { hx::ObjectPtr< Resource_obj > result = new Resource_obj(); result->__construct(); return result;} Dynamic Resource_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Resource_obj > result = new Resource_obj(); result->__construct(); return result;} ::haxe::io::Bytes Resource_obj::getBytes( ::String name){ HX_STACK_FRAME("haxe.Resource","getBytes",0x9bc1712d,"haxe.Resource.getBytes","C:\\Users\\Shane\\Downloads\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Resource.hx",33,0xb533daeb) HX_STACK_ARG(name,"name") HX_STACK_LINE(34) Array< unsigned char > array = ::__hxcpp_resource_bytes(name); HX_STACK_VAR(array,"array"); HX_STACK_LINE(35) if (((array == null()))){ HX_STACK_LINE(35) return null(); } HX_STACK_LINE(36) return ::haxe::io::Bytes_obj::ofData(array); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Resource_obj,getBytes,return ) Resource_obj::Resource_obj() { } Dynamic Resource_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"getBytes") ) { return getBytes_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic Resource_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { return super::__SetField(inName,inValue,inCallProp); } void Resource_obj::__GetFields(Array< ::String> &outFields) { super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("getBytes"), String(null()) }; #if HXCPP_SCRIPTABLE static hx::StorageInfo *sMemberStorageInfo = 0; #endif static ::String sMemberFields[] = { String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Resource_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Resource_obj::__mClass,"__mClass"); }; #endif Class Resource_obj::__mClass; void Resource_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("haxe.Resource"), hx::TCanCast< Resource_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics #ifdef HXCPP_VISIT_ALLOCS , sVisitStatics #endif #ifdef HXCPP_SCRIPTABLE , sMemberStorageInfo #endif ); } void Resource_obj::__boot() { } } // end namespace haxe
[ "misto423@gmail.com" ]
misto423@gmail.com
8e2631d01ae6256e92b2d12719ce590e95ce98de
dc66632dac12081000da3c8fe551431e4239c413
/viewer-development/indra/llui/llf32uictrl.cpp
7728292301b0a29a5d7433fdb76e70e1393568d1
[]
no_license
MAPSWorks/GIS
ea115b1d4f68fefe42aef91482d440f6c6407d7f
6bd74a125a35d33a763046a7cc506bdd7a629919
refs/heads/master
2020-04-07T16:34:38.952498
2012-02-06T20:25:34
2012-02-06T20:25:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,543
cpp
/** * @file llf32uictrl.cpp * @author Nat Goodspeed * @date 2008-09-08 * @brief Implementation for llf32uictrl. * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * GIS Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ // Precompiled header #include "linden_common.h" // associated header #include "llf32uictrl.h" // STL headers // std headers // external library headers // other Linden headers LLF32UICtrl::LLF32UICtrl(const Params& p) : LLUICtrl(p), mInitialValue(p.initial_value().asReal()), mMinValue(p.min_value), mMaxValue(p.max_value), mIncrement(p.increment) { mViewModel->setValue(p.initial_value); } F32 LLF32UICtrl::getValueF32() const { return mViewModel->getValue().asReal(); }
[ "hiz.wylder@gmail.com" ]
hiz.wylder@gmail.com
b1f1c9b866781cefa568a2ab3d46ba9ebb54b839
f1d0ea36f07c2ef126dec93208bd025aa78eceb7
/Zen/StudioPlugins/ArtLibraryModel/src/ArtAssetExplorerNodeDataCollection.cpp
a1f7e6d9d9dbcee937f831e178fb9029e20a4b53
[]
no_license
SgtFlame/indiezen
b7d6f87143b2f33abf977095755b6af77e9e7dab
5513d5a05dc1425591ab7b9ba1b16d11b6a74354
refs/heads/master
2020-05-17T23:57:21.063997
2016-09-05T15:28:28
2016-09-05T15:28:28
33,279,102
3
0
null
null
null
null
UTF-8
C++
false
false
2,123
cpp
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Zen Spaces // // Copyright (C) 2001 - 2009 Tony Richards // // Licensed under the Games by Sarge Publishing License - See your licensing // agreement for terms and conditions. // // Do not redistribute this source code. // // Tony Richards trichards@gamesbysarge.com //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // This is generated by the Zen Spaces Code Generator. Do not modify! //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #include "ArtAssetExplorerNodeDataCollection.hpp" #include "ArtAssetExplorerNodeDomainObject.hpp" //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace ArtLibrary { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ ArtAssetExplorerNodeDataCollection::ArtAssetExplorerNodeDataCollection() { } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ ArtAssetExplorerNodeDataCollection::~ArtAssetExplorerNodeDataCollection() { } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void ArtAssetExplorerNodeDataCollection::push_back(pArtAssetExplorerNodeDomainObject_type _pDomainObject) { m_objects.push_back(_pDomainObject); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ void ArtAssetExplorerNodeDataCollection::getAll(I_CollectionVisitor& _visitor) { _visitor.begin(); for(Collection_type::iterator iter = m_objects.begin(); iter != m_objects.end(); iter++) { _visitor.visit(*iter); } _visitor.end(); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ bool ArtAssetExplorerNodeDataCollection::isEmpty() const { return m_objects.empty(); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace ArtLibrary //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
[ "mgray@wintermute" ]
mgray@wintermute
75c9b637915ebef3686dd6ad1f25c9a1ced2d7bf
5654566c58aa91c269753f80ecf92b3fd76b0360
/ej4exTC2016/c++/dibujable.h
c6ab9627f23e288cd2c1186635f677e038f0f306
[]
no_license
DarFig/ejTC
0b3eb30940a16ec671628b51a5441cf0e132c03e
3697c8163f5d9158a0bc2fcdd7493c11b5d6f068
refs/heads/master
2021-06-14T06:12:56.197172
2017-04-29T17:47:20
2017-04-29T17:47:20
65,808,971
0
0
null
null
null
null
UTF-8
C++
false
false
209
h
#pragma once /* *v2016-08-16 * */ class dibujable { public: float x, y, z; dibujable(float _x, float _y, float _z) : x(_x), y(_y), z(_z){} virtual void draw() {}; virtual void update(float t){} };
[ "Napsterdos@yahoo.es" ]
Napsterdos@yahoo.es
fcf6cd3498ad72066fd29e60281d1bfa712cdf4b
0d506fd7fb335cd8b7f6e578951e8a75e8cf1626
/ch03/PointersIte.cpp
7493db079b12d568a680bf8537ec695c1eebce02
[]
no_license
imshenzhuo/CppPrimer
613b7a0a20076db599ad1f0f2187a954f7d79b84
87c74c0a36223e86571c2aedd9da428c06b04f4d
refs/heads/master
2020-07-22T15:02:20.808936
2020-02-29T16:08:40
2020-02-29T16:08:40
207,240,474
3
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
/************************************************************************* > File Name: PointersIte.cpp > Author: shenzhuo > Mail: im.shenzhuo@gmail.com > Created Time: 2019年08月28日 星期三 14时57分38秒 ************************************************************************/ #include<iostream> using namespace std; int main() { int arr[] = { 0,1,2,3,4,5,6,7,8,9 }; cout << *(end(arr)) << endl; cout << *(begin(arr)) << endl; auto n = end(arr) - begin(arr); cout << n << endl; int *p1 = arr; int *p2 = p1 + 5; cout << p1 - p2 << endl; return 0; }
[ "im.shenzhuo@gmail.com" ]
im.shenzhuo@gmail.com
0886f8fb4ebd0c325a5277a57b4c8c87a45efc33
e2ef305f927d17faf75d03d283298a42f3ff2e84
/ArUco/utils_calibration/aruco_calibration_fromimages.cpp
9b8f052418376ebde04f16117fd08485b594d777
[ "BSD-2-Clause" ]
permissive
SheehanChen/AR-with-OpenCV
285c97e47fa35d6179f9af32b8f9bee417a04739
d35fe7ec41594a1bef8e166af47cd6ad6301b11c
refs/heads/master
2022-01-08T08:04:04.434588
2019-01-09T03:17:34
2019-01-09T03:17:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,848
cpp
/** Copyright 2017 Rafael Muñoz Salinas. 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 Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Rafael Muñoz Salinas. */ #include <algorithm> #include <fstream> #include <iostream> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <sstream> #include "aruco.h" #include "aruco_calibration_grid_board_a4.h" #include "dirreader.h" #include <stdexcept> using namespace std; using namespace cv; using namespace aruco; Mat TheInputImage, TheInputImageCopy; CameraParameters TheCameraParameters; MarkerMap TheMarkerMapConfig; MarkerDetector TheMarkerDetector; string TheOutFile; string TheMarkerMapConfigFile; float TheMarkerSize = -1; string TheOutCameraParams; bool autoOrient=false; // given the set of markers detected, the function determines the get the 2d-3d correspondes void getMarker2d_3d(vector<cv::Point2f>& p2d, vector<cv::Point3f>& p3d, const vector<Marker>& markers_detected, const MarkerMap& bc) { p2d.clear(); p3d.clear(); // for each detected marker for (size_t i = 0; i < markers_detected.size(); i++) { // find it in the bc auto fidx = std::string::npos; for (size_t j = 0; j < bc.size() && fidx == std::string::npos; j++) if (bc[j].id == markers_detected[i].id) fidx = j; if (fidx != std::string::npos) { for (int j = 0; j < 4; j++) { p2d.push_back(markers_detected[i][j]); p3d.push_back(bc[fidx][j]); } } } cout << "points added" << endl; } vector<vector<cv::Point2f>> calib_p2d; vector<vector<cv::Point3f>> calib_p3d; aruco::CameraParameters camp; // camera parameters estimated class CmdLineParser { int argc;char** argv;public: CmdLineParser(int _argc, char** _argv): argc(_argc), argv(_argv){} bool operator[](string param) {int idx = -1; for (int i = 0; i < argc && idx == -1; i++)if (string(argv[i]) == param) idx = i;return (idx != -1); } string operator()(string param, string defvalue = "-1"){int idx = -1;for (int i = 0; i < argc && idx == -1; i++)if (string(argv[i]) == param) idx = i;if (idx == -1) return defvalue;else return (argv[idx + 1]);} }; /************************************ * * * * ************************************/ int main(int argc, char** argv) { try { CmdLineParser cml(argc,argv); if (argc < 3 || cml["-h"]) { cerr << "Usage: out_camera_calibration.yml directory_with_images [options] " << endl; cerr << "options:" << endl; cerr << "-size maker_size : Size of the markers in meters. " << endl; cerr << "-m markersetconfig.yml : By default, the one in utils is assumed. Otherwise, set the file here "<<endl; cerr << "-auto_orient : forces width larger than height by flipping image 90degs. " << endl; return -1; } TheMarkerSize = stof(cml("-size","1")); TheMarkerMapConfigFile=cml("-m",""); TheOutFile=argv[1]; autoOrient=cml["-auto_orient"]; // load board info if (TheMarkerMapConfigFile.empty()) { stringstream sstr; sstr.write((char*)default_a4_board, default_a4_board_size); TheMarkerMapConfig.fromStream(sstr); } else TheMarkerMapConfig.readFromFile(TheMarkerMapConfigFile); // is in meters if (!TheMarkerMapConfig.isExpressedInMeters()) { if (TheMarkerSize == -1) { cerr << "Need to specify the length of the board with -size" << endl; return -1; } else TheMarkerMapConfig = TheMarkerMapConfig.convertToMeters(TheMarkerSize); } // set specific parameters for this configuration TheMarkerDetector.setDictionary(TheMarkerMapConfig.getDictionary()); vector<string> images=DirReader::read(argv[2]); for(auto i:images)cout<<i<<endl; if (images.size()==0)throw std::runtime_error("Could not find a file in the speficied path"); cv::Size imageSize(-1, -1); // capture until press ESC or until the end of the video for(size_t currImage=0;currImage<images.size();currImage++){ cout << "reading " << images[currImage] << endl; if ( images[currImage].back()=='.') continue;//skip . and .. TheInputImage = cv::imread(images[currImage]); if (TheInputImage.cols<TheInputImage.rows && autoOrient){ cv::Mat aux; cv::transpose(TheInputImage,aux); cv::flip(aux,TheInputImage,0); } if (TheInputImage.empty()) continue;//not an image if (imageSize != cv::Size(-1, -1) && imageSize != TheInputImage.size()) { cerr << "Input image sizes must be equal" << endl; exit(0); } imageSize = TheInputImage.size(); // detect and print vector<aruco::Marker> detected_markers = TheMarkerDetector.detect(TheInputImage); vector<int> markers_from_set = TheMarkerMapConfig.getIndices(detected_markers); TheInputImage.copyTo(TheInputImageCopy); for (auto idx : markers_from_set) detected_markers[idx].draw(TheInputImageCopy, Scalar(0, 0, 255), static_cast<int>( max(float(1.f), 1.5f * float(TheInputImageCopy.cols) / 1000.f))); if (TheInputImageCopy.cols > 1280) cv::resize(TheInputImageCopy, TheInputImage, cv::Size(1280, static_cast<int>(1280.f * float(TheInputImageCopy.rows) / float(TheInputImageCopy.cols)))); else TheInputImageCopy.copyTo(TheInputImage); vector<cv::Point2f> p2d; vector<cv::Point3f> p3d; getMarker2d_3d(p2d, p3d, detected_markers, TheMarkerMapConfig); if (p3d.size() > 0) { calib_p2d.push_back(p2d); calib_p3d.push_back(p3d); } // show input with augmented information and the thresholded image cv::imshow("in", TheInputImage); // write to video if required cv::waitKey(100); // wait for key to be pressed } ; cout << "Starting calibration" << endl; vector<cv::Mat> vr, vt; camp.CamSize = imageSize; cout << calib_p2d.size() << endl; cv::calibrateCamera(calib_p3d, calib_p2d, imageSize, camp.CameraMatrix, camp.Distorsion, vr, vt); //compute the average reprojection error std::pair<double,int> sum={0,0}; for(size_t v=0;v<calib_p2d.size();v++){ vector<cv::Point2f> repj; cv::projectPoints(calib_p3d[v],vr[v],vt[v],camp.CameraMatrix, camp.Distorsion, repj); for(size_t p=0;p<calib_p3d[v].size();p++){ sum.first+=cv::norm(repj[p]-calib_p2d[v][p]); sum.second++; } } cerr << "repj error=" << sum.first/double(sum.second) << endl; camp.saveToFile(TheOutFile); cerr << "File saved in :" << TheOutFile << endl; } catch (std::exception& ex) { cout << "Exception :" << ex.what() << endl; } }
[ "wutongyuxuan@163.com" ]
wutongyuxuan@163.com
37fcced85067cf66aaa246479aed88e74853afd1
6694676178f274c1c83a4ca3c699ab126ff164c3
/src/Human.hpp
f558b2305a3601995f096cc3d2b89c6316690954
[]
no_license
Batname/directives_makefile_example
cfed309ed68f5637f2a20b567dfa6a2d41c5fd22
c28361f8d99d4cf101dea59bb1ffab305c0d565b
refs/heads/master
2021-01-21T17:38:35.642552
2017-05-21T17:34:45
2017-05-21T17:34:45
91,975,571
0
0
null
null
null
null
UTF-8
C++
false
false
137
hpp
#ifndef HUMAN #define HUMAN class Human { public: Human(int age); void PrintAge(); protected: private: int Age; }; #endif
[ "dadubinin@gmail.com" ]
dadubinin@gmail.com
4c7aa0090b48fe1e8b2acfd4024a25524e15b975
33a52c90e59d8d2ffffd3e174bb0d01426e48b4e
/uva/00200-/00273.cc
83d14fc1d7aeb0d593f387d7da02adce40cfc77a
[]
no_license
Hachimori/onlinejudge
eae388bc39bc852c8d9b791b198fc4e1f540da6e
5446bd648d057051d5fdcd1ed9e17e7f217c2a41
refs/heads/master
2021-01-10T17:42:37.213612
2016-05-09T13:00:21
2016-05-09T13:00:21
52,657,557
0
0
null
null
null
null
UTF-8
C++
false
false
2,296
cc
#include<iostream> #include<complex> #include<algorithm> #define SEG 20 #define OPE 100000 using namespace std; typedef complex<int> Point; class Segment{ public: Point bgn, end; Segment(){} Segment(Point b, Point e): bgn(b), end(e){} }; class Dset{ public: int nSet; int adj[SEG], rank[SEG]; Dset(){ nSet = 0; } void makeSet(int n){ adj[n] = n; rank[n] = 0; nSet++; } void merge(int a, int b){ if(find(a)!=find(b)) link(find(a),find(b)); } int find(int n){ if(adj[n]!=n) adj[n] = find(adj[n]); return adj[n]; } void link(int a, int b){ nSet--; if(rank[a]>rank[b]) swap(a,b); adj[a] = b; if(rank[a]==rank[b]) rank[b]++; } }; int nSeg, nOpe, ope[OPE][2]; Segment seg[SEG]; void read(){ cin >> nSeg; for(int i=0;i<nSeg;i++){ int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; seg[i] = Segment(Point(x1,y1),Point(x2,y2)); } nOpe = 0; while(true){ cin >> ope[nOpe][0] >> ope[nOpe][1]; if(ope[nOpe][0]==0 && ope[nOpe][1]==0) break; ope[nOpe][0]--, ope[nOpe][1]--; nOpe++; } } int cross(Point a, Point b){ return imag(conj(a)*b); } int ccw(Point a, Point b, Point c){ int ret = cross(b-a,c-a); if(ret==0) return 0; return (ret>0 ? 1:-1); } bool isIntersect(Segment a, Segment b){ Point a1, a2, b1, b2; a1 = a.bgn, a2 = a.end; b1 = b.bgn, b2 = b.end; if(min(a1.real(),a2.real())>max(b1.real(),b2.real())) return false; if(min(a1.imag(),a2.imag())>max(b1.imag(),b2.imag())) return false; if(min(b1.real(),b2.real())>max(a1.real(),a2.real())) return false; if(min(b1.imag(),b2.imag())>max(a1.imag(),a2.imag())) return false; return (0>=ccw(a1,a2,b1)*ccw(a1,a2,b2) && 0>=ccw(b1,b2,a1)*ccw(b1,b2,a2)); } void work(){ Dset sets = Dset(); for(int i=0;i<nSeg;i++) sets.makeSet(i); for(int i=0;i<nSeg;i++) for(int j=i+1;j<nSeg;j++) if(isIntersect(seg[i],seg[j])) sets.merge(i,j); for(int i=0;i<nOpe;i++){ if(sets.find(ope[i][0])==sets.find(ope[i][1])) cout << "CONNECTED" << endl; else cout << "NOT CONNECTED" << endl; } } int main(){ int cases; cin >> cases; for(int i=0;i<cases;i++){ if(i) cout << endl; read(); work(); } return 0; }
[ "ben.shooter2@gmail.com" ]
ben.shooter2@gmail.com
636bcda2c254522e5d3be094445e81e8af75ba78
afcb975d20a26f4437a6e865768f8f8e0797face
/quant/quant.h
75cbc742faa6d7ad292aab9144a145e1f498372c
[]
no_license
asialiugf/study
5f1a3c9a34b7018d956fb0fec31be21d7eac70ad
2072227683d060b00d3bebd92a06223d59a7f487
refs/heads/master
2023-07-08T15:06:58.834805
2021-08-15T08:22:23
2021-08-15T08:22:23
77,110,795
0
0
null
null
null
null
UTF-8
C++
false
false
344
h
#ifndef _SEE_QUANT #define _SEE_QUANT 1 #pragma GCC system_header #include <bits/c++config.h> #include <ostream> #include <istream> namespace SEE(default) { class BAR { public: double h; double o; double c; double l; double v; char date[8]; char time[8]; } } /* end of namespace SEE */ #endif /* _SEE_QUANT */
[ "asialiugf@sina.com" ]
asialiugf@sina.com
a8c52f1d67a5a212f269c9406981a7759ab0b56d
1086ef8bcd54d4417175a4a77e5d63b53a47c8cf
/Forks/Online-Judges-Problems-SourceCode-master/UVa/10337 - Flight Planner.cpp
d897d78db17fbfcbb207a430ac9c93b40b3f80b3
[]
no_license
wisdomtohe/CompetitiveProgramming
b883da6380f56af0c2625318deed3529cb0838f6
a20bfea8a2fd539382a100d843fb91126ab5ad34
refs/heads/master
2022-12-18T17:33:48.399350
2020-09-25T02:24:41
2020-09-25T02:24:41
298,446,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,416
cpp
//============================================================================ // File : 10337 - Flight Planner.cpp // Author : AHMED HANI IBRAHIM // Copyright : AHani // Version : UVa - Accepted - 0.008 // Created on September 7, 2012, 6:39 PM //============================================================================ //#include <cstdlib> #include <stdio.h> #include <string.h> //#include <string> //#include <iostream> //#include <map> #include <algorithm> //#include <functional> #define MaxWS 10 #define Max 1000 + 5 #define INF 1000000000 //#define INT_MAX 2147483647 #define FOR(i, N) for( int i = 0 ; i < N ; i++ ) //#define FOR1e(i, N) for( int i = 1 ; i <= N ; i++ ) //#define FORe(i, N) for(int i = 0 ; i <= N ; i++ ) #define FORg(i, N) for(int i = N ; i >= 0 ; i-- ) using namespace std; int TestCases, Target; int Grid[MaxWS][Max], Cost[MaxWS][Max]; unsigned int Solve(int Altitude, int Distance, int Targ){ int Climb, Remain, Down; if ( Distance == Targ && !Altitude) return 0; if ( Distance == Targ || Altitude < 0 || Altitude > 9 ) return INF; if ( Cost[Altitude][Distance] != -1 ) return Cost[Altitude][Distance]; if ( Altitude == NULL ){ if ( Distance == Targ - 1) return Cost[Altitude][Distance] = 30 - Grid[Altitude][Distance] + Solve(Altitude, Distance + 1, Targ); else{ Climb = 60 - Grid[Altitude][Distance] + Solve(Altitude + 1, Distance + 1, Targ); Remain = 30 - Grid[Altitude][Distance] + Solve(Altitude, Distance + 1, Targ); return Cost[Altitude][Distance] = min(Climb, Remain); } }else{ Climb = 60 - Grid[Altitude][Distance] + Solve(Altitude + 1, Distance + 1, Targ); Remain = 30 - Grid[Altitude][Distance] + Solve(Altitude, Distance + 1, Targ); Down = 20 - Grid[Altitude][Distance] + Solve(Altitude - 1, Distance + 1, Targ); return Cost[Altitude][Distance] = min(min(Climb, Remain), Down); } } int main(int argc, char** argv) { // freopen("Trojan.txt", "r", stdin); scanf("%d", &TestCases); while ( TestCases-- ){ scanf("%d", &Target); Target /= 100; FORg(i, 9) FOR(j, Target){ scanf("%d",&Grid[i][j]); } memset(Cost, -1, sizeof(Cost)); printf("%u\n\n", Solve(NULL, NULL, Target)); } return 0; }
[ "elmanciowisdom@gmail.com" ]
elmanciowisdom@gmail.com
bad6cbe4ca162ece9d478f39deb2672d40fbc91b
5fb0ce19853cdbf21543b438272ca187e063a433
/solutions/easy/728.cpp
3b2bd4c767e0538b5632bfb8c1d94407446a0624
[]
no_license
temanisparsh/leetcode
f4238dc0566239ac807d3e131e31af3d6c6cf05b
5e291843ddf9deba3e2f28804dc38395e1025f1d
refs/heads/master
2023-03-28T13:38:01.607424
2020-10-16T13:41:54
2020-10-16T13:41:54
294,234,906
9
1
null
2020-10-15T17:39:54
2020-09-09T21:34:43
JavaScript
UTF-8
C++
false
false
533
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> res; for(int i = left; i <= right; i++) { int isValid = 1; int num = i; while (num) { int rem = num % 10; if (rem == 0 || i % rem != 0) isValid = 0; num /= 10; } if (isValid) res.push_back(i); } return res; } };
[ "sparshtemani31415@gmail.com" ]
sparshtemani31415@gmail.com
750e24459d89f5a1ef83997dcce955bce8d0c67a
aba765c5993b8d1074622441089a55a1610ce18e
/snap/glib-core/bd.cpp
472276f73bd8d132f881dffc2ed92ba1097dc7bf
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
karmaresearch/trident
cbf3dfa7d81c93ac40c76782564d0e453f605fa3
621ed49c648c811d5f69617833539f419766d3be
refs/heads/master
2023-08-03T23:09:38.295697
2023-07-19T07:21:15
2023-07-19T07:21:15
97,223,343
23
9
Apache-2.0
2021-09-30T09:04:25
2017-07-14T10:40:40
C++
UTF-8
C++
false
false
4,025
cpp
#if SW_TRACE #include <execinfo.h> #endif ///////////////////////////////////////////////// // Mathmatical-Errors #if defined(__BCPLUSPLUS__) && (__BCPLUSPLUS__==0x0530) struct __exception { int type; /* Exception type */ char* name; /* Name of function causing exception */ double arg1; /* 1st argument to function */ double arg2; /* 2nd argument to function */ double retval; /* Function return value */ }; int std::_matherr(struct math_exception* e){ e->retval=0; return 1; } #elif defined(GLib_GLIBC) || defined(GLib_BSD) struct __exception { int type; /* Exception type */ char* name; /* Name of function causing exception */ double arg1; /* 1st argument to function */ double arg2; /* 2nd argument to function */ double retval; /* Function return value */ }; int _matherr(struct __exception* e){ e->retval=0; return 1; } #elif defined(GLib_SOLARIS) int _matherr(struct __math_exception* e){ e->retval=0; return 1; } #elif defined(GLib_CYGWIN) int matherr(struct __exception *e){ e->retval=0; return 1; } #elif defined(GLib_MACOSX) //int matherr(struct exception *e) { // e->retval=0; // return 1; //} #else int _matherr(struct _exception* e){ e->retval=0; return 1; } #endif ///////////////////////////////////////////////// // Messages void WrNotify(const char* CaptionCStr, const char* NotifyCStr){ #if defined(__CONSOLE__) || defined(_CONSOLE) printf("*** %s: %s\n", CaptionCStr, NotifyCStr); #else MessageBox(NULL, NotifyCStr, CaptionCStr, MB_OK); #endif } void SaveToErrLog(const char* MsgCStr){ int MxFNmLen=1000; char* FNm=new char[MxFNmLen]; if (FNm==NULL){return;} int FNmLen=GetModuleFileName(NULL, FNm, MxFNmLen); if (FNmLen==0){return;} FNm[FNmLen++]='.'; FNm[FNmLen++]='E'; FNm[FNmLen++]='r'; FNm[FNmLen++]='r'; FNm[FNmLen++]=char(0); time_t Time=time(NULL); FILE* fOut=fopen(FNm, "a+b"); if (fOut==NULL){return;} fprintf(fOut, "--------\r\n%s\r\n%s%s\r\n--------\r\n", FNm, ctime(&Time), MsgCStr); fclose(fOut); delete[] FNm; } #if SW_TRACE void PrintBacktrace() { // stack dump, works for g++ void *array[20]; size_t size; // flush stdout fflush(0); // get the trace and print it to stdout size = backtrace(array, 20); backtrace_symbols_fd(array, size, 1); } void Crash() { int *p; p = (int *) 0; *p = 1234; } #endif ///////////////////////////////////////////////// // Assertions TOnExeStop::TOnExeStopF TOnExeStop::OnExeStopF=NULL; void ExeStop( const char* MsgCStr, const char* ReasonCStr, const char* CondCStr, const char* FNm, const int& LnN){ char ReasonMsgCStr[1000]; #if SW_TRACE PrintBacktrace(); Crash(); #endif // construct reason message if (ReasonCStr==NULL){ReasonMsgCStr[0]=0;} else {sprintf(ReasonMsgCStr, " [Reason:'%s']", ReasonCStr);} // construct full message char FullMsgCStr[1000]; if (MsgCStr==NULL){ if (CondCStr==NULL){ sprintf(FullMsgCStr, "Execution stopped%s!", ReasonMsgCStr); } else { sprintf(FullMsgCStr, "Execution stopped: %s%s, file %s, line %d", CondCStr, ReasonMsgCStr, FNm, LnN); } } else { if (CondCStr==NULL){ sprintf(FullMsgCStr, "%s\nExecution stopped!", MsgCStr); } else { sprintf(FullMsgCStr, "Message: %s%s\nExecution stopped: %s, file %s, line %d", MsgCStr, ReasonMsgCStr, CondCStr, FNm, LnN); } } // report full message to log file SaveToErrLog(FullMsgCStr); #if defined(SW_NOABORT) TExcept::Throw(FullMsgCStr); #endif // report to screen & stop execution bool Continue=false; // call handler if (TOnExeStop::IsOnExeStopF()){ Continue=!((*TOnExeStop::GetOnExeStopF())(FullMsgCStr));} if (!Continue){ ErrNotify(FullMsgCStr); #ifdef GLib_WIN32 abort(); //ExitProcess(1); #else exit(1); #endif } }
[ "jacopo@cs.vu.nl" ]
jacopo@cs.vu.nl
13b31618ef1901ddca884129f0ad0af45d5df8e9
eb9b85c5ebeb4f464b3ef3f31f2afa1f0f0118ec
/src/Graphics/window.h
fb2c6f3f3196beddf8c0c4c18e964720a110a342
[]
no_license
jaankaup/my_opencl_project
d21279ff437f63c97ae5204fd011563e6c85a4ee
bd41cb1403f315d0ce412d8818649aa0308c0e62
refs/heads/main
2023-04-06T17:29:57.712474
2019-09-30T14:31:28
2019-09-30T14:31:28
362,106,978
0
0
null
null
null
null
UTF-8
C++
false
false
1,033
h
#ifndef WINDOW_H #define WINDOW_H //#include <memory> //#include <memory> #include <SDL2/SDL.h> #include <GL/glew.h> #include "../Program/InputCache.h" struct SDL_Window; using SDL_GLContext = void*; /* A window class using SDL2 window. */ class Window { public: static Window* getInstance(); // Swaps buffers. void swapBuffers(); // Resize method for window. // void resize(InputCache* ic); void resize(int w, int h); void set_vsync(const bool enabled) const; void setTitle(const std::string& title) const; std::string getTitle() const; // Initializes window. bool init(int width, int height); void renderImgui(); // Doesn't destroy the SDL2 and window. Call dispose to do this. ~Window(); private: SDL_Window* pWindow = NULL; SDL_GLContext pContext = NULL; // Creates a window and initializes SDL2. Window(); // Disposes the window. Destroys both window and SDL2. void dispose(); }; // Class window #endif //WINDOW_H
[ "janne.a.kauppinen@student.jyu.fi" ]
janne.a.kauppinen@student.jyu.fi
2347bb494c43a184599bcfa92faced8541c3e3b1
b4feb23bc7e97aa9bdf5e123e61c4c977b79e26c
/OpenWinL_cpp/Manager.cpp
cefefe80c332f2f4010896c4205e67ad32534a77
[]
no_license
yuni-net/OpenWinL
d29aa5c35e65a338626b7f415185d8c2f686b4e0
8365fc3fe718aff0c1b43c747ec17764da8500e6
refs/heads/master
2021-01-10T21:58:02.156043
2015-11-03T21:30:28
2015-11-03T21:30:28
41,798,308
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include <Manager.h> #include <popular.h> #include <Window.h> namespace ow { bool Manager::init() { const int default_width = 960; const int default_height = 600; return get_instance().init_dynamic(default_width, default_height); } bool Manager::init(const int screen_width, const int screen_height) { return get_instance().init_dynamic(screen_width, screen_height); } bool Manager::begin_frame() { return get_instance().begin_frame_dynamic(); } void Manager::show() { get_instance().show_dynamic(); } const Time & Manager::get_time() { return *(get_instance().time); } Manager & Manager::get_instance() { static Manager manager; return manager; } #ifdef ow_implement_is_DirectX9_ bool Manager::init_dynamic(const int screen_width, const int screen_height) { window.reset(new Window(screen_width, screen_height)); time.reset(new Time()); return true; } bool Manager::begin_frame_dynamic() { time->update(); return window->can_I_continue(); } void Manager::show_dynamic() { window->show(); } #endif #ifdef ow_implement_is_OpenGL_ bool Manager::init_dynamic(const int screen_width, const int screen_height) { if (glfwInit() == GL_FALSE) { return false; } window.reset(new Window(screen_width, screen_height)); return true; } bool Manager::begin_frame_dynamic() { glfwPollEvents(); time->update(); return window->can_I_continue(); } void Manager::show_dynamic() { window->show(); } #endif }
[ "yuni.net.liberty@gmail.com" ]
yuni.net.liberty@gmail.com
a46fd5b09de759719fb7e3dbe566d888f1da71ea
bb287b07de411c95595ec364bebbaf44eaca4fc6
/src/transactions/SignatureUtils.h
f9f829600625cd5e78e5c470ed58c185b613009e
[ "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT", "BSD-2-Clause" ]
permissive
viichain/vii-core
09eb613344630bc80fee60aeac434bfb62eab46e
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
refs/heads/master
2020-06-28T06:33:58.908981
2019-08-14T02:02:13
2019-08-14T02:02:13
200,164,931
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#pragma once #include "xdr/vii-types.h" namespace viichain { class ByteSlice; class SecretKey; struct DecoratedSignature; struct SignerKey; namespace SignatureUtils { DecoratedSignature sign(SecretKey const& secretKey, Hash const& hash); bool verify(DecoratedSignature const& sig, SignerKey const& signerKey, Hash const& hash); DecoratedSignature signHashX(const ByteSlice& x); bool verifyHashX(DecoratedSignature const& sig, SignerKey const& signerKey); SignatureHint getHint(ByteSlice const& bs); bool doesHintMatch(ByteSlice const& bs, SignatureHint const& hint); } }
[ "viichain" ]
viichain
973acca9a09a7f29bd23fadaebd5e95aab6847f6
a61a21484fa9d29152793b0010334bfe2fed71eb
/Skyrim/src/BSScript/BSScriptClass.cpp
51ae93ab76fb1d13b2d31d3daccb81f4f259ab07
[]
no_license
kassent/IndividualizedShoutCooldowns
784e3c62895869c7826dcdbdeea6e8e177e8451c
f708063fbc8ae21ef7602e03b4804ae85518f551
refs/heads/master
2021-01-19T05:22:24.794134
2017-04-06T13:00:19
2017-04-06T13:00:19
87,429,558
3
3
null
null
null
null
UTF-8
C++
false
false
1,030
cpp
#include "Skyrim.h" #include "Skyrim/BSScript/BSScriptClass.h" #include "Skyrim/BSScript/BSScriptIFunction.h" #include <string.h> namespace BSScript { bool BSScriptClass::IsBaseOf(const BSScriptClass* a_cass) const { const BSScriptClass* p = a_cass; while (p) { if (p == this) break; p = p->GetParent(); } return (p != nullptr); } IFunction* BSScriptClass::FindFunction(const char * name) { IFunction ** funcs = GetFunctions(); const UInt32 num = GetNumGlobalFunctions() + GetNumMemberFunctions(); for (UInt32 i = 0; i < num; i++) { IFunction * p = funcs[i]; if (p) { const BSFixedString &funcName = p->GetName(); if (_stricmp(funcName.c_str(), name) == 0) { return p; } } } return nullptr; } bool BSScriptClass::IsHidden() { static BSFixedString hidden = "hidden"; return GetScriptFlag(hidden, true); } bool BSScriptClass::IsConditional() { static BSFixedString conditional = "conditional"; return GetScriptFlag(conditional, true); } }
[ "wangzhengzewzz@gmail.com" ]
wangzhengzewzz@gmail.com
dc4f8c9a1f3b95d405b4d0a72a08bc17bb7eedd6
6db4d9744ecb7ab23b9107bb80d90d31984916da
/samples/LHW/Classes/game/ViewGameTap.cpp
7ac22c5e13bb881dc76c2f649d49b0152efeb71e
[]
no_license
centurywar/LHW
32d7a26f6712386219160c3d8c38957cf908b9cb
d17a71867962f2fda6d2edec4fa6efa546e1824d
refs/heads/master
2021-01-24T03:36:26.736594
2012-12-22T16:58:59
2012-12-22T16:58:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,569
cpp
// // ViewGameTap.cpp // TestCpp // // Created by 万斌 on 12-12-16. // // #include "ViewGameTap.h" ViewGameTap::ViewGameTap() { labTitle->setString("Ready?"); tapCount = 0; tapTime = 5; btnFrog = CCMenuItem::create(this, menu_selector(ViewGameTap::forgTog)); btnFrog->setPosition(ccp(window.width/2, window.height/2)); btnFrog->setContentSize(CCSize(250,200)); btnFrog->setScale(0.7); btnFrog->setAnchorPoint(CCPointMake(0.5, 0.5)); btnFrog->setEnabled(false); CCSprite * btnBg = CCSprite::createWithSpriteFrameName(s_z3); btnBg->setAnchorPoint(CCPointZero); btnFrog->addChild(btnBg); menu->addChild(btnFrog); gameStatus = statusInit; timeReset(tapTime, false); } void ViewGameTap::forgTog() { if(gameStatus==statusStart) { tapCount++; char temstr[5]; forgMove(); sprintf(temstr,"%d", tapCount); labTitle->setString(temstr); } // timeTag(); } void ViewGameTap::forgMove() { int x = 100 , y=40,newx,oldx; newx = x+rand()%600; oldx = btnFrog->getPositionX(); btnFrog->removeAllChildrenWithCleanup(false); CCSprite * btnBg =NULL; if(newx>oldx) { btnBg=CCSprite::createWithSpriteFrameName(s_z4); btnBg->setScale(2); } else{ btnBg=CCSprite::createWithSpriteFrameName(s_z2); } btnBg->setAnchorPoint(CCPointZero); btnFrog->addChild(btnBg); CCSize tem = btnBg->getContentSize(); // btnFrog->setContentSize(btnBg->getContentSize()); CCAction *temAction = CCMoveTo::create(0.05, CCPointMake(newx, y+rand()%400)); btnFrog->runAction(temAction); } void ViewGameTap::gameStart() { ViewGameBase::gameStart(); btnReady->setEnabled(false); btnFrog->setEnabled(true); labTitle->setString("0"); forgTog(); forgMove(); timeStart(); } void ViewGameTap::gameReStart() { ViewGameBase::gameReStart(); tapCount = 0; timeReset(tapTime, false); } void ViewGameTap::gameEnd() { gameStatus = statusEnd; btnFrog->setEnabled(false); int star = max(getStar(), 1); addTotalStar(star); addTotalCoin(tapTime); ViewGameBase::gameEnd(); if(star>getLevelStar()) { setLevelStar(star); } if(star>=1) { openNextLevel(); } labFont->setString("The End"); btnReady->setEnabled(false); } int ViewGameTap::getLevel() { return layerTap; } int ViewGameTap::getStar() { if(gameStatus==statusEnd) { return MIN(5, floor(tapCount/4)); } return -1; }
[ "wanbin89731@163.com" ]
wanbin89731@163.com
308c0db0bb1be3933856342ad927a742890f7cb9
06dfcdaf0c432e4488f162f7b6d4a583a450600a
/programmers/level3/단속카메라.cpp
9d51deadd583ba76621edd909a3cf1361f137148
[]
no_license
sumniy/algorithm_study
3941534a323e93cfca370f5d6614d6582ba10348
a02faeb4e208764849414ae7f355855808221311
refs/heads/master
2020-12-12T04:13:07.798260
2020-10-16T15:20:46
2020-10-16T15:20:46
234,039,807
0
0
null
2020-05-06T04:34:47
2020-01-15T08:58:27
C++
UTF-8
C++
false
false
1,054
cpp
#include <string> #include <vector> #include <queue> #include <algorithm> #include <iostream> using namespace std; bool cmp(vector<int> a, vector<int> b) { return a[0] < b[0]; } int solution(vector<vector<int>> routes) { ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int answer = 1; sort(routes.begin(), routes.end(), cmp); int size = routes.size(); int tmp = routes[0][1]; for(int i=0;i<size-1;i++) { // 지금 tmp의 구간안에서 가장 빨리 빠져나가는 차량을 기준으로 tmp를 다시 잡는다. 차량이 빠져나가는 순간이 그 구간에 겹치는 차량의 수가 최대인 순간이 되기 때문이다. if(tmp > routes[i][1]) tmp = routes[i][1]; // 먼저 출발한 차들이 다 빠져나간뒤의 시간에 i+1번째 차량이 출발한다면 감시 카메라가 필요한 새로운 구간이 생기는 것이다 if(routes[i+1][0] > tmp) { answer++; tmp = routes[i+1][1]; } } return answer; }
[ "sumniy94@gmail.com" ]
sumniy94@gmail.com
7094207c46ea52c69543366d55936e3c9e80171c
4691982b2a5641baa142d68f6f90a7c0defa58d9
/code3save/main.cpp
8bed7972491adc6c3bb1b171363764b301938c8e
[]
no_license
WillieTaylor/simgen
f31464a6e2f4f5531be36e1e99a48b6250197add
b10a0be6d8462b802b29e4e42501aa9e5dc295eb
refs/heads/master
2021-01-11T06:19:41.807880
2017-01-10T15:22:15
2017-01-10T15:22:15
69,450,888
4
1
null
null
null
null
UTF-8
C++
false
false
5,794
cpp
#include "util.hpp" #include "geom.hpp" #include "cell.hpp" #include "data.hpp" int argcin; char** argvin; void params ( FILE* ); void models ( FILE* ); void driver (); void bumper (); void shaker (); void potter ( int, int ); void tinker ( float, int, int, int ); void keeper ( Cell* ); void bonder ( Cell* ); void linker ( Cell* ); void center (); void sorter (); void viewer ( int, char** ); void presort (); void driver (); // in application directory void looker (); // in application directory Cell* setScene ( Cell* ); void fixSSEaxis( Cell*, float ); void fixRNAstem( Cell*, float ); // 100000000 = 1/10 sec. long nanos = 100000000; // good speed for watching int delay = 1;//10; int lastlook = 0; float atom2pdb; // scale factor void *acts ( void *ptr ) { sleep(1); // delay start to allow stuff to be set printf("Starting driver\n"); while (1) { driver(); // application control (user provided) timeout(nanos); } } void *look ( void *ptr ) { sleep(1); printf("Starting looker \n"); while (1) { // looker() should contain its own timeout delay looker(); // watches and measures things (user provided) lastlook++; } } void *fixs ( void *ptr ) { float weight = (float)nanos/100000000.0; // = 1 when speed = 1, .1 for 10, .01 for 100 sleep(1); // delay start to allow ends to be set printf("Starting fixers \n"); weight *= 0.001; // use fixed weight while (1) { fixSSEaxis(Cell::world,weight); fixRNAstem(Cell::world,weight); timeout(nanos); /* fixRNAaxis(world,0,weight); nanosleep(&wait,NULL); fixRNAstem(world,0,weight); nanosleep(&wait,NULL); fixDOMaxis(world,0,1.0); fixANYaxis(world,0,weight); nanosleep(&wait,NULL); reset2axis(world,0,weight); */ if (Data::frozen) // update the focus position and heat values { Cell *focus = Cell::uid2cell[abs(Data::frozen)]; float size = focus->len; size *= size; Data::focus = focus->xyz; FOR(i,Cell::total+1) // set heat from the squared distance from the focus { Cell *c = Cell::uid2cell[i]; float dd; if (c->heat > 1.0) continue; // flag for exempt level (over focus) dd = c->xyz || Data::focus; if (dd < size) { c->heat = 1.0; } else { c->heat = exp(-dd*0.1/size); } } } } } void *move ( void *ptr ) { printf("Starting mover\n"); while (1) { int fix = abs(Data::tinker); Data::frame++; shaker(); // makes random displacements at all levels keeper(Cell::world); // keeps children inside their parent center(); // keeps children centred on their parent if (fix>0 && (Data::frame%fix)==0) { tinker(0.5,Data::depth,0,1); // geometry patch-up using stored local data } timeout(nanos); } } void *link ( void *ptr ) { printf("Starting linker \n"); while (1) { bonder(Cell::world); linker(Cell::world); timeout(nanos); } } void *rank ( void *ptr ) { printf("Starting sorter \n"); while (1) { sorter(); // sorts the ranked lists timeout(1,nanos); // <------------NB + 1 sec. } } void *bump ( void *ptr ) { printf("Starting bumper \n"); while (1) { bumper(); timeout(nanos/100); } } void *pots ( void *ptr ) { struct timespec start, finish; long runtime, delay; int m = Data::depth; char *flag = (char*)ptr; int cycles = 1; printf("Starting molecular dynamics for %s\n", flag); while(1) { timespec start,finish; clock_gettime(CLOCK_REALTIME, &start); if (flag[0]=='a') { potter(m,cycles); } else { DO1(i,m-1) potter(i,(cycles*m)/i); } clock_gettime(CLOCK_REALTIME, &finish); runtime = timedifL(start,finish); if (runtime < nanos) { delay = nanos - runtime; //Ps(flag) Pt(waiting for) Pi(delay) Pi(cycles) NL timeout(delay); cycles++; } } } void *view ( void *ptr ) { printf("Starting viewer \n"); viewer(argcin,argvin); // sets-up graphical objects (types) then runs by callback } main ( int argc, char** argv ) { pthread_t thread[10]; FILE *run; int i, j, m, n; long rseed = (long)time(0); srand48(rseed); if (argc>2) { int speed; sscanf(argv[2],"%d", &speed); if (speed > 0) nanos /= speed; if (speed < 0) nanos *= -speed; Pt(Running at) Pi(speed) NL } run = 0; if (argc > 1) run = fopen(argv[1],"r"); if (!run) { printf("Assume test.run\n"); run = fopen("test.run","r"); if (!run) { printf("No test.run file\n"); return 1; } } Cell::world = new Cell; // create the top-level cell structure (set in models()) params(run); models(run); fclose(run); Pi(Cell::total) NL Pi(Data::depth) NL Pr(Data::shrink) NL Cell::world->print(); Cell::world->move(-Cell::world->xyz); Pt(Reset) Pv(Cell::world->xyz) NL Cell::scene = setScene(Cell::world); Cell::scene->sort = 0; presort(); Data::frame = -10; argcin=argc; argvin=argv; if (Data::noview) { Pt(No viewing) NL } else { pthread_create( thread+0, 0, view, 0 ); } pthread_create( thread+1, 0, rank, 0 ); if (Data::norun < 2) { // skipped on NOMOVE pthread_create( thread+2, 0, move, 0 ); pthread_create( thread+3, 0, bump, 0 ); pthread_create( thread+4, 0, link, 0 ); pthread_create( thread+5, 0, fixs, 0 ); } if (Data::norun==0) { // skipped on NORUN pthread_create( thread+6, 0, acts, 0 ); pthread_create( thread+7, 0, look, 0 ); } /* toy MD calls pthread_create( thread+8, 0, pots, (void*)"atoms" ); pthread_create( thread+9, 0, pots, (void*)"other" ); */ sleep(99999); } /* code to stretch chain if (Data::frame<200) { FOR(i,Cell::total) { Cell *c=Cell::uid2cell[i]; if (c->level==3) c->xyz.x -= 0.005*(i-Cell::total/2); } FOR(i,Cell::total) { Cell *c=Cell::uid2cell[i]; if (c->level==2) { Vec x = (c->endC - c->endN)*0.5; c->xyz = c->starts->xyz & c->finish->xyz; c->endN = c->xyz-x; c->endC = c->xyz+x; } } nanosleep(&wait,NULL); continue; } */
[ "william.taylor@crick.ac.uk" ]
william.taylor@crick.ac.uk
8fe1a3e47127244a85ad445b7375f555de584de7
481c025d70a45a5861ab0ae9f3fe009647b46651
/Assignment 8/repeatArrayMain.cpp
351f15b5a28190497bb5a5f6c2eef4867bb441c3
[]
no_license
cfrisby/CS161
1f8a83cb1e15a1143780f99c2648c92d51c7f572
5f052b6178f18d61f8881fdeacf8a419b029e50f
refs/heads/master
2021-07-14T01:22:03.291665
2019-04-27T03:48:46
2019-04-27T03:48:46
100,557,038
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include <iostream> using std::cout; using std::endl; void repeatArray(double* &array, int size); int main() { double* myArray = new double[10]; for (int i=0; i<10; i++) myArray[i] = (i+3)*8; repeatArray(myArray, 10); for (int i=0; i<20; i++) cout << myArray[i] << endl; delete []myArray; }
[ "cuylerfris@gmail.com" ]
cuylerfris@gmail.com
83f2c346427c5b83e690fc93823e0dc842da725e
c7272e93df5e9f68c36385308da28a944e300d9d
/350. Intersection of Two Arrays II.h
2cb77548ad64dbeab962d94fbcbe2f333318e184
[ "MIT" ]
permissive
Mids/LeetCode
368a941770bc7cb96a85a7b523d77446717a1f31
589b9e40acfde6e2dde37916fc1c69a3ac481070
refs/heads/master
2023-08-13T13:39:11.476092
2021-09-26T09:29:18
2021-09-26T09:29:18
326,600,963
1
0
null
null
null
null
UTF-8
C++
false
false
781
h
// // Created by jin on 1/14/2021. // #ifndef LEETCODE_350_INTERSECTION_OF_TWO_ARRAYS_II_H #define LEETCODE_350_INTERSECTION_OF_TWO_ARRAYS_II_H #include<algorithm> using namespace std; class Solution { public: vector<int> intersect(vector<int> &nums1, vector<int> &nums2) { int size1 = nums1.size(), size2 = nums2.size(); if (size1 == 0) return nums1; if (size2 == 0) return nums2; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> result; int i1 = 0, i2 = 0; while (i1 < size1 && i2 < size2) { if (nums1[i1] > nums2[i2]) ++i2; else if (nums1[i1] < nums2[i2]) ++i1; else { result.push_back(nums1[i1]); ++i1, ++i2; } } return result; } }; #endif //LEETCODE_350_INTERSECTION_OF_TWO_ARRAYS_II_H
[ "jinpark.dev@gmail.com" ]
jinpark.dev@gmail.com
75dc2332dab648efe2b3d1f6bc74f628ad6a3542
91b98f84f22ee2f2491141f808593cd78c139d7f
/treelodreferencecaching.h
9518f2ce630849d845c8c9fc038317efba4979b0
[ "MIT" ]
permissive
rollingrock/EngineFixesVR
67f0077169712b0a22280e2e5038d234237235d1
d936583776561053421a4c6bed0d9de440d53556
refs/heads/master
2023-02-12T21:53:51.157463
2023-01-30T21:01:37
2023-01-30T21:01:37
254,220,945
75
9
MIT
2023-01-30T20:34:08
2020-04-08T23:10:07
C++
UTF-8
C++
false
false
458
h
#pragma once #include "skse64/GameEvents.h" namespace patches { class CellEventHandler : public BSTEventSink<TESCellAttachDetachEvent> { public: virtual EventResult ReceiveEvent(TESCellAttachDetachEvent* evn, EventDispatcher<TESCellAttachDetachEvent>* dis) { //_MESSAGE("attached is %d", evn->attached); if (evn->attached == 0) { resetMap(); } //_MESSAGE("cell event %d", cur); return kEvent_Continue; } void resetMap(); }; }
[ "rollingrock16@gmail.com" ]
rollingrock16@gmail.com
3baa36ccbcf69bcb603a7f3a5e6bc4b84652f6bc
eb8d36a89dbaeffeedd8584d970aa2b33a8b2c6e
/CQ-0177/sequence/sequence.cpp
ab53765f4b7d9f68e54b7f025bdfcbc6d43a900d
[]
no_license
mcfx0/CQ-NOIP-2021
fe3f3a88c8b0cd594eb05b0ea71bfa2505818919
774d04aab2955fc4d8e833deabe43e91b79632c2
refs/heads/main
2023-09-05T12:41:42.711401
2021-11-20T08:59:40
2021-11-20T08:59:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll p = 998244353; ll n, m, k, x, ans, v[105], sum[256], a[256]; bool check() { x = a[0] = 0; for(int i = 0; i < 150; ++i) { a[i] += sum[i]; a[i + 1] = a[i] / 2; x += a[i] % 2; if(x > k) return false; } return true; } void dfs(ll pos, ll num, ll va, ll mul) { if(pos > m || num == n) { if(num == n && check()) { ans = (ans + va * mul) % p; } return; } dfs(pos + 1, num, va, mul); ll x = 1, t = 0; for(++num; num <= n; ++num) { ++sum[pos], va = va * v[pos] % p, mul = mul * num / ++t % p; dfs(pos + 1, num, va, mul); } sum[pos] = 0; } int main() { freopen("sequence.in", "r", stdin); freopen("sequence.out", "w", stdout); scanf("%lld%lld%lld", &n, &m, &k); for(int i = 0; i <= m; ++i) scanf("%lld", &v[i]); dfs(0, 0, 1, 1); printf("%lld", ans); return 0; //QAQ //QAQ //QAQ //QAQ }
[ "3286767741@qq.com" ]
3286767741@qq.com
dd906a132283548a2481ea4d01788487a60bfcd9
6fda6deb8811bb7a76e091c8cb4a7e9fa58a20c3
/Semester 3/core_wars/model/instructions.cpp
d462182b0d1858824a14a6a1b5c35355bc902cfb
[]
no_license
ValeraTM/Java
8008b82d6385dc8becfb48e85120870c7e3281ce
02d823eb628e27acef3b5521b9636dbc6d597fa8
refs/heads/master
2020-07-09T01:16:40.193776
2019-06-03T03:04:22
2019-06-03T03:04:22
203,833,165
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include "factory.h" #include "instructions.h" #include <cstddef> //size_t #include <string> #include <utility> //std::pair #include <sstream> void Instruction::initialize(const std::pair<char, int>& A1, const std::pair<char, int>& B1) { A = A1; B = B1; } int& Instruction::operandA() { return A.second; } int& Instruction::operandB() { return B.second; } std::string Instruction::info() { std::stringstream ss; ss << nameInstruction << " " << A.first << A.second << " " << B.first << B.second; std::string it; std::string result; while (!ss.eof()) { ss >> it; result += it + " "; } return result; }
[ "v.malkhanov@g.nsu.ru" ]
v.malkhanov@g.nsu.ru
26d3961f2cac40d6a007aa1e17f7127a34f7db87
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_1599_curl-7.51.0.cpp
5128b5990222375e8bb9f8ab730231f119a91001
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,969
cpp
static int showit(struct Curl_easy *data, curl_infotype type, char *ptr, size_t size) { static const char s_infotype[CURLINFO_END][3] = { "* ", "< ", "> ", "{ ", "} ", "{ ", "} " }; #ifdef CURL_DOES_CONVERSIONS char buf[BUFSIZE+1]; size_t conv_size = 0; switch(type) { case CURLINFO_HEADER_OUT: /* assume output headers are ASCII */ /* copy the data into my buffer so the original is unchanged */ if(size > BUFSIZE) { size = BUFSIZE; /* truncate if necessary */ buf[BUFSIZE] = '\0'; } conv_size = size; memcpy(buf, ptr, size); /* Special processing is needed for this block if it * contains both headers and data (separated by CRLFCRLF). * We want to convert just the headers, leaving the data as-is. */ if(size > 4) { size_t i; for(i = 0; i < size-4; i++) { if(memcmp(&buf[i], "\x0d\x0a\x0d\x0a", 4) == 0) { /* convert everything through this CRLFCRLF but no further */ conv_size = i + 4; break; } } } Curl_convert_from_network(data, buf, conv_size); /* Curl_convert_from_network calls failf if unsuccessful */ /* we might as well continue even if it fails... */ ptr = buf; /* switch pointer to use my buffer instead */ break; default: /* leave everything else as-is */ break; } #endif /* CURL_DOES_CONVERSIONS */ if(data->set.fdebug) return (*data->set.fdebug)(data, type, ptr, size, data->set.debugdata); switch(type) { case CURLINFO_TEXT: case CURLINFO_HEADER_OUT: case CURLINFO_HEADER_IN: fwrite(s_infotype[type], 2, 1, data->set.err); fwrite(ptr, size, 1, data->set.err); #ifdef CURL_DOES_CONVERSIONS if(size != conv_size) { /* we had untranslated data so we need an explicit newline */ fwrite("\n", 1, 1, data->set.err); } #endif break; default: /* nada */ break; } return 0; }
[ "993273596@qq.com" ]
993273596@qq.com
e5e1292e7ca6cc7a76c1a847f789871155ba2be9
1fb357bb753988011e0f20c4ca8ec6227516b84b
/LHPC/include/BOLlib/source/ArgumentParser.cpp
b90b5f1bdd0afccb66cb04dadfc479d99bfa2222
[ "DOC" ]
permissive
silvest/HEPfit
4240dcb05938596558394e97131872269cfa470e
cbda386f893ed9d8d2d3e6b35c0e81ec056b65d2
refs/heads/master
2023-08-05T08:22:20.891324
2023-05-19T09:12:45
2023-05-19T09:12:45
5,481,938
18
11
null
2022-05-15T19:53:40
2012-08-20T14:03:58
C++
UTF-8
C++
false
false
2,296
cpp
/* * ArgumentParser.cpp * * Created on: Sep 13, 2012 * Author: Ben O'Leary (benjamin.oleary@gmail.com) * * This file is part of BOLlib, released under the * GNU General Public License. Please see the accompanying * README.BOLlib.txt file for a full list of files, brief documentation * on how to use these classes, and further details on the license. */ #include "ArgumentParser.hpp" namespace BOL { ArgumentParser::ArgumentParser( int argumentCount, char** argumentCharArrays, std::string const inputTag, std::string const fallbackInputFilename ) : argumentStrings( ( argumentCount - 1 ), "" ), inputXmlParser() { inputXmlParser.loadString( "" ); for( int whichArgument( 1 ); argumentCount > whichArgument; ++whichArgument ) { argumentStrings[ whichArgument - 1 ].assign( argumentCharArrays[ whichArgument ] ); } if( !(inputTag.empty()) ) { std::string inputFilename( fromTag( inputTag ) ); if( inputFilename.empty() ) { inputFilename.assign( fallbackInputFilename ); } // at this point, if no input filename was provided either by the command // line arguments or by the constructor, I think that it's obvious that // the user didn't want to look for arguments in an XML file, so the // error message should not be shown for failing to open it. if( !(inputFilename.empty()) ) { bool successfullyRead( inputXmlParser.readAllOfRootElementOfFile( inputFilename ) && inputXmlParser.loadString( inputXmlParser.getCurrentElementContent() ) ); if( !successfullyRead ) { std::cout << std::endl << "BOL::ArgumentParser constructor failed to open root element of" << " \"" << inputFilename << "\"!"; std::cout << std::endl; } } } } ArgumentParser::~ArgumentParser() { // does nothing. } } /* namespace BOL */
[ "shehu@cantab.net" ]
shehu@cantab.net
c1dbcf3cb0b5916a6a6f4d2ee6f98ce7c66b2283
9ec67e83200f643f9f55ed90e0b2cae4581ebcb6
/InputLib/InputDataFormats.h
d53e2bb40a0a4dcdddb00bf159bae6f0eee4b834
[]
no_license
andrewpaterson/Codaphela.Library
465770eaf2839589fc305660725abb38033f8aa2
2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5
refs/heads/master
2023-05-25T13:01:45.587888
2023-05-14T11:46:36
2023-05-14T11:46:36
3,248,841
1
1
null
null
null
null
UTF-8
C++
false
false
1,443
h
/** ---------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE ------------- ** Copyright (c) 2009 Andrew Paterson This file is part of The Codaphela Project: Codaphela InputLib Codaphela InputLib is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Codaphela InputLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Codaphela InputLib. If not, see <http://www.gnu.org/licenses/>. Microsoft Windows is Copyright Microsoft Corporation ** ------------------------------------------------------------------------ **/ #ifndef __INPUT_DATA_FORMATS_H__ #define __INPUT_DATA_FORMATS_H__ #include "StandardLib/Unknown.h" #include "InputDataFormat.h" class CInputDataFormats : public CUnknown { CONSTRUCTABLE(CInputDataFormats); protected: CSetInputDataFormat mlcFormats; public: void Init(void); void Kill(void); CInputDataFormat* Add(char* szName); CInputDataFormat* Add(void); CInputDataFormat* Get(char* szName); }; #endif // !__INPUT_DATA_FORMATS_H__
[ "andrew.ian.paterson@gmail.com" ]
andrew.ian.paterson@gmail.com
47b9b5f75338a3bcc1a4abe4ea4fdcd12155584b
7c650903a326e0fd740a2ae24414d948f5fa7c4e
/Colts_work/scrap/mar27_2016/gr-Research/lib/new_qpsk_demod_cb_impl.h
2f5a78b5c5a2222feffc19f11dd85465fd2b4ac7
[]
no_license
yywynneyang/Research_W2016
837dbc31c60ed18bc4bdf3474602913102c681a5
317adf1ae01ef80634635e0d40ef17209dc32b7e
refs/heads/master
2020-04-15T05:03:50.621487
2016-04-13T19:50:59
2016-04-13T19:50:59
51,401,817
1
0
null
null
null
null
UTF-8
C++
false
false
1,646
h
/* -*- c++ -*- */ /* * Copyright 2016 <+YOU OR YOUR COMPANY+>. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_RESEARCH_NEW_QPSK_DEMOD_CB_IMPL_H #define INCLUDED_RESEARCH_NEW_QPSK_DEMOD_CB_IMPL_H #include <Research/new_qpsk_demod_cb.h> namespace gr { namespace Research { class new_qpsk_demod_cb_impl : public new_qpsk_demod_cb { private: bool d_gray_code; public: new_qpsk_demod_cb_impl(bool gray_code); ~new_qpsk_demod_cb_impl(); // Where all the action really happens void forecast (int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned char get_minimum_distances(const gr_complex &sample); }; } // namespace Research } // namespace gr #endif /* INCLUDED_RESEARCH_NEW_QPSK_DEMOD_CB_IMPL_H */
[ "cmthomas000@gmail.com" ]
cmthomas000@gmail.com
029e3a4e3dfce3d3aefb2aede18f0816e70fb4b5
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_1/C++/DoDoHushHush/a.cpp
2e518b543fad7960fabfda5a6ac928df7efddcf6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
314
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int t; cin>>t; for(int tt=1;tt<=t;tt++){ int r,c,w; cin>>r>>c>>w; int ha; if(c%w==0)ha=(c/w)+(w-1); else ha=(c/w)+w; cout<<"Case #"<<tt<<": "<<ha+(r-1)*(c/w)<<endl; } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
a63a4ed3909e906a07640c87007ad292c48132c2
d20f0bfe5343bf1e92e7eafcf3f534f275f791c4
/Component/CEquationsPrinter.cpp
2c2a95f4030fa75ebae1b190499206053280c715
[]
no_license
ShiloDenis1997/COM.2017.LUEquationsSolver
efdd81808035aca709e137531794fff07f406a05
07d472ca9ed8151c015c831d03d264b061c10e96
refs/heads/master
2020-05-23T04:35:26.420990
2017-04-08T13:13:16
2017-04-08T13:13:16
84,749,030
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
#include "CEquationsPrinter.h" void printTrace(const char* msg) { std::cout << msg << std::endl; } void CEquationsPrinter::PrintLMatrix() const { if (owner->m_LUmatr == nullptr) { std::cout << TEXT("No matrix provided") << std::endl; } for (int i = 0; i < owner->m_N; i++) { for (int j = 0; j < owner->m_N; j++) { if (j > i) { std::cout << 0 << " "; } else if (j < i) { std::cout << owner->m_LUmatr[i][j] << " "; } else { std::cout << "1 "; } } std::cout << std::endl; } } void CEquationsPrinter::PrintUMatrix() const { if (owner->m_LUmatr == nullptr) { std::cout << TEXT("No matrix provided") << std::endl; } for (int i = 0; i < owner->m_N; i++) { for (int j = 0; j < owner->m_N; j++) { if (j < i) { std::cout << 0 << " "; } else if (j >= i) { std::cout << owner->m_LUmatr[i][j] << " "; } } std::cout << std::endl; } } CEquationsPrinter::CEquationsPrinter(CEquationSolver* ownerComp) { printTrace("Printer interface ctor"); owner = ownerComp; m_cRef = 1; owner->AddRef(); } CEquationsPrinter::~CEquationsPrinter() { printTrace("Printer destroying"); owner->Release(); } HRESULT CEquationsPrinter::QueryInterface(const IID& riid, void** ppvObject) { printTrace("component query interface"); if (riid != IID_IEquationPrinter) { return owner->QueryInterface(riid, ppvObject); } else { *ppvObject = static_cast<IEquationPrinter*>(this); } reinterpret_cast<IUnknown*>(this)->AddRef(); return S_OK; } ULONG CEquationsPrinter::AddRef() { printTrace("Add ref printer"); return InterlockedIncrement(&m_cRef); } ULONG CEquationsPrinter::Release() { printTrace("Release printer"); if (InterlockedDecrement(&m_cRef) == 0) { printTrace("Deleting printer part"); owner->printerIface = nullptr; delete this; return 0; } return m_cRef; }
[ "shilo.denis.1997g@gmail.com" ]
shilo.denis.1997g@gmail.com
dcc91811b09f46bc4d79e228ce906f62adffab44
927c2b11739dccab27a44d5c1c76bbbc38add8f1
/Practice/PTA 数据结构与算法题目集(中文)/5-9 旅游规划/5-9 旅游规划/main.cpp
55193bf00547a4d2e82419f8f7ef5fdb83c08680
[]
no_license
civinx/ACM_Code
23034ca3eecb9758c3c00a519f61434a526e89cc
d194ee4e2554a29720ac455e6c6f86b3219724ee
refs/heads/master
2021-09-15T06:18:09.151529
2018-05-27T18:07:25
2018-05-27T18:07:25
105,544,957
1
0
null
null
null
null
UTF-8
C++
false
false
2,508
cpp
// // main.cpp // 5-9 旅游规划 // // Created by czf on 16/2/26. // Copyright © 2016年 czf. All rights reserved. // #include <iostream> #include <vector> #include <queue> #include <string> using namespace std; const int INF = 0xfffffff; const int maxn = 500 + 5; struct Dijkstra { struct Edge { int from, to, dist, cost; Edge(int u, int v, int d, int c) : from(u), to(v), dist(d), cost(c) {} }; struct HeapNode { int d, c, u; bool operator < (const HeapNode rhs) const{ return d > rhs.d; } }; int n, m; vector<Edge> edges; //边集 vector<int> G[maxn]; //每个点所连的边的编号集 int d[maxn]; int c[maxn]; bool done[maxn]; void init(int n) { this->n = n; for(int i = 0; i < n; i ++) G[i].clear(); edges.clear(); } void AddEdge(int from, int to, int dist, int cost) { edges.push_back(Edge(from, to, dist, cost)); m = edges.size(); G[from].push_back(m-1); edges.push_back(Edge(to, from, dist, cost)); m = edges.size(); G[to].push_back(m-1); } void dijkstra(int s) { priority_queue<HeapNode> q; for(int i = 0; i < n; i ++) { d[i] = INF; c[i] = INF; done[i] = 0; } d[s] = 0; c[s] = 0; q.push((HeapNode){0, 0, s}); while(!q.empty()){ HeapNode x = q.top(); q.pop(); int u = x.u; if (done[u]) continue; done[u] = 1; for(int i = 0; i < G[u].size(); i ++){ Edge &e = edges[G[u][i]]; //e即当前扫描的边 // if (done[e.to]) continue; if (d[e.to] > d[u] + e.dist) { d[e.to] = d[u] + e.dist; c[e.to] = c[u] + e.cost; q.push((HeapNode){d[e.to], c[e.to], e.to}); } else if (d[e.to] == d[u] + e.dist && c[u] + e.cost < c[e.to]) { c[e.to] = c[u] + e.cost; q.push((HeapNode){d[e.to], c[e.to], e.to}); } } } } }; int main() { int N, M, S, D; string s = "12345"; scanf("%d%d%d%d",&N,&M,&S,&D); Dijkstra solve; solve.init(N); for(int i = 0; i < M; i ++){ int from, to, dist, cost; scanf("%d%d%d%d",&from,&to,&dist,&cost); solve.AddEdge(from, to, dist, cost); } solve.dijkstra(S); printf("%d %d\n",solve.d[D],solve.c[D]); return 0; }
[ "31501293@stu.zucc.edu.cn" ]
31501293@stu.zucc.edu.cn
2142d0a14d60999f25c68abec6506567f05a51c8
0b7f95a5a66eaa35738cd4e6b553e49175301959
/Source/System/Core/OS-API/OSAPI.hpp
0e66ee335248d4e7509da5c8626fecc146af1c6e
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
arian153/Engine5th
f993b45122de49e305e698f44ac9be4e2462a003
34f85433bc0a74a7ebe7da350d3f3698de77226e
refs/heads/master
2021-11-19T20:09:20.716035
2021-09-04T05:59:27
2021-09-04T05:59:27
219,928,073
1
0
null
null
null
null
UTF-8
C++
false
false
550
hpp
#pragma once #if defined(E5_WIN32) //classes #define OSAPI OSWin32 #define KeyboardInputAPI KeyboardInputWin32 #define MouseInputAPI MouseInputWin32 #define GamePadInputAPI GamePadInputWin32 //includes #define IncludeOSAPI "Win32/OSWin32.hpp" #define IncludeKeyboardAPI "../OS-API/Win32/KeyboardInputWin32.hpp" #define IncludeMouseAPI "../OS-API/Win32/MouseInputWin32.hpp" #define IncludeGamePadAPI "../OS-API/Win32/GamePadInputWin32.hpp" #elif defined(E5_UWP) //classes #define OSAPI OSUWP //includes #define IncludeOSAPI "UWP/OSUWP.hpp" #endif
[ "p084111@gmail.com" ]
p084111@gmail.com
fa6860169879a471ac4004afac9db61da389b1c3
25da30573b1c06324f3231a897a1bb8483b78ead
/0tmp/push_derived_into_vec.cc
02a09d6634c23dffd5f5a6e580c4315f07d4e508
[]
no_license
cedric-sun/happy_hacking_cxx20
34c7027a679fc284b45e640891c57af647621e95
ac126b6a0ceeb1747d5bf0e91a0254426393d768
refs/heads/master
2023-02-03T17:47:30.074151
2020-12-19T03:33:24
2020-12-19T03:33:24
294,602,449
1
0
null
null
null
null
UTF-8
C++
false
false
344
cc
// cesun, 10/17/20 7:55 PM. struct A { int avalue = 3; }; struct B : public A { int bvalue = 5; }; #include <vector> #include <cstdio> int main() { std::vector<A *> avec; B binst; binst.bvalue = 444; avec.push_back(&binst); printf("%d %d\n", avec.front()->avalue, reinterpret_cast<B*>(avec.front())->bvalue); }
[ "sunce@ufl.edu" ]
sunce@ufl.edu
d3d9c2b6829f00d61d7415360b1b01a595482378
ce7453e65bc63cfffa334a39a368891eab082f29
/mediatek/custom/common/hal/imgsensor/ov5647_mipi_raw/camera_calibration_cam_cal.cpp
af17a40dc0bb9f989ca36357d8f9b80a71ae4d1f
[]
no_license
AdryV/kernel_w200_kk_4.4.2_3.4.67_mt6589
7a65d4c3ca0f4b59e4ad6d7d8a81c28862812f1c
f2b1be8f087cd8216ec1c9439b688df30c1c67d4
refs/heads/master
2021-01-13T00:45:17.398354
2016-12-04T17:41:24
2016-12-04T17:41:24
48,487,823
7
10
null
null
null
null
UTF-8
C++
false
false
50,028
cpp
#define LOG_TAG "CamCalCamCal" #include <cutils/xlog.h> //#include <utils/Log.h> #include <cutils/properties.h> #include <fcntl.h> #include <math.h> //seanlin 120921 for 658x #include "MediaHal.h" //#include "src/lib/inc/MediaLog.h" //#include "src/lib/inc/MediaLog.h" //#include "camera_custom_nvram.h" #include "camera_custom_nvram.h" //cam_cal #include "cam_cal.h" #include "cam_cal_define.h" extern "C"{ //#include "cam_cal_layout.h" #include "camera_custom_cam_cal.h" } #include "camera_calibration_cam_cal.h" //ov5647 #include <stdio.h> //for rand? #include <stdlib.h> //sl121106 for atoi()//for rand? //#include "src/core/scenario/camera/mhal_cam.h" //for timer //COMMON #define DEBUG_CALIBRATION_LOAD #define CUSTOM_CAM_CAL_ROTATION_00 CUSTOM_CAM_CAL_ROTATION_0_DEGREE #define CUSTOM_CAM_CAL_ROTATION_01 CUSTOM_CAM_CAL_ROTATION_0_DEGREE #define CUSTOM_CAM_CAL_COLOR_ORDER_00 CUSTOM_CAM_CAL_COLOR_SHIFT_00 //SeanLin@20110629: #define CUSTOM_CAM_CAL_COLOR_ORDER_01 CUSTOM_CAM_CAL_COLOR_SHIFT_00 //#define CUSTOM_CAM_CAL_PART_NUMBERS_START_ADD 5 //#define CUSTOM_CAM_CAL_NEW_MODULE_NUMBER_CHECK 1 // #define CAM_CAL_SHOW_LOG 1 #define CAM_CAL_VER "ver8900~" //83 : 6583, 00 : draft version 120920 #ifdef CAM_CAL_SHOW_LOG //#define CAM_CAL_LOG(fmt, arg...) LOGD(fmt, ##arg) #define CAM_CAL_LOG(fmt, arg...) XLOGD(CAM_CAL_VER " "fmt, ##arg) #define CAM_CAL_ERR(fmt, arg...) XLOGE(CAM_CAL_VER "Err: %5d: "fmt, __LINE__, ##arg) #else #define CAM_CAL_LOG(fmt, arg...) void(0) #define CAM_CAL_ERR(fmt, arg...) void(0) #endif #define CAM_CAL_LOG_IF(cond, ...) do { if ( (cond) ) { CAM_CAL_LOG(__VA_ARGS__); } }while(0) ////< #if 0 ////seanlin 121016 for 658x UINT32 DoCamCalDefectLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); UINT32 DoCamCalPregainLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); UINT32 DoCamcalISPSlimShadingLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); UINT32 DoCamCalISPDynamicShadingLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); UINT32 DoCamCalISPFixShadingLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); UINT32 DoCamCalISPSensorShadingLoad(INT32 CamcamFID, UINT32 start_addr, UINT32* pGetSensorCalData); #else UINT32 DoCamCalModuleVersion(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize,UINT32* pGetSensorCalData); UINT32 DoCamCalPartNumber(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); //UINT32 DoCamCalShadingTable(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCalSingleLsc(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCalN3dLsc(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCalAWBGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCal2AGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCal3AGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); UINT32 DoCamCal3DGeo(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); #endif ////seanlin 121016 for 658x #if 0 ////seanlin 121016 for 658x enum { CALIBRATION_LAYOUT_SLIM_LSC1 = 0, CALIBRATION_LAYOUT_SLIM_LSC2, CALIBRATION_LAYOUT_DYANMIC_LSC1, CALIBRATION_LAYOUT_DYANMIC_LSC2, CALIBRATION_LAYOUT_FIX_LSC1, CALIBRATION_LAYOUT_FIX_LSC2, CALIBRATION_LAYOUT_SENSOR_LSC1, CALIBRATION_LAYOUT_SENSOR_LSC2, CALIBRATION_LAYOUT_SUNNY_Q8N03D_LSC1, //SL 110317 MAX_CALIBRATION_LAYOUT_NUM }; #define CALIBRATION_DATA_SIZE_SLIM_LSC1 656 #define CALIBRATION_DATA_SIZE_SLIM_LSC2 3716 #define CALIBRATION_DATA_SIZE_DYANMIC_LSC1 2048 #define CALIBRATION_DATA_SIZE_DYANMIC_LSC2 5108 #define CALIBRATION_DATA_SIZE_FIX_LSC1 4944 #define CALIBRATION_DATA_SIZE_FIX_LSC2 8004 #define CALIBRATION_DATA_SIZE_SENSOR_LSC1 20 #define CALIBRATION_DATA_SIZE_SENSOR_LSC2 3088 #define CALIBRATION_DATA_SIZE_SUNNY_Q8N03D_LSC1 656 //SL 110317 #define MAX_CALIBRATION_DATA_SIZE CALIBRATION_DATA_SIZE_FIX_LSC2 #endif ////seanlin 121016 for 658x #if 0 //from camera_custom_cam_cal.h const MUINT32 CamCalReturnErr[CAMERA_CAM_CAL_DATA_LIST]= { CAM_CAL_ERR_NO_VERSION, CAM_CAL_ERR_NO_PARTNO, CAM_CAL_ERR_NO_SHADING, CAM_CAL_ERR_NO_3A_GAIN, CAM_CAL_ERR_NO_3D_GEO}; typedef enum { CAMERA_CAM_CAL_DATA_MODULE_VERSION=0, //seanlin 121016 it's for user to get info. of single module or N3D module CAMERA_CAM_CAL_DATA_PART_NUMBER, //seanlin 121016 return 5x4 byes gulPartNumberRegCamCal[5] CAMERA_CAM_CAL_DATA_SHADING_TABLE, //seanlin 121016 return SingleLsc or N3DLsc CAMERA_CAM_CAL_DATA_3A_GAIN, //seanlin 121016 return Single2A or N3D3A CAMERA_CAM_CAL_DATA_3D_GEO, //seanlin 121016 return none or N3D3D CAMERA_CAM_CAL_DATA_LIST } CAMERA_CAM_CAL_TYPE_ENUM; #endif //from camera_custom_cam_cal.h #if 0 //use the same CAMERA_CAM_CAL_TYPE_ENUM in camera_custom_cam_cal.h enum { CALIBRATION_ITEM_DEFECT = 0, CALIBRATION_ITEM_PREGAIN, CALIBRATION_ITEM_SHADING, MAX_CALIBRATION_ITEM_NUM }; #endif //use the same CAMERA_CAM_CAL_TYPE_ENUM in camera_custom_cam_cal.h #if 0 //use the same error code in camera_custom_cam_cal.h static UINT32 GetCalErr[MAX_CALIBRATION_ITEM_NUM] = { CAM_CAL_ERR_NO_DEFECT, CAM_CAL_ERR_NO_PREGAIN, CAM_CAL_ERR_NO_SHADING, }; #endif //use the same error code in camera_custom_cam_cal.h #if 1 //typedef enum enum { CALIBRATION_LAYOUT_SLIM_LSC1 = 0, //Legnacy module for 657x CALIBRATION_LAYOUT_N3D_DATA1, //N3D module for 658x CALIBRATION_LAYOUT_SUNNY_Q8N03D_LSC1, //SL 110317 CALIBRATION_LAYOUT_SENSOR_OTP, MAX_CALIBRATION_LAYOUT_NUM }; //}CAM_CAL_MODULE_TYPE; /* typedef enum { CAM_CAL_LAYOUT_PASS, CAM_CAL_LAYOUT_FAILED, CAM_CAL_LAYOUT_QUEUE }CAM_CAL_LAYOUT_T; */ #else #define CALIBRATION_LAYOUT_SLIM_LSC1 0 //Legnacy module for 657x #define CALIBRATION_LAYOUT_N3D_DATA1 1 //N3D module for 658x #define CALIBRATION_LAYOUT_SUNNY_Q8N03D_LSC1 2 //SL 110317 #define MAX_CALIBRATION_LAYOUT_NUM 3 #endif #if 1 typedef enum // : MUINT32 { CAM_CAL_LAYOUT_RTN_PASS = 0x0, CAM_CAL_LAYOUT_RTN_FAILED = 0x1, CAM_CAL_LAYOUT_RTN_QUEUE = 0x2 } CAM_CAL_LAYOUT_T; #else #define CAM_CAL_LAYOUT_RTN_PASS 0x0 #define CAM_CAL_LAYOUT_RTN_FAILED 0x1 #define CAM_CAL_LAYOUT_RTN_QUEUE 0x2 #endif /* #define CAL_DATA_SIZE_SLIM_LSC1_CC (0x290)//656 #define CAL_DATA_SIZE_N3D_DATA1_CC (0x1C84) #define CAL_DATA_SIZE_SUNNY_LSC1_CC (0x290)//656 //SL 110317 */ typedef struct { UINT16 Include; //calibration layout include this item? UINT32 StartAddr; // item Start Address UINT32 BlockSize; //BlockSize UINT32 (*GetCalDataProcess)(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData);//(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData); } CALIBRATION_ITEM_STRUCT; typedef struct { UINT32 HeaderAddr; //Header Address UINT32 HeaderId; //Header ID UINT32 DataVer; ////new for 658x CAM_CAL_SINGLE_EEPROM_DATA, CAM_CAL_SINGLE_OTP_DATA,CAM_CAL_N3D_DATA //seanlin 121016 for 658x UINT32 CheckShading; // Do check shading ID? //seanlin 121016 for 658x UINT32 ShadingID; // Shading ID CALIBRATION_ITEM_STRUCT CalItemTbl[CAMERA_CAM_CAL_DATA_LIST]; } CALIBRATION_LAYOUT_STRUCT; /* //Const variable */ //static UINT8 gIsInitedCamCal = 0;//seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. const MUINT8 CamCalPartNumber[24]={0x57,0x61,0x6E,0x70,0x65,0x69,0x20,0x4C,0x69,0x61,0x6E,0x67, 0x20,0x53,0x6F,0x70,0x68,0x69,0x65,0x52,0x79,0x61,0x6E,0x00}; const CALIBRATION_LAYOUT_STRUCT CalLayoutTbl[MAX_CALIBRATION_LAYOUT_NUM]= { {//CALIBRATION_LAYOUT_SLIM_LSC1 without Defect //data sheet of excel : "Slim" 0x00000000, 0x010200FF, CAM_CAL_SINGLE_EEPROM_DATA, { {0x00000001, 0x00000000, 0x00000000, DoCamCalModuleVersion}, //CAMERA_CAM_CAL_DATA_MODULE_VERSION {0x00000001, 0x00000000, 0x00000000, DoCamCalPartNumber}, //CAMERA_CAM_CAL_DATA_PART_NUMBER {0x00000001, 0x0000000C, 0x00000284, DoCamCalSingleLsc}, //CAMERA_CAM_CAL_DATA_SHADING_TABLE {0x00000001, 0x00000004, 0x00000008, DoCamCalAWBGain}, //CAMERA_CAM_CAL_DATA_3A_GAIN {0x00000000, 0x00000000, 0x00000000, DoCamCal3DGeo} //CAMERA_CAM_CAL_DATA_3D_GEO } }, {//CALIBRATION_LAYOUT_N3D //data sheet of excel : "3D_EEPROM 8M+2M _0A_2" 0x00000000, 0x020A00FF,CAM_CAL_N3D_DATA, { {0x00000001, 0x00000002, 0x00000000, DoCamCalModuleVersion}, //CAMERA_CAM_CAL_DATA_MODULE_VERSION {0x00000001, 0x00000000, 0x00000018, DoCamCalPartNumber}, //CAMERA_CAM_CAL_DATA_PART_NUMBER {0x00000001, 0x1480009C, 0x00000840, DoCamCalN3dLsc}, //CAMERA_CAM_CAL_DATA_SHADING_TABLE {0x00000001, 0x1400001C, 0x00000080, DoCamCal3AGain}, //CAMERA_CAM_CAL_DATA_3A_GAIN {0x00000001, 0x00000A00, 0x00000898, DoCamCal3DGeo} //CAMERA_CAM_CAL_DATA_3D_GEO } }, {//CALIBRATION_LAYOUT_SUNY 0x00000000, 0x796e7573, CAM_CAL_SINGLE_EEPROM_DATA, { {0x00000001, 0x00000000, 0x00000000, DoCamCalModuleVersion}, //CAMERA_CAM_CAL_DATA_MODULE_VERSION {0x00000001, 0x00000000, 0x00000000, DoCamCalPartNumber}, //CAMERA_CAM_CAL_DATA_PART_NUMBER {0x00000001, 0x0000000C, 0x00000284, DoCamCalSingleLsc}, //CAMERA_CAM_CAL_DATA_SHADING_TABLE {0x00000001, 0x00000004, 0x00000008, DoCamCalAWBGain}, //CAMERA_CAM_CAL_DATA_3A_GAIN {0x00000000, 0x00000000, 0x00000000, DoCamCal3DGeo} //CAMERA_CAM_CAL_DATA_3D_GEO } }, {//CALIBRATION_LAYOUT_SENSOR_OTP 0x00000001, 0x010b00ff, CAM_CAL_SINGLE_OTP_DATA, { {0x00000001, 0x00000000, 0x00000000, DoCamCalModuleVersion}, //CAMERA_CAM_CAL_DATA_MODULE_VERSION {0x00000001, 0x00000005, 0x00000002, DoCamCalPartNumber}, //CAMERA_CAM_CAL_DATA_PART_NUMBER {0x00000001, 0x00000017, 0x00000001, DoCamCalSingleLsc}, //CAMERA_CAM_CAL_DATA_SHADING_TABLE {0x00000001, 0x00000007, 0x0000000E, DoCamCal2AGain}, //CAMERA_CAM_CAL_DATA_3A_GAIN {0x00000000, 0x00000000, 0x00000000, DoCamCal3DGeo} //CAMERA_CAM_CAL_DATA_3D_GEO } } }; /**************************************************************** //Global variable ****************************************************************/ //static CAM_CAL_LAYOUT_T gIsInitedCamCal = CAM_CAL_LAYOUT_RTN_QUEUE;//seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. static UINT16 LayoutType = (MAX_CALIBRATION_LAYOUT_NUM+1); //seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. static bool bFirstLoad = TRUE; static MINT32 dumpEnable=0; static CAM_CAL_LAYOUT_T gIsInitedCamCal = CAM_CAL_LAYOUT_RTN_QUEUE;//(CAM_CAL_LAYOUT_T)CAM_CAL_LAYOUT_RTN_QUEUE;//seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. //MUINT32 gIsInitedCamCal = CAM_CAL_LAYOUT_RTN_QUEUE;//(CAM_CAL_LAYOUT_T)CAM_CAL_LAYOUT_RTN_QUEUE;//seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. UINT32 ShowCmdErrorLog(CAMERA_CAM_CAL_TYPE_ENUM cmd) { CAM_CAL_ERR("Return ERROR %s\n",CamCalErrString[cmd]); return 0; } #if 0 //for test, no use currently UINT32 DoReadDataByCmd(CAMERA_CAM_CAL_TYPE_ENUM Command, NT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize,UINT8* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; UINT32 ioctlerr, err; cam_calCfg.u4Offset = start_addr; cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= pGetSensorCalData; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(Command); } return err; } #endif //for test, no use currently UINT32 DoCamCalModuleVersion(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize,UINT32* pGetSensorCalData) { PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; UINT32 err= 0; /* if(start_addr<CAM_CAL_TYPE_NUM) { pCamCalData->DataVer = start_addr; } else { err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); }*/ #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================Module version==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[DataVer] = 0x%x\n", pCamCalData->DataVer); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================Module version==================\n"); #endif return err; } UINT32 DoCamCalPartNumber(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT8 ucModuleNumber[CAM_CAL_PART_NUMBERS_COUNT_BYTE]={0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0}; if(BlockSize==(CAM_CAL_PART_NUMBERS_COUNT_BYTE)) { cam_calCfg.u4Offset = start_addr; cam_calCfg.u4Length = CAM_CAL_PART_NUMBERS_COUNT_BYTE; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&ucModuleNumber[0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } } else { CAM_CAL_LOG_IF(dumpEnable,"use default part number\n"); srand(time(NULL)); for(idx=0;idx<(CAM_CAL_PART_NUMBERS_COUNT*LSC_DATA_BYTES);idx++) { ucModuleNumber[idx]=CamCalPartNumber[idx]; if(ucModuleNumber[idx] ==0x20) { //disable random> TBD //ucModuleNumber[idx] = (UINT32)rand(); //random //disable random< TBD } } err = CAM_CAL_ERR_NO_ERR; } CAM_CAL_LOG_IF(dumpEnable,"%s\n",ucModuleNumber); memcpy((char*)&pCamCalData->PartNumber[0],ucModuleNumber,sizeof(CAM_CAL_PART_NUMBERS_COUNT_BYTE)); #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================Part Number==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[Part Number] = %s\n", pCamCalData->PartNumber); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================Part Number==================\n"); #endif return err; } UINT32 DoCamCalAWBGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 PregainFactor, PregainOffset; UINT32 PregainFactorH, PregainOffsetH; UINT32 GainValue; if(pCamCalData->DataVer >= CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else if(pCamCalData->DataVer < CAM_CAL_N3D_DATA) { if(BlockSize!=CAM_CAL_SINGLE_AWB_COUNT_BYTE) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,CAM_CAL_SINGLE_AWB_COUNT_BYTE); ShowCmdErrorLog(pCamCalData->Command); } else { ////Only AWB Gain without AF>//// pCamCalData->Single2A.S2aVer = 0x01; pCamCalData->Single2A.S2aBitEn = CAM_CAL_AWB_BITEN; pCamCalData->Single2A.S2aAfBitflagEn = 0x0;// //Bit: step 0(inf.), 1(marco), 2, 3, 4,5,6,7 memset(pCamCalData->Single2A.S2aAf,0x0,sizeof(pCamCalData->Single2A.S2aAf)); ////Only AWB Gain without AF<//// ////Only AWB Gain Gathering >//// cam_calCfg.u4Offset = start_addr|0xFFFF; cam_calCfg.u4Length = 4; cam_calCfg.pu1Params = (u8 *)&PregainFactor; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = start_addr+4; cam_calCfg.u4Length = 4; cam_calCfg.pu1Params = (u8 *)&PregainOffset; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } PregainFactorH = ((PregainFactor>>16)&0xFFFF); PregainOffsetH = ((PregainOffset>>16)&0xFFFF); if((PregainOffset==0)||(PregainOffsetH==0)) { //pre gain pCamCalData->Single2A.S2aAwb.rUnitGainu4R = 512; pCamCalData->Single2A.S2aAwb.rUnitGainu4G = 512; pCamCalData->Single2A.S2aAwb.rUnitGainu4B = 512; CAM_CAL_LOG_IF(dumpEnable,"Pegain has no Calinration Data!!!\n"); } else { //pre gain pCamCalData->Single2A.S2aAwb.rUnitGainu4R = (((PregainFactor&0xFF)<<8)| ((PregainFactor&0xFF00)>>8))*512 / (((PregainOffset&0xFF)<<8)| ((PregainOffset&0xFF00)>>8)); pCamCalData->Single2A.S2aAwb.rUnitGainu4G = 512; pCamCalData->Single2A.S2aAwb.rUnitGainu4B = (((PregainFactorH&0xFF)<<8)| ((PregainFactorH&0xFF00)>>8))*512/ (((PregainOffsetH&0xFF)<<8)| ((PregainOffsetH&0xFF00)>>8)); err=0; } if((pCamCalData->Single2A.S2aAwb.rUnitGainu4R==0)||(pCamCalData->Single2A.S2aAwb.rUnitGainu4B==0)) { //pre gain pCamCalData->Single2A.S2aAwb.rUnitGainu4R = 512; pCamCalData->Single2A.S2aAwb.rUnitGainu4G = 512; pCamCalData->Single2A.S2aAwb.rUnitGainu4B = 512; CAM_CAL_ERR("RGB Gain is not reasonable!!!\n"); pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; ShowCmdErrorLog(pCamCalData->Command); } ////Only AWB Gain Gathering <//// #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================AWB CAM_CAL==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[CAM_CAL PREGAIN VALUE] = 0x%x\n", PregainFactor); CAM_CAL_LOG_IF(dumpEnable,"[CAM_CAL PREGAIN OFFSET] = 0x%x\n", PregainOffset); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4R] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4R); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4G] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4G); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4B] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4B); CAM_CAL_LOG_IF(dumpEnable,"======================AWB CAM_CAL==================\n"); #endif //////////////////////////////////////////////////////////////////////////////// } } return err; } /********************************************************/ //Please put your AWB+AF data funtion, here. /********************************************************/ UINT32 DoCamCal2AGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 GainValue; UINT32 CalGain, FacGain; UINT8 AWBAFConfig; UINT32 AFInf, AFMacro; UINT8 tempMin = 255; UINT8 tempGain, CalR, CalGr, CalGb, CalB, FacR, FacGr, FacGb, FacB; //Structure /* Byte[0]:Version Byte[1]: [x,x,x,x,enbAFMacro, enbAFInf, enbAF, enbWB] Byte[9:2]: {GoldenB, GoldenGb, GoldenGr, GoldenR, UnitB, UnitGb, UnitGr, UnitR} Byte[11:10]: AF inf. Byte[13:12]: AF Macro */ if(pCamCalData->DataVer >= CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else if(pCamCalData->DataVer < CAM_CAL_N3D_DATA) { if(BlockSize!=14) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,14); ShowCmdErrorLog(pCamCalData->Command); } else { // Check the config. for AWB & AF cam_calCfg.u4Offset = (start_addr+1); cam_calCfg.u4Length = 1; cam_calCfg.pu1Params = (u8 *)&AWBAFConfig; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } pCamCalData->Single2A.S2aVer = 0x01; pCamCalData->Single2A.S2aBitEn = (0x03 & AWBAFConfig); CAM_CAL_LOG_IF(dumpEnable,"S2aBitEn=0x%x", pCamCalData->Single2A.S2aBitEn); pCamCalData->Single2A.S2aAfBitflagEn = (0x0C & AWBAFConfig);// //Bit: step 0(inf.), 1(marco), 2, 3, 4,5,6,7 //memset(pCamCalData->Single2A.S2aAf,0x0,sizeof(pCamCalData->Single2A.S2aAf)); if(0x1&AWBAFConfig){ ////AWB//// cam_calCfg.u4Offset = (start_addr+2); cam_calCfg.u4Length = 4; cam_calCfg.pu1Params = (u8 *)&CalGain; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); CAM_CAL_LOG_IF(dumpEnable,"Read CalGain OK\n"); if(!ioctlerr) { // Get min gain CalR = CalGain&0xFF; CalGr = (CalGain>>8)&0xFF; CalGb = (CalGain>>16)&0xFF; CalB = (CalGain>>24)&0xFF; CAM_CAL_LOG_IF(dumpEnable,"Extract CalGain OK\n"); for (int i=0;i<4;i++){ tempGain = (CalGain>>(8*i)) & 0xFF; CAM_CAL_LOG_IF(dumpEnable,"item=%d", tempGain); if( tempGain < tempMin){ tempMin = tempGain; CAM_CAL_LOG_IF(dumpEnable,"New tempMin=%d", tempMin); } } err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = (start_addr+6); cam_calCfg.u4Length = 4; cam_calCfg.pu1Params = (u8 *)&FacGain; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); CAM_CAL_LOG_IF(dumpEnable,"Read FacGain OK\n"); if(!ioctlerr) { // Get min gain FacR = FacGain&0xFF; FacGr = (FacGain>>8)&0xFF; FacGb = (FacGain>>16)&0xFF; FacB = (FacGain>>24)&0xFF; CAM_CAL_LOG_IF(dumpEnable,"Extract CalGain OK\n"); for (int i=0;i<4;i++){ tempGain = (FacGain>>(8*i)) & 0xFF; CAM_CAL_LOG_IF(dumpEnable,"item=%d", tempGain); if( tempGain < tempMin){ tempMin = tempGain; CAM_CAL_LOG_IF(dumpEnable,"New tempMin=%d", tempMin); } } err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } CAM_CAL_LOG_IF(dumpEnable,"Start assign value\n"); pCamCalData->Single2A.S2aAwb.rUnitGainu4R = (u32)(CalR*512/tempMin); pCamCalData->Single2A.S2aAwb.rUnitGainu4G = (u32)( (CalGr+CalGb)*512/2/tempMin ); pCamCalData->Single2A.S2aAwb.rUnitGainu4B = (u32)(CalB*512/tempMin); pCamCalData->Single2A.S2aAwb.rGoldGainu4R = (u32)(FacR*512/tempMin); pCamCalData->Single2A.S2aAwb.rGoldGainu4G = (u32)( (FacGr+FacGb)*512/2/tempMin ); pCamCalData->Single2A.S2aAwb.rGoldGainu4B = (u32)(FacB*512/tempMin); ////Only AWB Gain Gathering <//// #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================AWB CAM_CAL==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[CalGain] = 0x%x\n", CalGain); CAM_CAL_LOG_IF(dumpEnable,"[FacGain] = 0x%x\n", FacGain); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4R] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4R); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4G] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4G); CAM_CAL_LOG_IF(dumpEnable,"[rCalGain.u4B] = %d\n", pCamCalData->Single2A.S2aAwb.rUnitGainu4B); CAM_CAL_LOG_IF(dumpEnable,"[rFacGain.u4R] = %d\n", pCamCalData->Single2A.S2aAwb.rGoldGainu4R); CAM_CAL_LOG_IF(dumpEnable,"[rFacGain.u4G] = %d\n", pCamCalData->Single2A.S2aAwb.rGoldGainu4G); CAM_CAL_LOG_IF(dumpEnable,"[rFacGain.u4B] = %d\n", pCamCalData->Single2A.S2aAwb.rGoldGainu4B); CAM_CAL_LOG_IF(dumpEnable,"======================AWB CAM_CAL==================\n"); #endif } if(0x2&AWBAFConfig){ ////AF//// cam_calCfg.u4Offset = (start_addr+10); cam_calCfg.u4Length = 2; cam_calCfg.pu1Params = (u8 *)&AFInf; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = (start_addr+12); cam_calCfg.u4Length = 2; cam_calCfg.pu1Params = (u8 *)&AFMacro; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { pCamCalData->Single2A.S2aBitEn = CAM_CAL_NONE_BITEN; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } pCamCalData->Single2A.S2aAf[0] = AFInf; pCamCalData->Single2A.S2aAf[1] = AFMacro; ////Only AWB Gain Gathering <//// #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================AF CAM_CAL==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[AFInf] = %d\n", AFInf); CAM_CAL_LOG_IF(dumpEnable,"[AFMacro] = %d\n", AFMacro); CAM_CAL_LOG_IF(dumpEnable,"======================AF CAM_CAL==================\n"); #endif } //////////////////////////////////////////////////////////////////////////////// } } return err; } UINT32 DoCamCalSingleLsc(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 PregainFactor, PregainOffset; UINT32 PregainFactorH, PregainOffsetH; UINT32 GainValue; if(pCamCalData->DataVer >= CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else { if(BlockSize!=CAM_CAL_SINGLE_LSC_SIZE) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,CAM_CAL_SINGLE_LSC_SIZE); ShowCmdErrorLog(pCamCalData->Command); } else { pCamCalData->SingleLsc.TableRotation=CUSTOM_CAM_CAL_ROTATION_00; cam_calCfg.u4Offset = (start_addr|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->SingleLsc.LscTable.Data[0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } } } #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================SingleLsc Data==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[1st] = %x, %x, %x, %x \n", pCamCalData->SingleLsc.LscTable.Data[0], pCamCalData->SingleLsc.LscTable.Data[1], pCamCalData->SingleLsc.LscTable.Data[2], pCamCalData->SingleLsc.LscTable.Data[3]); CAM_CAL_LOG_IF(dumpEnable,"[1st] = SensorLSC(1)?MTKLSC(2)? %x \n", pCamCalData->SingleLsc.LscTable.MtkLcsData.MtkLscType); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================SingleLsc Data==================\n"); #endif return err; } UINT32 DoCamCalN3dLsc(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 PregainFactor, PregainOffset; UINT32 PregainFactorH, PregainOffsetH; UINT32 GainValue; if(pCamCalData->DataVer != CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else { if(BlockSize!=CAM_CAL_N3D_LSC_SIZE) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,CAM_CAL_N3D_LSC_SIZE); ShowCmdErrorLog(pCamCalData->Command); } else { pCamCalData->N3DLsc.Data[0].TableRotation=CUSTOM_CAM_CAL_ROTATION_00; pCamCalData->N3DLsc.Data[1].TableRotation=CUSTOM_CAM_CAL_ROTATION_01; cam_calCfg.u4Offset = (start_addr|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3DLsc.Data[0].LscTable.Data[0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = ((start_addr>>16)|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3DLsc.Data[1].LscTable.Data[0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } } } #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================3DLsc Data==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[1st] = %x, %x, %x, %x \n", pCamCalData->N3DLsc.Data[0].LscTable.Data[0], pCamCalData->N3DLsc.Data[0].LscTable.Data[1], pCamCalData->N3DLsc.Data[0].LscTable.Data[2], pCamCalData->N3DLsc.Data[0].LscTable.Data[3]); CAM_CAL_LOG_IF(dumpEnable,"[1st] = SensorLSC(1)?MTKLSC(2)? %x \n", pCamCalData->N3DLsc.Data[0].LscTable.MtkLcsData.MtkLscType); CAM_CAL_LOG_IF(dumpEnable,"[2nd] = %x, %x, %x, %x \n", pCamCalData->N3DLsc.Data[1].LscTable.Data[0], pCamCalData->N3DLsc.Data[1].LscTable.Data[1], pCamCalData->N3DLsc.Data[1].LscTable.Data[2], pCamCalData->N3DLsc.Data[1].LscTable.Data[3]); CAM_CAL_LOG_IF(dumpEnable,"[[2nd]] = SensorLSC(1)?MTKLSC(2)? %x \n", pCamCalData->N3DLsc.Data[1].LscTable.MtkLcsData.MtkLscType); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================3DLsc Data==================\n"); #endif return err; } UINT32 DoCamCal3AGain(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 PregainFactor, PregainOffset; UINT32 PregainFactorH, PregainOffsetH; UINT32 GainValue; if(pCamCalData->DataVer != CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else { if(BlockSize!=CAM_CAL_N3D_3A_SIZE) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,CAM_CAL_N3D_3A_SIZE); ShowCmdErrorLog(pCamCalData->Command); } else { cam_calCfg.u4Offset = (start_addr|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3D3A.Data[0][0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = ((start_addr>>16)|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3D3A.Data[1][0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } } } #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================3A Data==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[1st] = %x, %x, %x, %x \n", pCamCalData->N3D3A.Data[0][0],pCamCalData->N3D3A.Data[0][1], pCamCalData->N3D3A.Data[0][2],pCamCalData->N3D3A.Data[0][3]); CAM_CAL_LOG_IF(dumpEnable,"[2nd] = %x, %x, %x, %x \n", pCamCalData->N3D3A.Data[1][0],pCamCalData->N3D3A.Data[1][1], pCamCalData->N3D3A.Data[1][2],pCamCalData->N3D3A.Data[1][3]); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================3A Data==================\n"); #endif return err; } UINT32 DoCamCal3DGeo(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { stCAM_CAL_INFO_STRUCT cam_calCfg; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; MUINT32 idx; UINT32 ioctlerr; UINT32 err = CamCalReturnErr[pCamCalData->Command]; UINT32 PregainFactor, PregainOffset; UINT32 PregainFactorH, PregainOffsetH; UINT32 GainValue; if(pCamCalData->DataVer != CAM_CAL_N3D_DATA) { err = CAM_CAL_ERR_NO_DEVICE; CAM_CAL_ERR("ioctl err\n"); ShowCmdErrorLog(pCamCalData->Command); } else { if(BlockSize!=CAM_CAL_N3D_3D_SIZE) { CAM_CAL_ERR("BlockSize(%d) is not correct (%d)\n",BlockSize,CAM_CAL_N3D_3D_SIZE); ShowCmdErrorLog(pCamCalData->Command); } else { cam_calCfg.u4Offset = (start_addr|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3D3D.Data[0][0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } cam_calCfg.u4Offset = ((start_addr>>16)|0xFFFF); cam_calCfg.u4Length = BlockSize; //sizeof(ucModuleNumber) cam_calCfg.pu1Params= (u8 *)&pCamCalData->N3D3D.Data[1][0]; ioctlerr= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); if(!ioctlerr) { err = CAM_CAL_ERR_NO_ERR; } else { CAM_CAL_ERR("ioctl err\n"); err = CamCalReturnErr[pCamCalData->Command]; ShowCmdErrorLog(pCamCalData->Command); } } } #ifdef DEBUG_CALIBRATION_LOAD CAM_CAL_LOG_IF(dumpEnable,"======================3D Data==================\n"); CAM_CAL_LOG_IF(dumpEnable,"[1st] = %x, %x, %x, %x \n", pCamCalData->N3D3D.Data[0][0],pCamCalData->N3D3D.Data[0][1], pCamCalData->N3D3D.Data[0][2],pCamCalData->N3D3D.Data[0][3]); CAM_CAL_LOG_IF(dumpEnable,"[2nd] = %x, %x, %x, %x \n", pCamCalData->N3D3D.Data[1][0],pCamCalData->N3D3D.Data[1][1], pCamCalData->N3D3D.Data[1][2],pCamCalData->N3D3D.Data[1][3]); CAM_CAL_LOG_IF(dumpEnable,"RETURN = 0x%x \n", err); CAM_CAL_LOG_IF(dumpEnable,"======================3D Data==================\n"); #endif return err; } /****************************************************************************** *seanlin 121017, MT658x *In order to get data one block by one block instead of overall data in one time *It must extract FileID and LayoutType from CAM_CALGetCalData() *******************************************************************************/ UINT32 DoCamCalLayoutCheck(void) { MINT32 lCamcamFID = -1; //seanlin 121017 01 local for layout check UCHAR cBuf[128] = "/dev/"; UCHAR HeadID[5] = "NONE"; UINT32 result = CAM_CAL_ERR_NO_DEVICE; //cam_cal stCAM_CAL_INFO_STRUCT cam_calCfg; UINT32 CheckID,i ; INT32 err; switch(gIsInitedCamCal) { case CAM_CAL_LAYOUT_RTN_PASS: result = CAM_CAL_ERR_NO_ERR; break; case CAM_CAL_LAYOUT_RTN_QUEUE: case CAM_CAL_LAYOUT_RTN_FAILED: default: result = CAM_CAL_ERR_NO_DEVICE; break; } if ((gIsInitedCamCal==CAM_CAL_LAYOUT_RTN_QUEUE) && (CAM_CALInit() != CAM_CAL_NONE) && (CAM_CALDeviceName(&cBuf[0]) == 0)) { lCamcamFID = open(cBuf, O_RDWR); CAM_CAL_LOG_IF(dumpEnable,"lCamcamFID= 0x%x", lCamcamFID); if(lCamcamFID == -1) { CAM_CAL_ERR("----error: can't open CAM_CAL %s----\n",cBuf); gIsInitedCamCal=CAM_CAL_LAYOUT_RTN_FAILED; result = CAM_CAL_ERR_NO_DEVICE; return result;//0; } //read ID cam_calCfg.u4Offset = 0xFFFFFFFF; for (i = 0; i< MAX_CALIBRATION_LAYOUT_NUM; i++) { if (cam_calCfg.u4Offset != CalLayoutTbl[i].HeaderAddr) { CheckID = 0x00000000; cam_calCfg.u4Offset = CalLayoutTbl[i].HeaderAddr; cam_calCfg.u4Length = 4; cam_calCfg.pu1Params = (u8 *)&CheckID; err= ioctl(lCamcamFID, CAM_CALIOC_G_READ , &cam_calCfg); if(err< 0) { CAM_CAL_ERR("ioctl err\n"); CAM_CAL_ERR("Read header ID fail err = 0x%x \n",err); gIsInitedCamCal=CAM_CAL_LAYOUT_RTN_FAILED; result = CAM_CAL_ERR_NO_DEVICE; break; } } CAM_CAL_LOG_IF(dumpEnable,"Table[%d] ID= 0x%x",i, CheckID); if(CheckID == CalLayoutTbl[i].HeaderId) { LayoutType = i; gIsInitedCamCal=CAM_CAL_LAYOUT_RTN_PASS; result = CAM_CAL_ERR_NO_ERR; break; } } CAM_CAL_LOG_IF(dumpEnable,"LayoutType= 0x%x",LayoutType); CAM_CAL_LOG_IF(dumpEnable,"result= 0x%x",result); //// close(lCamcamFID); } else //test { CAM_CAL_LOG_IF(dumpEnable,"----gIsInitedCamCal_0x%x!----\n",gIsInitedCamCal); CAM_CAL_LOG_IF(dumpEnable,"----NO CAM_CAL_%s!----\n",cBuf); CAM_CAL_LOG_IF(dumpEnable,"----NO CCAM_CALInit_%d!----\n",CAM_CALInit()); } return result; } /****************************************************************************** * *******************************************************************************/ UINT32 CAM_CALGetCalData(UINT32* pGetSensorCalData) { UCHAR cBuf[128] = "/dev/"; UCHAR HeadID[5] = "NONE"; UINT32 result = CAM_CAL_ERR_NO_DEVICE; //cam_cal stCAM_CAL_INFO_STRUCT cam_calCfg; UINT32 CheckID,i ; INT32 err = CAM_CAL_ERR_NO_DEVICE; // static UINT16 LayoutType = (MAX_CALIBRATION_LAYOUT_NUM+1); //seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. INT32 CamcamFID = 0; //seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. UINT16 u2IDMatch = 0; UINT32 ulPartNumberCount = 0; CAMERA_CAM_CAL_TYPE_ENUM lsCommand; PCAM_CAL_DATA_STRUCT pCamCalData = (PCAM_CAL_DATA_STRUCT)pGetSensorCalData; // CAM_CAL_LOG_IF(dumpEnable,"CAM_CALGetCalData(0x%8x)----\n",(unsigned int)pGetSensorCalData); //====== Get Property ====== char value[PROPERTY_VALUE_MAX] = {'\0'}; property_get("camcalcamcal.log", value, "0"); dumpEnable = atoi(value); //====== Get Property ====== lsCommand = pCamCalData->Command; CAM_CAL_LOG_IF(dumpEnable,"pCamCalData->Command = 0x%x \n",pCamCalData->Command); CAM_CAL_LOG_IF(dumpEnable,"lsCommand = 0x%x \n",lsCommand); //Make sure Layout is confirmed, first if(DoCamCalLayoutCheck()==CAM_CAL_ERR_NO_ERR) { pCamCalData->DataVer = (CAM_CAL_DATA_VER_ENUM)CalLayoutTbl[LayoutType].DataVer; if ((CAM_CALInit() != CAM_CAL_NONE) && (CAM_CALDeviceName(&cBuf[0]) == 0)) { CamcamFID = open(cBuf, O_RDWR); if(CamcamFID == -1) { CAM_CAL_LOG_IF(dumpEnable,"----error: can't open CAM_CAL %s----\n",cBuf); result = CamCalReturnErr[lsCommand]; ShowCmdErrorLog(lsCommand); return result; } /*********************************************/ if ((CalLayoutTbl[LayoutType].CalItemTbl[lsCommand].Include != 0) &&(CalLayoutTbl[LayoutType].CalItemTbl[lsCommand].GetCalDataProcess != NULL)) { result = CalLayoutTbl[LayoutType].CalItemTbl[lsCommand].GetCalDataProcess( CamcamFID, CalLayoutTbl[LayoutType].CalItemTbl[lsCommand].StartAddr, CalLayoutTbl[LayoutType].CalItemTbl[lsCommand].BlockSize, pGetSensorCalData); } else { result = CamCalReturnErr[lsCommand]; ShowCmdErrorLog(lsCommand); } /*********************************************/ close(CamcamFID); } } else { result = CamCalReturnErr[lsCommand]; ShowCmdErrorLog(lsCommand); return result; } CAM_CAL_LOG_IF(dumpEnable,"result = 0x%x\n",result); return result; } /****************************************************************************** *seanlin 121017, MT658x *In order to get data one block by one block instead of overall data in one time *It must add reset function if destory in cam cal drv instance *******************************************************************************/ UINT32 DoCamCalDataReset(INT32 CamcamFID, UINT32 start_addr, UINT32 BlockSize, UINT32* pGetSensorCalData) { gIsInitedCamCal = CAM_CAL_LAYOUT_RTN_QUEUE;//seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. LayoutType = (MAX_CALIBRATION_LAYOUT_NUM+1); //seanlin 121017 why static? Because cam_cal_drv will get data one block by one block instead of overall in one time. bFirstLoad = TRUE; return 0; } #if 0 #if 1 unsigned int size[MAX_CALIBRATION_LAYOUT_NUM]={ CALIBRATION_DATA_SIZE_SLIM_LSC1, CALIBRATION_DATA_SIZE_N3D_DATA1, CALIBRATION_DATA_SIZE_SUNNY_Q8N03D_LSC1}; #endif if(bFirstLoad) { cam_calCfg.u4Length = CAM_CAL_PART_NUMBERS_COUNT*LSC_DATA_BYTES; //sizeof(ulModuleNumber) cam_calCfg.u4Offset = size[LayoutType]+CUSTOM_CAM_CAL_PART_NUMBERS_START_ADD*LSC_DATA_BYTES; cam_calCfg.pu1Params= (u8 *)ulModuleNumber; err= ioctl(CamcamFID, CAM_CALIOC_S_WRITE, &cam_calCfg); bFirstLoad = FALSE; #ifdef CUSTOM_CAM_CAL_NEW_MODULE_NUMBER_CHECK cam_calCfg.u4Length = CAM_CAL_PART_NUMBERS_COUNT*LSC_DATA_BYTES; //sizeof(ulModuleNumber) cam_calCfg.u4Offset = size[LayoutType]+CUSTOM_CAM_CAL_PART_NUMBERS_START_ADD*LSC_DATA_BYTES; cam_calCfg.pu1Params= (u8 *)&ulPartNumbertmp[0]; err= ioctl(CamcamFID, CAM_CALIOC_G_READ, &cam_calCfg); for(i=0;i<CAM_CAL_PART_NUMBERS_COUNT;i++) { CAM_CAL_LOG_IF(dumpEnable,"ulPartNumbertmp[%d]=0x%8x\n",i,ulPartNumbertmp[i]); } #endif } #endif
[ "vetaxa.manchyk@gmail.com" ]
vetaxa.manchyk@gmail.com
ec8f3636d84fda0d4bd303cad9c4de46fb3b8536
b4eafb92231c3aa48961f3caec7f7295b1e28daf
/codetop/70.cpp
15d5a6994bf1e65d554fa7485b976febbb84ccd6
[]
no_license
want-food/leetcode
8d11bc299eac455cb6d279a8fd8357d8954ea6e2
c13ad3b3f7ed5d8996948eb17d04dd862de0946d
refs/heads/main
2023-06-12T03:32:20.435768
2021-07-09T00:27:43
2021-07-09T00:27:43
332,108,019
0
0
null
null
null
null
UTF-8
C++
false
false
659
cpp
/************************************************************************* > File Name: 70.cpp > Author: dingchen > Mail: 18811502859@163.com > Created Time: Mon Jul 5 23:58:10 2021 ************************************************************************/ #include <iostream> using namespace std; class Solution { public: int climbStairs(int n) { if(n == 0 || n == 1) return n; int first = 0, second = 1; for (int i = 0; i < n; i++) { int tmp = second; second += first; first = tmp; } return second; } }; int main() { int n = 3; Solution solution; int res = solution.climbStairs(n); cout << "res: " << res << endl; }
[ "645743914@qq.com" ]
645743914@qq.com
224a3c71c43fe2e2c798ad01c435760b3ea37b89
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/13_22437_20.cpp
f9954f4edb981ab2f40cb8972169a56f73a68f85
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
912
cpp
#include <string> #include <algorithm> #include <iostream> #include <fstream> #include <cmath> using namespace std; int palindrome(string word) { do{ string rev_word = word; reverse(rev_word.begin(), rev_word.end()); if(word == rev_word)return 1; else return 0; }while (word != "END"); } int main() { ifstream in("entrada.in"); ofstream out ("res_1000.txt"); int pal[14]={1, 4, 9 ,121, 484, 10201, 12321, 14641, 40804, 44944 }; int SIZE=9; int T=0, a=0,b=0; in>>T; for(int x=1; x<=T; x++) { int res=0; in>>a>>b; int i=0, j=SIZE; while(a>pal[i] && i<SIZE) i++; while(b<pal[j] && j>=0) j--; //cout<<"i: "<<i<<" ["<<pal[i]<<" ]"<<endl; //cout<<"j: "<<j<<" ["<<pal[j]<<" ]"<<endl; if(j<i)res=0; else res=j-i+1; out<<"Case #"<<x<<": "<<res<<endl; } /* string a; while(a!="-1") { cin>>a; if(palindrome(a)) out<<a<<endl; } */ return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
ba2babda7197c9c8777e36419fe091ceb34e73c5
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE590_Free_Memory_Not_on_Heap/s02/CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_05.cpp
2e46cefa80b3172c059439fd23f7d1f638b739c2
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
4,061
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_05.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml Template File: sources-sink-05.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: alloca Data buffer is allocated on the stack with alloca() * GoodSource: Allocate memory on the heap * Sink: * BadSink : Print then free data * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) * * */ #include "std_testcase.h" #include <wchar.h> /* The two variables below are not defined as "const", but are never assigned any other value, so a tool should be able to identify that reads of these will always return their initialized values. */ static int staticTrue = 1; /* true */ static int staticFalse = 0; /* false */ namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_05 { #ifndef OMITBAD void bad() { twoIntsStruct * data; data = NULL; /* Initialize data */ { { /* FLAW: data is allocated on the stack and deallocated in the BadSink */ twoIntsStruct * dataBuffer = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); { size_t i; for (i = 0; i < 100; i++) { dataBuffer[i].intOne = 1; dataBuffer[i].intTwo = 1; } } data = dataBuffer; } } printStructLine(&data[0]); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */ static void goodG2B1() { twoIntsStruct * data; data = NULL; /* Initialize data */ { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ twoIntsStruct * dataBuffer = new twoIntsStruct[100]; { size_t i; for (i = 0; i < 100; i++) { dataBuffer[i].intOne = 1; dataBuffer[i].intTwo = 1; } } data = dataBuffer; } } printStructLine(&data[0]); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete [] data; } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { twoIntsStruct * data; data = NULL; /* Initialize data */ { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ twoIntsStruct * dataBuffer = new twoIntsStruct[100]; { size_t i; for (i = 0; i < 100; i++) { dataBuffer[i].intOne = 1; dataBuffer[i].intTwo = 1; } } data = dataBuffer; } } printStructLine(&data[0]); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete [] data; } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_05; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
37c6f73d49bef9421b1ec1f6cd36f1056f7b52d2
6f972188a65c5f2562f3f54fdf3eab2d636f91d5
/Source/Engine/Core/Math/Plane.h
5d863b101f36b3875aeceebcc4302c18be71a397
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
everard/SELENE-Device
7112b41c1c9fd0ea71051e29bd4b4eb3a6c7f18a
775bb5cf66ba9fdbc55eac7b216e035c36d82954
refs/heads/master
2020-05-18T01:26:20.274659
2015-02-23T16:24:50
2015-02-23T16:24:50
6,096,086
0
0
null
null
null
null
UTF-8
C++
false
false
3,133
h
// Copyright (c) 2012 Nezametdinov E. Ildus // Licensed under the MIT License (see LICENSE.txt for details) #ifndef PLANE_H #define PLANE_H #include "Vector.h" namespace selene { /** * \addtogroup Math * @{ */ /** * Represents plane in 3D space. */ class Plane { public: /** * \brief Constructs plane with given coefficients. * \param[in] a x coordinate of normal * \param[in] b y coordinate of normal * \param[in] c z coordinate of normal * \param[in] d constant in plane equation */ Plane(float a = 0.0f, float b = 0.0f, float c = 0.0f, float d = 0.0f); /** * \brief Constructs plane with given normal and point. * \param[in] normal normal of the plane * \param[in] point point on the plane */ Plane(const Vector3d& normal, const Vector3d& point); /** * \brief Constructs plane from three points. * \param[in] point0 the first point * \param[in] point1 the second point * \param[in] point2 the third point */ Plane(const Vector3d& point0, const Vector3d& point1, const Vector3d& point2); Plane(const Plane&) = default; ~Plane(); Plane& operator =(const Plane&) = default; /** * \brief Defines plane with given coefficients. * \param[in] a x coordinate of normal * \param[in] b y coordinate of normal * \param[in] c z coordinate of normal * \param[in] d constant in plane equation */ void define(float a, float b, float c, float d); /** * \brief Defines plane with given normal and point. * \param[in] normal normal of the plane * \param[in] point point on the plane */ void define(const Vector3d& normal, const Vector3d& point); /** * \brief Defines plane with three points. * \param[in] point0 the first point * \param[in] point1 the second point * \param[in] point2 the third point */ void define(const Vector3d& point0, const Vector3d& point1, const Vector3d& point2); /** * \brief Computes distance to the given point. * \param[in] point point * \return distance to the point */ float distance(const Vector3d& point) const; /** * \brief Normalizes plane. */ void normalize(); private: Vector3d normal_; float d_; }; /** * @} */ } #endif
[ "neil.log@gmail.com" ]
neil.log@gmail.com
2389bc92adebeafc5ce7f6e8e64cb60bc72f2d76
a0d97e57842892f29e77fb477441f86078d3a356
/sources/layers/movelayerundocommand.h
5d1e3a27e1e2749ef3b8a73cee8fcc4dd0933718
[]
no_license
ymahinc/MyTypon
89cac5385edeed2d171392e2160b62bf6ed2fd7f
5fa2548d2cfa909575797474c66361772c9ce397
refs/heads/master
2020-04-27T21:03:20.178564
2019-03-09T10:56:12
2019-03-09T10:56:12
174,682,329
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
#ifndef MOVELAYERUNDOCOMMAND_H #define MOVELAYERUNDOCOMMAND_H #include <QUndoCommand> #include "layer.h" #include "layersstack.h" class MoveLayerUndoCommand : public QUndoCommand { public: MoveLayerUndoCommand(LayersStack *stack, Layer *layer, bool up); void undo(); void redo(); private: LayersStack *m_stack; Layer *m_layer; bool m_up; }; #endif // MOVELAYERUNDOCOMMAND_H
[ "ymahinc@gmail.com" ]
ymahinc@gmail.com
fa60ba14eca7cc88e90bd730706d185c3bd68caa
dffed8c214c1a4dfcc597aeb085d54f4a0e7825d
/LArSoftCodes/arxiv/wketchum_MCTruth_Anatree_Dec17/MCTruth/MCTruthBase/MCTruthParticleList.h
98f5df709cd5dcf22d7e08a7e3ed198e3753f29c
[]
no_license
erezcoh4/CCQEana
852cdc24eb3820ab8d291c0c23aa2b7fcefa1985
ced8c88b4e3fee18a685bf353043c7a70288f82d
refs/heads/master
2021-01-01T06:56:28.028517
2019-05-07T11:45:59
2019-05-07T11:45:59
97,554,037
0
1
null
null
null
null
UTF-8
C++
false
false
17,358
h
//////////////////////////////////////////////////////////////////////// /// \file MCTruthParticleList.h /// \brief Particle list in DetSim contains Monte Carlo particle information. /// /// \version $Id: MCTruthParticleList.h,v 1.13 2010/05/13 16:12:20 seligman Exp $ /// \author seligman@nevis.columbia.edu //////////////////////////////////////////////////////////////////////// /// /// ******************************************************************** /// *** This class has been lifted from nutools and modified so that it /// *** does NOT take ownwership of the MCParticles that are added to it /// *** so we can avoid duplicating them /// ******************************************************************** /// /// A container for particles generated during an event simulation. /// It acts like a map<int,Particle*> but with additional features: /// /// - A method Cut(double) that will remove all particles with energy /// less than the argument. /// /// - Methods TrackId(int) and Particle(int) for those who are unfamiliar with the /// concepts associated with STL maps: /// truth::MCTruthParticleList* MCTruthParticleList = // ...; /// int numberOfParticles = MCTruthParticleList->size(); /// for (int i=0; i<numberOfParticles; ++i) /// { /// int trackID = MCTruthParticleList->TrackId(i); /// simb::MCParticle* particle = MCTruthParticleList->Particle(i); /// } /// The STL equivalent to the above statements (more efficient): /// truth::MCTruthParticleList* MCTruthParticleList = // ...; /// for ( auto i = MCTruthParticleList->begin(); /// i != MCTruthParticleList->end(); ++i ) /// { /// const simb::MCParticle* particle = (*i).second; /// int trackID = particle->TrackId(); // or... /// int trackID = (*i).first; /// } /// or, more compact: /// truth::MCTruthParticleList* MCTruthParticleList = // ...; /// for ( const auto& i: *MCTruthParticleList) /// { /// const simb::MCParticle* particle = i.second; /// int trackID = particle->TrackId(); // or... /// int trackID = i.first; /// } /// If looping over all the particles, do prefer the second and third forms, /// since the first one is unacceptably inefficient for large events. /// /// - Methods to access the list of primary particles in the event: /// truth::MCTruthParticleList MCTruthParticleList = // ...; /// int numberOfPrimaries = MCTruthParticleList->NumberOfPrimaries(); /// for ( int i = 0; i != numberOfPrimaries; ++i ) /// { /// simb::MCParticle* particle = MCTruthParticleList->Primary(i); /// ... /// } /// There's also a simple test: /// int trackID = // ...; /// if ( MCTruthParticleList->IsPrimary(trackID) ) {...} /// /// (Aside: note that MCTruthParticleList[i] does NOT give you the "i-th" /// particle in the list; it gives you the particle whose trackID /// is "i".) /// Also this form becomes unacceptably inefficient when looping over all the /// particles in a crowded event: prefer to do a bit more of typing as: /// truth::MCTruthParticleList* MCTruthParticleList = // ...; /// for ( const auto& i: *MCTruthParticleList) /// { /// int trackID = i.first; /// if (!MCTruthParticleList->IsPrimary(trackID)) continue; /// const simb::MCParticle* primary = i.second; /// // ... /// } /// /// /// /// - A method EveId(int) to determine the "eve ID" (or ultimate /// mother) for a given particle. For more information, including how /// to supply your own eve ID calculation, see /// Simulation/EveIdCalculator.h and Simulation/EmEveIdCalculator.h. /// - Two MCTruthParticleLists can be merged, which may be useful for /// modeling overlays: /// truth::MCTruthParticleList a,b; /// a.Add(b); /// There's also an operator+ that does the same thing: /// truth::MCTruthParticleList c = a + b; /// WARNING! If the track IDs of the two lists overlapped, then /// the results would be garbage. Therefore, the track IDs of the /// second operand are adjusted when the two lists are merged (without /// actually changing the IDs in that second list). Don't rely /// on the track IDs remaining unchanged! /// /// - The previous procedure requires that the track IDs for an entire /// list be adjust by a fixed offset. In case this functionality is /// useful for cases other than merging lists, it's been made /// available via Add(int) and operator+(int) methods: /// truth::MCTruthParticleList a,b,combinedAB; /// truth::MCTruthParticleList c = b + 10000000; // add 1000000 to all the track IDs in list b /// combinedAB = a + c; /// /// - If you use the clear() or erase() methods, the list will also /// delete the underlying Particle*. (This means that if you use /// insert() or Add() to add a particle to the list, the /// MCTruthParticleList will take over management of it. Don't delete the /// pointer yourself!) /// /// - Print() and operator<< methods for ROOT display and ease of /// debugging. #ifndef SIM_MCTruthParticleList_H #define SIM_MCTruthParticleList_H #include "nusimdata/SimulationBase/MCParticle.h" #include <memory> #include <ostream> #include <map> #include <cstdlib> // std::abs() namespace truth { // Forward declarations. class MCTruthEveIdCalculator; class MCTruthParticleList { public: // Some type definitions to make life easier, and to help "hide" // the implementation details. (If you're not familiar with STL, // you can ignore these definitions.) typedef std::map<int,const simb::MCParticle*> list_type; typedef list_type::key_type key_type; typedef list_type::mapped_type mapped_type; typedef list_type::value_type value_type; typedef list_type::iterator iterator; typedef list_type::const_iterator const_iterator; typedef list_type::reverse_iterator reverse_iterator; typedef list_type::const_reverse_iterator const_reverse_iterator; typedef list_type::size_type size_type; typedef list_type::difference_type difference_type; typedef list_type::key_compare key_compare; typedef list_type::allocator_type allocator_type; // Standard constructor, let compiler default the detector MCTruthParticleList(); virtual ~MCTruthParticleList(); private: struct archived_info_type { int parentID = 0; archived_info_type() = default; archived_info_type(int pid): parentID(pid) {} archived_info_type(simb::MCParticle const& part) : parentID(part.Mother()) {} archived_info_type(simb::MCParticle const* part) : parentID(part->Mother()) {} int Mother() const { return parentID; } friend std::ostream& operator<< ( std::ostream& output, const MCTruthParticleList::archived_info_type& ); }; // archived_info_type typedef std::set< int > primaries_type; typedef std::map<int, archived_info_type> archive_type; typedef primaries_type::iterator primaries_iterator; typedef primaries_type::const_iterator primaries_const_iterator; list_type m_MCTruthParticleList; ///< Sorted list of particles in the event primaries_type m_primaries; ///< Sorted list of the track IDs of ///< primary particles. archive_type m_archive; ///< archive of the particles no longer among us //---------------------------------------------------------------------------- // variable for eve ID calculator. We're using an unique_ptr, // so when this object is eventually deleted (at the end of the job) // it will delete the underlying pointer. mutable std::unique_ptr<MCTruthEveIdCalculator> m_eveIdCalculator; #ifndef __GCCXML__ public: // Because this list contains pointers, we have to provide the // copy and assignment constructors. // MCTruthParticleList( const MCTruthParticleList& rhs ); // MCTruthParticleList& operator=( const MCTruthParticleList& rhs ); // you know what? let's make it UNCOPIABLE instead! // The cost of copying this buauty is such that we don't want it // to happen unless really requested (copy()) MCTruthParticleList( const MCTruthParticleList& rhs ) = delete; MCTruthParticleList& operator=( const MCTruthParticleList& rhs ) = delete; MCTruthParticleList( MCTruthParticleList&& rhs ) = default; MCTruthParticleList& operator=( MCTruthParticleList&& rhs ) = default; /// Returns a copy of this object MCTruthParticleList MakeCopy() const; // The methods advertised above: // Apply an energy threshold cut to the particles in the list, // removing all those that fall below the cut. (Be careful if // you're playing with voxels; this method does not change the // contents of a LArVoxelList.) void Cut( const double& ); const key_type& TrackId( const size_type ) const; mapped_type const& Particle( const size_type ) const; mapped_type Particle( const size_type ); /// Returns whether we have this particle, live (with full information) bool HasParticle( int trackID ) const { auto iParticle = find(trackID); return (iParticle != end()) && (iParticle->second != nullptr); } /// Returns whether we have had this particle, archived or live bool KnownParticle( int trackID ) const { return find(trackID) != end(); } bool IsPrimary( int trackID ) const; int NumberOfPrimaries() const; std::vector<const simb::MCParticle*> GetPrimaries() const; const simb::MCParticle* Primary( const int ) const; // Standard STL methods, to make this class look like an STL map. // Again, if you don't know STL, you can just ignore these // methods. iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const; size_type size() const; bool empty() const; void swap( MCTruthParticleList& other ); iterator find(const key_type& key); const_iterator find(const key_type& key) const; iterator upper_bound(const key_type& key); const_iterator upper_bound(const key_type& key) const; iterator lower_bound(const key_type& key); const_iterator lower_bound(const key_type& key) const; // Be careful when using operator[] here! It takes the track ID as the argument: // truth::MCTruthParticleList partList; // const sim::Particle* = partList[3]; // The above line means the particle with trackID==3, NOT the third // particle in the list! Use partList.Particle(3) if you want to // get the particles by index number instead of track ID. // Note that this only works in a const context. Use the insert() // or Add() methods to add a new particle to the list. mapped_type const& operator[]( const key_type& key ) const; // This non-const version of operator[] does NOT permit you to insert // Particles into the list. Use Add() or insert() for that. mapped_type operator[]( const key_type& key ); mapped_type at(const key_type& key); mapped_type const& at(const key_type& key) const; /// Extracts the key from the specified value key_type key(mapped_type const& part) const; // These two methods do the same thing: // - Add the Particle to the list, using the track ID as the key. // - Update the list of primary particles as needed. // Note that when you insert a Particle* into a MCTruthParticleList, it // takes over management of the pointer. Don't delete it yourself! void insert( const simb::MCParticle* value ); void Add( const simb::MCParticle* value ); /// Removes the particle from the list, keeping minimal info of it void Archive( const key_type& key ); void Archive( const mapped_type& key ); /// This function seeks for the exact key, not its absolute value int GetMotherOf( const key_type& key ) const; void clear(); size_type erase( const key_type& key ); iterator erase( iterator key ); friend std::ostream& operator<< ( std::ostream& output, const MCTruthParticleList& ); friend std::ostream& operator<< ( std::ostream& output, const MCTruthParticleList::archived_info_type& ); // Methods associated with the eve ID calculation. // Calculate the eve ID. int EveId ( const int trackID ) const; // Set a pointer to a different eve ID calculation. The name // begins with "Adopt" because it accepts control of the ponters; // do NOT delete the pointer yourself if you use this method. void AdoptEveIdCalculator( MCTruthEveIdCalculator* ) const; #endif }; } #ifndef __GCCXML__ inline truth::MCTruthParticleList::iterator truth::MCTruthParticleList::begin() { return m_MCTruthParticleList.begin(); } inline truth::MCTruthParticleList::const_iterator truth::MCTruthParticleList::begin() const { return m_MCTruthParticleList.begin(); } inline truth::MCTruthParticleList::iterator truth::MCTruthParticleList::end() { return m_MCTruthParticleList.end(); } inline truth::MCTruthParticleList::const_iterator truth::MCTruthParticleList::end() const { return m_MCTruthParticleList.end(); } inline truth::MCTruthParticleList::reverse_iterator truth::MCTruthParticleList::rbegin() { return m_MCTruthParticleList.rbegin(); } inline truth::MCTruthParticleList::const_reverse_iterator truth::MCTruthParticleList::rbegin() const { return m_MCTruthParticleList.rbegin(); } inline truth::MCTruthParticleList::reverse_iterator truth::MCTruthParticleList::rend() { return m_MCTruthParticleList.rend(); } inline truth::MCTruthParticleList::const_reverse_iterator truth::MCTruthParticleList::rend() const { return m_MCTruthParticleList.rend(); } inline truth::MCTruthParticleList::size_type truth::MCTruthParticleList::size() const { return m_MCTruthParticleList.size(); } inline bool truth::MCTruthParticleList::empty() const { return m_MCTruthParticleList.empty(); } inline void truth::MCTruthParticleList::Add(const simb::MCParticle* value) { insert(value); } inline void truth::MCTruthParticleList::swap( truth::MCTruthParticleList& other ) { m_MCTruthParticleList.swap( other.m_MCTruthParticleList ); m_archive.swap( other.m_archive ); m_primaries.swap( other.m_primaries); } inline truth::MCTruthParticleList::iterator truth::MCTruthParticleList::find(const truth::MCTruthParticleList::key_type& key) { return m_MCTruthParticleList.find(abs(key)); } inline truth::MCTruthParticleList::const_iterator truth::MCTruthParticleList::find(const truth::MCTruthParticleList::key_type& key) const { return m_MCTruthParticleList.find(abs(key)); } inline truth::MCTruthParticleList::iterator truth::MCTruthParticleList::upper_bound(const truth::MCTruthParticleList::key_type& key) { return m_MCTruthParticleList.upper_bound(abs(key)); } inline truth::MCTruthParticleList::const_iterator truth::MCTruthParticleList::upper_bound(const truth::MCTruthParticleList::key_type& key) const { return m_MCTruthParticleList.upper_bound(abs(key)); } inline truth::MCTruthParticleList::iterator truth::MCTruthParticleList::lower_bound(const truth::MCTruthParticleList::key_type& key) { return m_MCTruthParticleList.lower_bound(abs(key)); } inline truth::MCTruthParticleList::const_iterator truth::MCTruthParticleList::lower_bound(const truth::MCTruthParticleList::key_type& key) const { return m_MCTruthParticleList.lower_bound(abs(key)); } inline truth::MCTruthParticleList::mapped_type truth::MCTruthParticleList::at(const truth::MCTruthParticleList::key_type& key) { return m_MCTruthParticleList.at(std::abs(key)); } inline truth::MCTruthParticleList::mapped_type const& truth::MCTruthParticleList::at(const truth::MCTruthParticleList::key_type& key) const { return m_MCTruthParticleList.at(std::abs(key)); } inline truth::MCTruthParticleList::mapped_type truth::MCTruthParticleList::operator[] (const truth::MCTruthParticleList::key_type& key) { return at(key); } inline truth::MCTruthParticleList::mapped_type const& truth::MCTruthParticleList::operator[] (const truth::MCTruthParticleList::key_type& key) const { return at(key); } inline truth::MCTruthParticleList::key_type truth::MCTruthParticleList::key(mapped_type const& part) const { return part->TrackId(); } #endif #endif // SIM_MCTruthParticleList_H
[ "cohen.erez7@gmail.com" ]
cohen.erez7@gmail.com
a99fe086dc03ceaf7e295c32d90cf1ec0041c011
42c64672a2a640646a2b66197da2e5134486a1bc
/mixExcel/FirstStep_Excel_Wirte2/FirstStep_Excel/CBorders.h
6296d032eba2c759448a07a5cb4a7020c5cf2c7b
[]
no_license
15831944/C_plus_plus
898de0abd44898060460c9adcabade9f4849fece
50a3d1e72718c6d577a49180ce29e8c81108cdfd
refs/heads/master
2022-10-01T15:30:13.837718
2020-06-08T20:08:09
2020-06-08T20:08:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,225
h
// Machine generated IDispatch wrapper class(es) created with Add Class from Typelib Wizard // CBorders wrapper class class CBorders : public COleDispatchDriver { public: CBorders(){} // Calls COleDispatchDriver default constructor CBorders(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CBorders(const CBorders& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: // Borders methods public: LPDISPATCH get_Application() { LPDISPATCH result; InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_Creator() { long result; InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Parent() { LPDISPATCH result; InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_Color() { VARIANT result; InvokeHelper(0x63, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Color(VARIANT newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x63, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_ColorIndex() { VARIANT result; InvokeHelper(0x61, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_ColorIndex(VARIANT newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x61, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } long get_Count() { long result; InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Item(long Index) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, Index); return result; } VARIANT get_LineStyle() { VARIANT result; InvokeHelper(0x77, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_LineStyle(VARIANT newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x77, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPUNKNOWN get__NewEnum() { LPUNKNOWN result; InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); return result; } VARIANT get_Value() { VARIANT result; InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Value(VARIANT newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_Weight() { VARIANT result; InvokeHelper(0x78, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Weight(VARIANT newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x78, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPDISPATCH get__Default(long Index) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, Index); return result; } // Borders properties public: };
[ "logovopost@yandex.ru" ]
logovopost@yandex.ru
73523d9b9df64c1eb5b3e48db6698c2ba115812d
693d93174f43a81d8a65041553282a8872e3a6ff
/src/test/fuzz/float.cpp
43410dc8e93a3002c77092fe5dd7d2f3a484ab00
[ "MIT" ]
permissive
eleccoin/eleccoin
c075719d5ee676fc2bb9a21f3711d75d673655bd
963f6d4a069e40ab2e46217e5d49bc94adda2c5c
refs/heads/master
2022-11-13T02:38:36.662655
2022-10-30T08:56:57
2022-10-30T08:56:57
238,475,897
3
7
MIT
2022-01-10T07:29:19
2020-02-05T14:56:34
C++
UTF-8
C++
false
false
2,677
cpp
// Copyright (c) 2020-2021 The Eleccoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <memusage.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/serfloat.h> #include <version.h> #include <cassert> #include <cmath> #include <limits> FUZZ_TARGET(float) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); { const double d{[&] { double tmp; CallOneOf( fuzzed_data_provider, // an actual number [&] { tmp = fuzzed_data_provider.ConsumeFloatingPoint<double>(); }, // special numbers and NANs [&] { tmp = fuzzed_data_provider.PickValueInArray({ std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::min(), -std::numeric_limits<double>::min(), std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), std::numeric_limits<double>::lowest(), -std::numeric_limits<double>::lowest(), std::numeric_limits<double>::quiet_NaN(), -std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::signaling_NaN(), -std::numeric_limits<double>::signaling_NaN(), std::numeric_limits<double>::denorm_min(), -std::numeric_limits<double>::denorm_min(), }); }, // Anything from raw memory (also checks that DecodeDouble doesn't crash on any input) [&] { tmp = DecodeDouble(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); }); return tmp; }()}; (void)memusage::DynamicUsage(d); uint64_t encoded = EncodeDouble(d); if constexpr (std::numeric_limits<double>::is_iec559) { if (!std::isnan(d)) { uint64_t encoded_in_memory; std::copy((const unsigned char*)&d, (const unsigned char*)(&d + 1), (unsigned char*)&encoded_in_memory); assert(encoded_in_memory == encoded); } } double d_deserialized = DecodeDouble(encoded); assert(std::isnan(d) == std::isnan(d_deserialized)); assert(std::isnan(d) || d == d_deserialized); } }
[ "unify@eleccoin.org" ]
unify@eleccoin.org
83f61013b39ea5e054704cf89891879c418215eb
387f582cdc6370bbfb364b35a0642d55ede59387
/Plugins/AdvancedSteamSessions/Intermediate/Build/Win64/UE4Editor/Inc/AdvancedSteamSessions/AdvancedSteamFriendsLibrary.generated.h
6e8084b408216a9b9a4c26d4e9c638adcff8acc6
[]
no_license
ScottyO19/Medieval_Mayhem1
4b8c339e5ba350e30a3fcf14ef26ec1fd6f5761c
09a988b821059efb897bd36570b6013066203d61
refs/heads/main
2023-02-27T11:56:23.030118
2021-01-26T19:21:43
2021-01-26T19:21:43
332,352,154
0
0
null
null
null
null
UTF-8
C++
false
false
8,629
h
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS struct FBPSteamGroupInfo; struct FBPUniqueNetId; enum class EBlueprintResultSwitch : uint8; enum class ESteamUserOverlayType : uint8; enum class EBlueprintAsyncResultSwitch : uint8; enum class SteamAvatarSize : uint8; class UTexture2D; #ifdef ADVANCEDSTEAMSESSIONS_AdvancedSteamFriendsLibrary_generated_h #error "AdvancedSteamFriendsLibrary.generated.h already included, missing '#pragma once' in AdvancedSteamFriendsLibrary.h" #endif #define ADVANCEDSTEAMSESSIONS_AdvancedSteamFriendsLibrary_generated_h #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_289_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FBPSteamGroupInfo_Statics; \ ADVANCEDSTEAMSESSIONS_API static class UScriptStruct* StaticStruct(); template<> ADVANCEDSTEAMSESSIONS_API UScriptStruct* StaticStruct<struct FBPSteamGroupInfo>(); #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_SPARSE_DATA #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execGetSteamGroups); \ DECLARE_FUNCTION(execGetSteamFriendGamePlayed); \ DECLARE_FUNCTION(execGetLocalSteamIDFromSteam); \ DECLARE_FUNCTION(execCreateSteamIDFromString); \ DECLARE_FUNCTION(execGetSteamPersonaName); \ DECLARE_FUNCTION(execGetFriendSteamLevel); \ DECLARE_FUNCTION(execOpenSteamUserOverlay); \ DECLARE_FUNCTION(execRequestSteamFriendInfo); \ DECLARE_FUNCTION(execGetSteamFriendAvatar); #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execGetSteamGroups); \ DECLARE_FUNCTION(execGetSteamFriendGamePlayed); \ DECLARE_FUNCTION(execGetLocalSteamIDFromSteam); \ DECLARE_FUNCTION(execCreateSteamIDFromString); \ DECLARE_FUNCTION(execGetSteamPersonaName); \ DECLARE_FUNCTION(execGetFriendSteamLevel); \ DECLARE_FUNCTION(execOpenSteamUserOverlay); \ DECLARE_FUNCTION(execRequestSteamFriendInfo); \ DECLARE_FUNCTION(execGetSteamFriendAvatar); #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUAdvancedSteamFriendsLibrary(); \ friend struct Z_Construct_UClass_UAdvancedSteamFriendsLibrary_Statics; \ public: \ DECLARE_CLASS(UAdvancedSteamFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSteamSessions"), NO_API) \ DECLARE_SERIALIZER(UAdvancedSteamFriendsLibrary) #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_INCLASS \ private: \ static void StaticRegisterNativesUAdvancedSteamFriendsLibrary(); \ friend struct Z_Construct_UClass_UAdvancedSteamFriendsLibrary_Statics; \ public: \ DECLARE_CLASS(UAdvancedSteamFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSteamSessions"), NO_API) \ DECLARE_SERIALIZER(UAdvancedSteamFriendsLibrary) #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UAdvancedSteamFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedSteamFriendsLibrary) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedSteamFriendsLibrary); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedSteamFriendsLibrary); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAdvancedSteamFriendsLibrary(UAdvancedSteamFriendsLibrary&&); \ NO_API UAdvancedSteamFriendsLibrary(const UAdvancedSteamFriendsLibrary&); \ public: #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UAdvancedSteamFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAdvancedSteamFriendsLibrary(UAdvancedSteamFriendsLibrary&&); \ NO_API UAdvancedSteamFriendsLibrary(const UAdvancedSteamFriendsLibrary&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedSteamFriendsLibrary); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedSteamFriendsLibrary); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedSteamFriendsLibrary) #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_PRIVATE_PROPERTY_OFFSET #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_308_PROLOG #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_PRIVATE_PROPERTY_OFFSET \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_SPARSE_DATA \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_RPC_WRAPPERS \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_INCLASS \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_PRIVATE_PROPERTY_OFFSET \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_SPARSE_DATA \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_RPC_WRAPPERS_NO_PURE_DECLS \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_INCLASS_NO_PURE_DECLS \ Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h_311_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> ADVANCEDSTEAMSESSIONS_API UClass* StaticClass<class UAdvancedSteamFriendsLibrary>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Medieval_Mayhem_Plugins_AdvancedSteamSessions_Source_AdvancedSteamSessions_Classes_AdvancedSteamFriendsLibrary_h #define FOREACH_ENUM_ESTEAMUSEROVERLAYTYPE(op) \ op(ESteamUserOverlayType::steamid) \ op(ESteamUserOverlayType::chat) \ op(ESteamUserOverlayType::jointrade) \ op(ESteamUserOverlayType::stats) \ op(ESteamUserOverlayType::achievements) \ op(ESteamUserOverlayType::friendadd) \ op(ESteamUserOverlayType::friendremove) \ op(ESteamUserOverlayType::friendrequestaccept) \ op(ESteamUserOverlayType::friendrequestignore) enum class ESteamUserOverlayType : uint8; template<> ADVANCEDSTEAMSESSIONS_API UEnum* StaticEnum<ESteamUserOverlayType>(); #define FOREACH_ENUM_STEAMAVATARSIZE(op) \ op(SteamAvatarSize::SteamAvatar_INVALID) \ op(SteamAvatarSize::SteamAvatar_Small) \ op(SteamAvatarSize::SteamAvatar_Medium) \ op(SteamAvatarSize::SteamAvatar_Large) enum class SteamAvatarSize : uint8; template<> ADVANCEDSTEAMSESSIONS_API UEnum* StaticEnum<SteamAvatarSize>(); PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "54415208+ScottyO19@users.noreply.github.com" ]
54415208+ScottyO19@users.noreply.github.com
2fcf4dfec4388d48c30237156da6a822da6fed7c
1b81c39f0df3c195eb0aecc47d8675eb2c8a9434
/source code/PathFinder.cpp
ad6f25b13498edfad681c90625ba43da54b21e4a
[]
no_license
Jarcionek/SEG
8d542ebf476f88375d020999c8da6d5bb63205c6
59cdea9bffa5dd67b7baf1edcf97a67bf3d9d0ed
refs/heads/master
2021-05-16T02:44:38.232404
2011-04-03T16:00:00
2012-05-08T17:24:24
4,263,278
0
0
null
null
null
null
UTF-8
C++
false
false
8,044
cpp
/* * File: PathFinder.cpp * Author: Group Papa */ #ifndef PATHFINDER_CPP #define PATHFINDER_CPP #include "PathFinder.h" #include "Constants.cpp" #include "Utilities.cpp" PathFinder::PathFinder(MapSquare **grid) { this->grid = grid; PFgrid = new PathFinderSquare*[WIDTH]; for (int i = 0; i < WIDTH; i++) { PFgrid[i] = new PathFinderSquare[HEIGHT]; for (int j = 0; j < HEIGHT; j++) { PFgrid[i][j] = PathFinderSquare(); } } for(int i = 0; i <= PIXELS_PER_METER; i++) { defValues[i] = (PIXELS_PER_METER + 5 - i) * (PIXELS_PER_METER + 5 - i); } mapExplored = 0; path = std::vector<Point>(); }; PathFinder::~PathFinder() { for (int i = 0; i < WIDTH; i++) { delete PFgrid[i]; } delete PFgrid; }; bool PathFinder::isMapExplored() { return mapExplored; }; bool PathFinder::isStartAccessible() { return PFgrid[WIDTH/2][HEIGHT/2].cost != -1; }; bool PathFinder::isPathValid() { if (path.empty()) { return 0; }; Point p = path.front(); if (grid[p.x][p.y].seen) { return 0; } for (int i = 0; i < path.size(); i++) { p = path.at(i); if (PFgrid[p.x][p.y].margin) { return 0; } } return 1; }; bool PathFinder::isReturnPathValid() { if (path.empty()) { return 0; }; Point p = path.front(); if (p.x != WIDTH / 2 && p.y != HEIGHT / 2) { return 0; }; for (int i = 0; i < path.size(); i++) { p = path.at(i); if (!grid[p.x][p.y].walkable) { return 0; } } return 1; }; void PathFinder::findNewPath(int robx, int roby) { restore(); std::queue<Point> list = std::queue<Point>(); Point target = Point(robx, roby); list.push(target); PFgrid[robx][roby].cost = 0; bool margin = PFgrid[robx][roby].margin; // 0 margins not filled, break at !seen // 1 unwalkable not filled, switch at !margin while (true) { target = list.front(); // if unseen found if (!grid[target.x][target.y].seen) { mapExplored = 0; break; } // if not-margin found, stop searching through the margin if (!PFgrid[target.x][target.y].margin) { margin = 0; } if (margin) { fillWalkableAround(&list, target, -1, 0, 2); fillWalkableAround(&list, target, 1, 0, 2); fillWalkableAround(&list, target, 0, -1, 2); fillWalkableAround(&list, target, 0, 1, 2); fillWalkableAround(&list, target, -1, -1, 3); fillWalkableAround(&list, target, -1, 1, 3); fillWalkableAround(&list, target, 1, -1, 3); fillWalkableAround(&list, target, 1, 1, 3); } else { fillNotMarginAround(&list, target, -1, 0, 2); fillNotMarginAround(&list, target, 1, 0, 2); fillNotMarginAround(&list, target, 0, -1, 2); fillNotMarginAround(&list, target, 0, 1, 2); fillNotMarginAround(&list, target, -1, -1, 3); fillNotMarginAround(&list, target, -1, 1, 3); fillNotMarginAround(&list, target, 1, -1, 3); fillNotMarginAround(&list, target, 1, 1, 3); } list.pop(); if (list.empty()) { mapExplored = 1; break; } } if (mapExplored) { #ifdef PRINT PRINT("MAX EXPLORED"); #endif findReturnPath(robx, roby); } else { choosePath(target, robx, roby); } }; void PathFinder::findReturnPath(int robx, int roby) { restore(); std::queue<Point> list = std::queue<Point>(); Point target = Point(robx, roby); list.push(target); PFgrid[robx][roby].cost = 0; while (true) { target = list.front(); if (target.x == WIDTH / 2 && target.y == HEIGHT / 2) { break; } fillSeenAround(&list, target, -1, 0, 2); fillSeenAround(&list, target, 1, 0, 2); fillSeenAround(&list, target, 0, -1, 2); fillSeenAround(&list, target, 0, 1, 2); fillSeenAround(&list, target, -1, -1, 3); fillSeenAround(&list, target, -1, 1, 3); fillSeenAround(&list, target, 1, -1, 3); fillSeenAround(&list, target, 1, 1, 3); list.pop(); if (list.empty()) { break; } } if (isStartAccessible()) { choosePath(Point(WIDTH / 2, HEIGHT / 2), robx, roby); #ifdef PRINT PRINT("RETURN PATH FOUND"); #endif } }; std::vector<Point> *PathFinder::getPath() { return &path; }; PathFinderSquare **PathFinder::getGrid() { return PFgrid; }; void PathFinder::setWallDetectedAt(int x, int y) { // set margin checkMap(x, y, MARGIN_PX + WALLS_BOLDING_PX); for (int a = -(MARGIN_PX + WALLS_BOLDING_PX); a <= (MARGIN_PX + WALLS_BOLDING_PX); a++) { for (int b = -(MARGIN_PX + WALLS_BOLDING_PX); b <= (MARGIN_PX + WALLS_BOLDING_PX); b++) { PFgrid[x + a][y + b].margin = 1; } } // set penalty checkMap(x, y, PENALTY_DIST_PX); for (int a = -PENALTY_DIST_PX; a <= PENALTY_DIST_PX; a++) { for (int b = -PENALTY_DIST_PX; b <= PENALTY_DIST_PX; b++) { int k = abs(a) > abs(b)? abs(a) : abs(b); if (PFgrid[x + a][y + b].penalty < defValues[k]) { PFgrid[x + a][y + b].penalty = defValues[k]; } } } }; int PathFinder::getBiggestPenalty() { return defValues[0]; }; void PathFinder::restore() { for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { PFgrid[i][j].cost = -1; } } }; void PathFinder::choosePath(Point target, int robx, int roby) { path.clear(); Point current = Point(target.x, target.y); while (current.x != robx || current.y != roby) { path.push_back(Point(current.x, current.y)); int nx = current.x; int ny = current.y; // find adjacent square with the lowest cost for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (PFgrid[current.x + i][current.y + j].cost != -1 && PFgrid[current.x + i][current.y + j].cost < PFgrid[nx][ny].cost) { nx = current.x + i; ny = current.y + j; } } } if (nx == current.x && ny == current.y) { /* * This may be invoked only while choosing as a target a point * which not necessarily has a cost set. It may occur only * in finding return path, so ensure that start point is accessible * after setting costs and before calling this method. */ std::cerr << "ERROR - TARGET IS INACCESSIBLE" << std::endl; break; } current.x = nx; current.y = ny; } }; void PathFinder::fillNotMarginAround(std::queue<Point> *list, Point p, int xm, int ym, int cost) { if (!PFgrid[p.x + xm][p.y + ym].margin) { fill(list, p, xm, ym, cost); } }; void PathFinder::fillWalkableAround(std::queue<Point> *list, Point p, int xm, int ym, int cost) { if (grid[p.x + xm][p.y + ym].walkable) { fill(list, p, xm, ym, cost); } }; void PathFinder::fillSeenAround(std::queue<Point> *list, Point p, int xm, int ym, int cost) { if (grid[p.x + xm][p.y + ym].seen && grid[p.x + xm][p.y + ym].walkable) { fill(list, p, xm, ym, cost); } }; void PathFinder::fill(std::queue<Point> *list, Point p, int xm, int ym, int cost) { PathFinderSquare *current = &PFgrid[p.x][p.y]; PathFinderSquare *adjacent = &PFgrid[p.x + xm][p.y + ym]; if (adjacent->cost == -1 || adjacent->cost > current->cost + adjacent->penalty + cost) { adjacent->cost = current->cost + adjacent->penalty + cost; list->push(Point(p.x + xm, p.y + ym)); } }; #endif /* PATHFINDER_CPP */
[ "jarcionek@users.noreply.github.com" ]
jarcionek@users.noreply.github.com
9e1b9a32872e7bea297e7a2315c7186dd39a72a0
391b46772c6a7d0779d85fcbe3f15b76f5201619
/CppExamples/CppExamples/10_24_25/Example36_10_24_25.cpp
5bf22d0e813867d3c6786379b393a86973976a4e
[]
no_license
cicekozkan/CppExamples
b750775cccb73b6880152ef4f04b659389e7d910
05a8adf902a7e5b02d5f75aab56e7cf33e4601ae
refs/heads/master
2021-01-20T10:30:37.773845
2016-02-10T15:52:50
2016-02-10T15:52:50
37,305,590
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
// std::basic_ostream::put // basic_ostream& put( char_type ch ); // Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, writes the character ch to the output stream. // If the output fails for any reason, sets badbit. #include <iostream> using namespace std; int main() { char ch = 65; cout << ch << endl; cout.put(ch); return 0; }
[ "ozkan.cicek@analog.com" ]
ozkan.cicek@analog.com
87404cc9c3c1c7f16e4f798d246cffe6c094726a
0897560a7ebde50481f950c9a441e2fc3c34ba04
/10.0.15042.0/winrt/internal/Windows.ApplicationModel.Wallet.System.3.h
f265e658b43599490f4a164a2478348653fe2ea0
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
dngoins/cppwinrt
338f01171153cbca14a723217129ed36b6ce2c9d
0bb7a57392673f793ba99978738490100a9684ec
refs/heads/master
2021-01-19T19:14:59.993078
2017-03-01T22:14:18
2017-03-01T22:14:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
757
h
// C++ for the Windows Runtime v1.0.private // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.ApplicationModel.Wallet.System.2.h" WINRT_EXPORT namespace winrt { namespace Windows::ApplicationModel::Wallet::System { struct WINRT_EBO WalletItemSystemStore : Windows::ApplicationModel::Wallet::System::IWalletItemSystemStore, impl::require<WalletItemSystemStore, Windows::ApplicationModel::Wallet::System::IWalletItemSystemStore2> { WalletItemSystemStore(std::nullptr_t) noexcept {} }; struct WalletManagerSystem { WalletManagerSystem() = delete; static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Wallet::System::WalletItemSystemStore> RequestStoreAsync(); }; } }
[ "kwelton@microsoft.com" ]
kwelton@microsoft.com
548d9a3e09f7b03b7f063a95217bcb4261bbf416
89b4d54389227c6d58bf05f9b48454bd5a0f2e48
/Module3/Algr_DZ3_1/CSetGraph.cpp
21258bdd4d0ba88d031b8e25e1d2eb8e9aa0e2a9
[]
no_license
ShelbyKS/AlgorithmsTP
4ec47877623cdd825636980a5a6d7786140a0318
f554d42b457ddbca84e1678665058548c9785d1f
refs/heads/master
2023-05-31T03:40:10.809874
2018-12-25T14:06:57
2018-12-25T14:06:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,352
cpp
// // Created by liza_shch on 14.12.18. // #include "CSetGraph.h" CSetGraph::CSetGraph(const IGraph *other): CSetGraph(other->VerticesCount()) { for (int i = 0; i < VerticesCount(); i++) { std::vector<int> nextVertices = other->GetNextVertices(i); for (auto vertex : nextVertices) { adjacencyHashTablesFromTo[i].Add(vertex); adjacencyHashTablesToFrom[vertex].Add(i); } } } bool CSetGraph::isValid(int index) const { return (index >= 0 && index < VerticesCount()); } void CSetGraph::AddEdge(int from, int to) { assert(isValid(from)); assert(isValid(to)); adjacencyHashTablesFromTo[from].Add(to); adjacencyHashTablesToFrom[to].Add(from); } std::vector<int> CSetGraph::GetNextVertices(int vertex) const { assert(isValid(vertex)); std::vector<int> nextVertices; for (int i = 0; i < VerticesCount(); i++) { if (adjacencyHashTablesFromTo[vertex].Has(i)) { nextVertices.push_back(i); } } return nextVertices; } std::vector<int> CSetGraph::GetPrevVertices(int vertex) const { assert(isValid(vertex)); std::vector<int> prevVertices; for (int i = 0; i < VerticesCount(); i++) { if (adjacencyHashTablesToFrom[vertex].Has(i)) { prevVertices.push_back(i); } } return prevVertices; }
[ "scherbakova.liz@yandex.ru" ]
scherbakova.liz@yandex.ru
89a71704975153e783b6182c9232a98eeebac606
cffc460605febc80e8bb7c417266bde1bd1988eb
/before2020/UVa_ACM/104 - Volume CIV/UVa 10405(2.5, DP, LCS, fast-IO).cpp
b03d5b47d1a2a46dbab967276f27cdaea7950122
[]
no_license
m80126colin/Judge
f79b2077f2bf67a3b176d073fcdf68a8583d5a2c
56258ea977733e992b11f9e0cb74d630799ba274
refs/heads/master
2021-06-11T04:25:27.786735
2020-05-21T08:55:03
2020-05-21T08:55:03
19,424,030
7
4
null
null
null
null
UTF-8
C++
false
false
685
cpp
/** * @judge UVa * @id 10405 * @tag 2.5, DP, LCS, fast IO */ #include <cstdio> #include <cstring> #include <iostream> using namespace std; #define MAX 1010 #define HASH(x) ((x) & 1) char s1[MAX], s2[MAX]; int dp[2][MAX], len1, len2; int LCS() { int i, j; memset(dp, 0, sizeof(dp)); for (i = 1; i <= len1; i++) for (j = 1; j <= len2; j++) if (s1[i] == s2[j]) dp[HASH(i)][j] = dp[HASH(i - 1)][j - 1] + 1; else dp[HASH(i)][j] = max(dp[HASH(i - 1)][j], dp[HASH(i)][j - 1]); return dp[HASH(len1)][len2]; } int main() { while (gets(s1 + 1) && gets(s2 + 1)) { len1 = strlen(s1 + 1); len2 = strlen(s2 + 1); printf("%d\n", LCS()); } }
[ "m80126colin@gmail.com" ]
m80126colin@gmail.com
d7ae46a563cfdba6598a7ea89bc7cc1db81186ec
8becf845df66d6be7e80ec74afddd860a1e8b248
/http.h
2ce159503d2fec67eb2e3add2ba7fd291e54e549
[]
no_license
shawcm/toy-web-server
31f511a1ea6b524ce83a47b32062c10655f1f8bc
4c287efe25f209d1b4da329b636a0043cc20689b
refs/heads/master
2023-04-29T07:22:23.543625
2021-05-13T07:23:42
2021-05-13T07:23:42
366,968,794
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
h
#ifndef HTTP_H #define HTTP_H #include "util.h" struct HttpHeader; struct HttpRequest; enum HttpMethod { GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH }; enum HttpStatus { OK = 200, MovedPermanently = 301, BadRequest = 400, NotFound = 404, RequestTimeout = 408 // and lots of others, to be added }; const char* httpStatusToString (HttpStatus s); // the header fields of a HTTP request struct HttpHeader { // constructor: a buffer location, buffer size HttpHeader(); HttpHeader(char *buf, ssize_t len); // write header to a buffer void dump(char *&buf, ssize_t len); string A_IM; string Accept; string Accept_Charset; string Accept_Datetime; string Accept_Encoding; string Accept_Language; string Access_Control_Request_Method; string Access_Control_Request_Headers; string Authorization; string Cache_Control; string Connection; string Content_Encoding; string Content_Length; string Content_MD5; string Content_Type; string Cookie; string Date; string Expect; string Forwarded; string From; string Host; string HTTP2_Settings; string If_Match; string If_Modified_Since; string If_None_Match; string If_Range; string If_Unmodified_Since; string Max_Forwards; string Origin; string Pragma; string Prefer; string Proxy_Authorization; string Range; string Referer; string TE; string Trailer; string Transfer_Encoding; string User_Agent; string Upgrade; string Via; string Warning; }; struct HttpRequest { typedef std::shared_ptr<HttpRequest> Ptr; HttpMethod method; // GET string location; // /index.html string version; // HTTP/1.1 HttpHeader header; // heads.. const char *content; // content buffer ssize_t content_len_; // construct the struct from buffer HttpRequest(); HttpRequest(const char *buf, ssize_t len); void construct(const char *buf, ssize_t len); }; enum HttpRequestProgressBuildState { READ_INIT, READ_BEGIN, READ_LENGTH, READ_CONTENT, READ_FINISH }; struct HttpRequestProgressBuilder { typedef std::shared_ptr<HttpRequestProgressBuilder> Ptr; HttpRequestProgressBuildState state; char *buf; const char *skip; HttpMethod method; ssize_t current_len; ssize_t content_len; ssize_t current_content_len; ssize_t sequence_r_r; bool prev_is_r_n; HttpRequestProgressBuilder(char *buf); int progress(ssize_t len); void reset(); }; struct HttpResponse { typedef std::shared_ptr<HttpResponse> Ptr; string version; HttpStatus status; HttpHeader header; char *content; ssize_t content_len_; //HttpResponse(char *buf, ssize_t len); ///?no use // write response to a buffer ssize_t dump(char *buf, ssize_t len); }; #endif
[ "comynshaw@gmail.com" ]
comynshaw@gmail.com
cc33127355b0bc244575378b80ef7d8cc31df8a3
7dc53606032bd907765cccc88245c0efd3e495cb
/tests/lazy/dot/transform.hpp
9c7554d5c07702db4ddb64a47a3ef28a89226d9c
[]
no_license
nerikhman/cusend
c8a1b2fd3fd428d492c6a682d40c0596214010a5
0c797af1a462a357af78df954d4aaf64fc038878
refs/heads/master
2022-11-19T20:01:37.025920
2020-07-17T22:12:30
2020-07-17T22:12:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,892
hpp
#include <cassert> #include <cstring> #include <cusend/execution/executor/inline_executor.hpp> #include <cusend/lazy/combinator/just.hpp> #include <cusend/lazy/dot/transform.hpp> namespace ns = cusend; #ifndef __host__ #define __host__ #define __device__ #define __managed__ #define __global__ #endif __managed__ int result; template<class Function> class move_only_function { public: __host__ __device__ move_only_function(Function f) : f_(f) {} move_only_function(const move_only_function&) = delete; move_only_function(move_only_function&&) = default; __host__ __device__ int operator()(int arg) const { return f_(arg); } private: Function f_; }; template<class Function> __host__ __device__ move_only_function<Function> make_move_only_function(Function f) { return {f}; } struct my_receiver { __host__ __device__ void set_value(int value) { result = value; } void set_error(std::exception_ptr) {} __host__ __device__ void set_done() noexcept {} }; __host__ __device__ void test_is_typed_sender() { using namespace ns; { auto result = dot::transform(just(), [] { return; }); static_assert(is_typed_sender<decltype(result)>::value, "Error."); } { auto result = dot::transform(just(), [] { return 13; }); static_assert(is_typed_sender<decltype(result)>::value, "Error."); } { auto result = dot::transform(just(13), [](int arg) { return arg; }); static_assert(is_typed_sender<decltype(result)>::value, "Error."); } { auto result = dot::transform(just(13,7), [](int arg1, int arg2) { return arg1 + arg2; }); static_assert(is_typed_sender<decltype(result)>::value, "Error."); } } template<class S> __host__ __device__ constexpr bool is_chaining(const S&) { return false; } template<class S> __host__ __device__ constexpr bool is_chaining(const ns::chaining_sender<S>&) { return true; } __host__ __device__ void test_is_chaining() { using namespace ns; { auto result = dot::transform(just(), [] { return; }); static_assert(is_chaining(result), "Error."); } { auto result = dot::transform(just(), [] { return 13; }); static_assert(is_chaining(result), "Error."); } { auto result = dot::transform(just(13), [](int arg) { return arg; }); static_assert(is_chaining(result), "Error."); } { auto result = dot::transform(just(13,7), [](int arg1, int arg2) { return arg1 + arg2; }); static_assert(is_chaining(result), "Error."); } } __host__ __device__ void test_copyable_continuation() { using namespace ns; result = 0; int arg1 = 13; int arg2 = 7; int expected = arg1 + arg2; my_receiver r; dot::transform(just(arg1), [=] (int arg1) { return arg1 + arg2; }).connect(std::move(r)).start(); assert(expected == result); } __host__ __device__ void test_move_only_continuation() { using namespace ns; result = 0; int arg1 = 13; int arg2 = 7; int expected = arg1 + arg2; my_receiver r; auto continuation = make_move_only_function([=] (int arg1) { return arg1 + arg2; }); dot::transform(just(arg1), std::move(continuation)).connect(std::move(r)).start(); assert(expected == result); } struct my_sender_with_transform_member_function { int arg; template<class Function> __host__ __device__ auto transform(Function continuation) && -> decltype(ns::dot::transform(ns::just(arg), continuation)) { return ns::dot::transform(ns::just(arg), continuation); } }; __host__ __device__ void test_sender_with_transform_member_function() { result = 0; int arg1 = 13; int arg2 = 7; int expected = arg1 + arg2; my_receiver r; my_sender_with_transform_member_function s{arg1}; ns::dot::transform(std::move(s), [=](int arg1) {return arg1 + arg2;}).connect(std::move(r)).start(); assert(expected == result); } struct my_sender_with_transform_free_function { int arg; }; template<class Function> __host__ __device__ auto transform(my_sender_with_transform_free_function&& s, Function continuation) -> decltype(ns::dot::transform(ns::just(s.arg), continuation)) { return ns::dot::transform(ns::just(s.arg), continuation); } __host__ __device__ void test_sender_with_transform_free_function() { result = 0; int arg1 = 13; int arg2 = 7; int expected = arg1 + arg2; my_receiver r; my_sender_with_transform_member_function s{arg1}; ns::dot::transform(std::move(s), [=](int arg1) {return arg1 + arg2;}).connect(std::move(r)).start(); assert(expected == result); } template<class F> __global__ void device_invoke_kernel(F f) { f(); } template<class F> __host__ __device__ void device_invoke(F f) { #if defined(__CUDACC__) #if !defined(__CUDA_ARCH__) // __host__ path device_invoke_kernel<<<1,1>>>(f); #else // __device__ path // workaround restriction on parameters with copy ctors passed to triple chevrons void* ptr_to_arg = cudaGetParameterBuffer(std::alignment_of<F>::value, sizeof(F)); std::memcpy(ptr_to_arg, &f, sizeof(F)); // launch the kernel if(cudaLaunchDevice(&device_invoke_kernel<F>, ptr_to_arg, dim3(1), dim3(1), 0, 0) != cudaSuccess) { assert(0); } #endif assert(cudaDeviceSynchronize() == cudaSuccess); #else // device invocations are not supported assert(0); #endif } void test_transform() { test_is_typed_sender(); test_is_chaining(); test_copyable_continuation(); test_move_only_continuation(); test_sender_with_transform_member_function(); test_sender_with_transform_free_function(); #ifdef __CUDACC__ device_invoke([] __device__ () { test_is_typed_sender(); test_is_chaining(); test_copyable_continuation(); test_move_only_continuation(); test_sender_with_transform_member_function(); test_sender_with_transform_free_function(); }); assert(cudaDeviceSynchronize() == cudaSuccess); #endif }
[ "jaredhoberock@gmail.com" ]
jaredhoberock@gmail.com
40d1f188f4a058e8e378ceff1118b5c3bc137ef4
dfa8ef7faf2c330b389e9b3435b5bdfbe1a08d68
/src/processor/reorder_buffer_line.cpp
dede9c9837687fd1a05cb03f36697e299356ab69
[]
no_license
gotojump/Simulator
f010f2a682c9dc73aa16acc19bd0d228011da79b
b6c59ade6b3eea53e446aea1a4bd244ce8f13e5d
refs/heads/master
2020-04-09T00:24:24.640087
2018-12-03T13:52:47
2018-12-03T13:52:47
159,865,266
0
0
null
null
null
null
UTF-8
C++
false
false
6,493
cpp
/* * Copyright (C) 2010~2014 Marco Antonio Zanata Alves * (mazalves at inf.ufrgs.br) * GPPD - Parallel and Distributed Processing Group * Universidade Federal do Rio Grande do Sul * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "simulator.hpp" #include <string> // ========================================================================== // reorder_buffer_line_t::reorder_buffer_line_t() { this->package_clean(); this->reg_deps_ptr_array = NULL; }; // -------------------------------------------------------------------------- // reorder_buffer_line_t::~reorder_buffer_line_t() { utils_t::template_delete_array<reorder_buffer_line_t*>(reg_deps_ptr_array); }; // -------------------------------------------------------------------------- // bool reorder_buffer_line_t::operator==(const reorder_buffer_line_t& reorder_buffer_line){ // cmp uop if(this->uop==reorder_buffer_line.uop) return FAIL; // uOP stored // cmp entry stafge if(this->stage !=reorder_buffer_line.stage) return FAIL; // wait Register Dependencies Control if(this->wait_reg_deps_number !=reorder_buffer_line.wait_reg_deps_number) return FAIL; //cmp reg deps array if(memcmp(this->reg_deps_ptr_array,reorder_buffer_line.reg_deps_ptr_array,sizeof(reorder_buffer_line_t)*ROB_SIZE)!=0) return FAIL; //cmp counter wake up if(this->wake_up_elements_counter !=reorder_buffer_line.wake_up_elements_counter) return FAIL; //cmp mob pointer if(memcmp(this->mob_ptr,reorder_buffer_line.mob_ptr,sizeof(memory_order_buffer_line_t))!=0) return FAIL; if(this->on_chain !=reorder_buffer_line.on_chain) return FAIL; if(this->is_poisoned !=reorder_buffer_line.is_poisoned) return FAIL; if(this->original_miss !=reorder_buffer_line.original_miss) return FAIL; if(this->emc_executed !=reorder_buffer_line.emc_executed) return FAIL; return OK; }; // -------------------------------------------------------------------------- // void reorder_buffer_line_t::package_clean() { this->uop.package_clean(); this->stage = PROCESSOR_STAGE_DECODE; this->mob_ptr = NULL; this->wait_reg_deps_number = 0; this->wake_up_elements_counter = 0; this->on_chain = false; this->is_poisoned = false; this->original_miss = false; this->emc_executed = false; this->op_on_emc_buffer = 0; }; // -------------------------------------------------------------------------- // std::string reorder_buffer_line_t::content_to_string() { std::string content_string; content_string = ""; #ifndef SHOW_FREE_PACKAGE if (this->uop.status == PACKAGE_STATE_FREE) { return content_string; } #endif content_string = this->uop.content_to_string(); content_string = content_string + " | Stage:" + get_enum_processor_stage_char(this->stage); content_string = content_string + " | Reg.Wait:" + utils_t::uint32_to_string(this->wait_reg_deps_number); content_string = content_string + " | Op_On_EMC_B.:" + utils_t::uint32_to_string(this->op_on_emc_buffer); content_string = content_string + " | WakeUp:" + utils_t::uint32_to_string(this->wake_up_elements_counter); content_string = content_string + " | ReadyAt: " + utils_t::uint64_to_string(this->uop.readyAt); content_string = content_string + " | On Dep Chain: " + utils_t::bool_to_string(this->on_chain); content_string = content_string + " | Poisoned: " + utils_t::bool_to_string(this->is_poisoned); content_string = content_string + " | Executed on EMC: " + utils_t::bool_to_string(this->emc_executed); if(this->mob_ptr != NULL){ content_string = content_string + this->mob_ptr->content_to_string(); } return content_string; }; // -------------------------------------------------------------------------- // std::string reorder_buffer_line_t::content_to_string2() { std::string content_string; content_string = ""; #ifndef SHOW_FREE_PACKAGE if(this->uop.status == PACKAGE_STATE_FREE) { return content_string; } #endif content_string = this->uop.content_to_string(); content_string = content_string + " | Stage:" + get_enum_processor_stage_char(this->stage); content_string = content_string + " | Reg.Wait:" + utils_t::uint32_to_string(this->wait_reg_deps_number); content_string = content_string + " | WakeUp:" + utils_t::uint32_to_string(this->wake_up_elements_counter); content_string = content_string + " | ReadyAt: " + utils_t::uint64_to_string(this->uop.readyAt); content_string = content_string + " | On Dep Chain: " + utils_t::bool_to_string(this->on_chain); return content_string; }; // -------------------------------------------------------------------------- // void reorder_buffer_line_t::print_dependences(){ for(uint16_t i=0;i<ROB_SIZE;i++){ if(this->reg_deps_ptr_array[i] == NULL)break; ORCS_PRINTF("%s\n",this->reg_deps_ptr_array[i]->content_to_string().c_str()) } }; // -------------------------------------------------------------------------- // // STATIC METHODS std::string reorder_buffer_line_t::print_all(reorder_buffer_line_t *input_array, uint32_t size_array) { std::string content_string; std::string final_string; final_string = ""; for (uint32_t i = 0; i < size_array ; i++) { content_string = ""; content_string = input_array[i].content_to_string(); if (content_string.size() > 1) { final_string = final_string + "[" + utils_t::uint32_to_string(i) + "] " + content_string + "\n"; } } return final_string; }; // -------------------------------------------------------------------------- // // Generate Dep Chains to EMC void reorder_buffer_line_t::get_deps(std::vector<reorder_buffer_line_t> *buffer){ if(this->wake_up_elements_counter>0){ for(size_t i = 0; i < ROB_SIZE; i++){ if(this->reg_deps_ptr_array[i]!=NULL){ buffer->push_back(*this->reg_deps_ptr_array[i]); } else{ break; } } } }; // ========================================================================== //
[ "ericlowsez@gmail.com" ]
ericlowsez@gmail.com
4d128aae6aac59fc5c8fd56766986ca2c25f5b35
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/tao/PolicyFactory_Registry_Factory.cpp
3ba5530238293e65f74cd4fd815436737feb1bfa
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
202
cpp
#include "tao/PolicyFactory_Registry_Factory.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_PolicyFactory_Registry_Factory::~TAO_PolicyFactory_Registry_Factory (void) { } TAO_END_VERSIONED_NAMESPACE_DECL
[ "lihuibin705@163.com" ]
lihuibin705@163.com
7b74da857b0e37e148dae978d24c0350fa42cb2c
e77f804d0ec11516b6eec1f1fa1049deac2bccbd
/src/uArm/UF_uArm_Metal-master/UF_uArm_Metal.h
b19eb0d131fdde145b494e82bebfad8e3998451c
[]
no_license
gitter-badger/Robot_Group
cef63132c936ef9b61028d16fbd14897c70745f7
701cac0e48168f5378e967f9010ed69e171b324d
refs/heads/master
2021-01-18T06:24:51.222878
2016-05-28T05:37:13
2016-05-28T05:37:13
59,935,391
1
1
null
2016-05-29T09:21:04
2016-05-29T09:21:04
null
UTF-8
C++
false
false
5,159
h
/****************************************************************************** * File Name : UF_uArm.h * Author : Evan * Updated : Evan * Version : V0.0.3 (BATE) * Created Date : 12 Dec, 2014 * Modified Date : 17 Jan, 2015 * Description : * License : * Copyright(C) 2014 UFactory Team. All right reserved. ******************************************************************************* * Updated : Alex * Date : 04 Mar, 2015 * Version : V0.0.2 * Description : CtrlData 0x80 for RESET *************************************************************************/ #include <Arduino.h> #include <EEPROM.h> #include "VarSpeedServo.h" #ifndef UF_uArm_Metal_h #define UF_uArm_Metal_h /**************** Macro definitions ****************/ #define ARM_A 148 // upper arm #define ARM_B 160 // lower arm #define ARM_2AB 47360 // 2*A*B #define ARM_A2 21904 // A^2 #define ARM_B2 25600 // B^2 #define ARM_A2B2 47504 // A^2 + B^2 #define ARM_STRETCH_MIN 0 #define ARM_STRETCH_MAX 195 #define ARM_HEIGHT_MIN -150 #define ARM_HEIGHT_MAX 160 #define ARM_ROTATION_MIN -90 #define ARM_ROTATION_MAX 90 #define HAND_ROTATION_MIN -90 #define HAND_ROTATION_MAX 90 #define HAND_ANGLE_OPEN 25 #define HAND_ANGLE_CLOSE 70 #define FIXED_OFFSET_L 25 #define FIXED_OFFSET_R 42 #define D090M_SERVO_MIN_PUL 500 #define D090M_SERVO_MAX_PUL 2500 #define D009A_SERVO_MIN_PUL 600 #define D009A_SERVO_MAX_PUL 2550 #define SAMPLING_DEADZONE 2 #define INIT_POS_L 145//37 // the angle of calibration position (initial angle) #define INIT_POS_R 68//25 // the angle of calibration position (initial angle) #define BTN_TIMEOUT_1000 1000 #define BTN_TIMEOUT_3000 3000 #define CATCH 0x01 #define RELEASE 0x02 #define RESET 0x80 #define CALIBRATION_FLAG 0xEE #define SERVO_MAX 635 #define SERVO_MIN 72 #define MEMORY_SERVO_PER 335 // eeprom: (1024 - 3 - 14)/3=335 #define DATA_FLAG 255 #define BUFFER_OUTPUT 5 /***************** Port definitions *****************/ #define BTN_D4 4 // #define BTN_D7 7 // #define BUZZER 3 // #define LIMIT_SW 2 // Limit Switch #define PUMP_EN 6 // #define VALVE_EN 5 // #define SERVO_HAND 9 // #define SERVO_HAND_ROT 10 // #define SERVO_ROT 11 // #define SERVO_R 12 // #define SERVO_L 13 // class UF_uArm { public: UF_uArm(); void init(); // initialize the uArm position void calibration(); // void recordingMode(unsigned char _sampleDelay = 50); void setPosition(double _stretch, double _height, int _armRot, int _handRot); // void setServoSpeed(char _servoNum, unsigned char _servoSpeed); // 0=full speed, 1-255 slower to faster int readAngle(char _servoNum); void gripperCatch(); // void gripperRelease(); // void gripperDetach(); // void gripperDirectDetach(); // void pumpOn(); // pump enable void pumpOff(); // pump disnable void valveOn(); // valve enable, decompression void valveOff(); // valve disnable void detachServo(char _servoNum); void sendData(byte _dataAdd, int _dataIn); // void alert(int _times, int _runTime, int _stopTime); void writeEEPROM(); void readEEPROM(); void play(unsigned char buttonPin); void record(unsigned char buttonPin, unsigned char buttonPinC); void servoBufOutL(unsigned char _lastDt, unsigned char _dt); void servoBufOutR(unsigned char _lastDt, unsigned char _dt); void servoBufOutRot(unsigned char _lastDt, unsigned char _dt); private: /******************* Servo offset *******************/ char offsetL; char offsetR; /***************** Define variables *****************/ int heightLst; int height; int stretch; int rotation; int handRot; boolean playFlag; boolean recordFlag; boolean firstFlag; boolean gripperRst; unsigned char sampleDelay; unsigned char servoSpdR; unsigned char servoSpdL; unsigned char servoSpdRot; unsigned char servoSpdHand; unsigned char servoSpdHandRot; unsigned char leftServoLast; unsigned char rightServoLast; unsigned char rotServoLast; unsigned char griperState[14]; unsigned char data[3][MEMORY_SERVO_PER+1]; // 0: L 1: R 2: Rotation unsigned long delay_loop; unsigned long lstTime; //limit: 50days /*************** Create servo objects ***************/ VarSpeedServo servoR; VarSpeedServo servoL; VarSpeedServo servoRot; VarSpeedServo servoHand; VarSpeedServo servoHandRot; }; #endif
[ "13667693152@163.com" ]
13667693152@163.com
bdef538ae56f26aa03b9dd5cad26cc4927541c96
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/fiber/test/test_barrier_post.cpp
ebba98de26747077392603a0e737ed2bb08a6e7d
[ "BSL-1.0" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
1,589
cpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // This test is based on the tests of Boost.Thread #include <sstream> #include <string> #include <boost/test/unit_test.hpp> #include <boost/fiber/all.hpp> int value1 = 0; int value2 = 0; void fn1( boost::fibers::barrier & b) { ++value1; boost::this_fiber::yield(); b.wait(); ++value1; boost::this_fiber::yield(); ++value1; boost::this_fiber::yield(); ++value1; boost::this_fiber::yield(); ++value1; } void fn2( boost::fibers::barrier & b) { ++value2; boost::this_fiber::yield(); ++value2; boost::this_fiber::yield(); ++value2; boost::this_fiber::yield(); b.wait(); ++value2; boost::this_fiber::yield(); ++value2; } void test_barrier() { value1 = 0; value2 = 0; boost::fibers::barrier b( 2); boost::fibers::fiber f1( boost::fibers::launch::post, fn1, std::ref( b) ); boost::fibers::fiber f2( boost::fibers::launch::post, fn2, std::ref( b) ); f1.join(); f2.join(); BOOST_CHECK_EQUAL( 5, value1); BOOST_CHECK_EQUAL( 5, value2); } boost::unit_test::test_suite * init_unit_test_suite( int, char* []) { boost::unit_test::test_suite * test = BOOST_TEST_SUITE("Boost.Fiber: barrier test suite"); test->add( BOOST_TEST_CASE( & test_barrier) ); return test; }
[ "james.pack@stardog.com" ]
james.pack@stardog.com
a8114af3a6df726244bf74d2f29738f75bfd1926
dde014c37394cc0c7135a6d6f6fbbd7e70e24d74
/fizika/KPIYAP(3 sem)/Лабораторная работа №3/Shape/Shape/Cylinder.h
96229533034572daaca645e313b69e9360c54837
[]
no_license
andrushkin2/university
d7b502fafc548788c7f70beaa888d865b983aaa8
53466464e835827ffbaceaab6599aa3b5deecbd6
refs/heads/master
2020-05-21T12:21:55.201518
2019-04-09T10:19:46
2019-04-09T10:19:46
32,348,978
1
3
null
null
null
null
UTF-8
C++
false
false
411
h
#ifndef _CYLINDER_H_ #define _CYLINDER_H_ #include"ThreeDShape.h" class Cylinder : public ThreeDShape { private: int height; public: Cylinder(int _radius = 0,int _height = 0); ~Cylinder(); //inline int GetRadius() { return this->radius; }; inline int GetHeight() { return this->height; }; //void Set(int _radius,int _height); double Volume(); double Area(); void Input(); }; #endif
[ "andrushkin2@live.ru" ]
andrushkin2@live.ru
a33af1c144b20bbd49dc3eb4c504bdbe6ed0320a
a1fbf16243026331187b6df903ed4f69e5e8c110
/cs/sdk/include/boost/date_time/locale_config.hpp
6b79f83a1816d88cd3a6b3fa013ff96e9a65c2bc
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
OpenXRay/xray-15
ca0031cf1893616e0c9795c670d5d9f57ca9beff
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
refs/heads/xd_dev
2023-07-17T23:42:14.693841
2021-09-01T23:25:34
2021-09-01T23:25:34
23,224,089
64
23
NOASSERTION
2019-04-03T17:50:18
2014-08-22T12:09:41
C++
UTF-8
C++
false
false
1,375
hpp
#ifndef DATE_TIME_LOCALE_CONFIG_HPP___ #define DATE_TIME_LOCALE_CONFIG_HPP____ /* Copyright (c) 2002 CrystalClear Software, Inc. * Disclaimer & Full Copyright at end of file * Author: Jeff Garland */ // This file configures whether the library will support locales and hence // iostream based i/o. Even if a compiler has some support for locales, // any failure to be compatible gets the compiler on the exclusion list. // // At the moment this is defined for MSVC 6 and any compiler that // defines BOOST_NO_STD_LOCALE (gcc 2.95.x) #include "boost/config.hpp" //sets BOOST_NO_STD_LOCALE //This file basically becomes a noop if locales are not properly supported #if (defined(BOOST_NO_STD_LOCALE) || (defined(BOOST_MSVC) && (_MSC_VER <= 1200)) || (defined(__BORLANDC__))) #define BOOST_DATE_TIME_NO_LOCALE #endif /* Copyright (c) 2002 * CrystalClear Software, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. CrystalClear Software makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ #endif
[ "paul-kv@yandex.ru" ]
paul-kv@yandex.ru
3dda096d0ad61e4a788da39e92f344ae8ea9bb6b
fddf5a1807a9eac2193819091e0382a4044c2657
/generateRandomNumbers.cpp
d2b2ab28ccb398a418a9ef1ad8df381718e0d69d
[]
no_license
Vaklic/iotGeneratorGui
218327ba2d174128d9f2c1fa1c8dcfb722762d16
4d548130632939e03bf1bf1235a66e0720b0c679
refs/heads/master
2021-06-25T09:38:47.630277
2017-09-09T09:56:40
2017-09-09T09:56:40
100,522,050
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include "library.hpp" uint8_t generateRandomUInt8(uint8_t lowBorder, uint8_t highBorder){ return (uint8_t)(lowBorder + rand() % highBorder); } uint16_t generateRandomUInt16(uint16_t lowBorder, uint16_t highBorder){ return (uint16_t)(lowBorder + rand() % highBorder); } double generateRandomDouble(double lowBorder, double highBorder){ double f = (double)rand() / RAND_MAX; return (lowBorder + f * (highBorder - lowBorder)); } char generateRandomChar(void){ return 0x40 + (char)rand()%16; } uint32_t generateRandomUInt32(uint32_t lowBorder, uint32_t highBorder){ return (uint32_t)(lowBorder + rand() % highBorder); } uint64_t generateRandomUInt64(uint64_t lowBorder, uint64_t highBorder){ return (uint64_t)(lowBorder + rand() % highBorder); }
[ "vaklicr@gmail.com" ]
vaklicr@gmail.com
2bd8281761f45fa6694be81dc393522c6cde0a95
6dded22cdba148e01b2eebc73f3941dc9e2bd050
/125.ValidPalindrome/ValidPalindrome.cc
adc4c283638288565f9ade96ee3254c7df07f836
[ "MIT" ]
permissive
stdbilly/leetcode
271f7e8f89d2ee9f4754a271a448486893f04aca
752704ff99c21863bde4c929b7cc4fa18128cf39
refs/heads/master
2020-07-02T19:36:56.153275
2019-09-22T10:44:13
2019-09-22T10:44:13
201,641,271
0
0
null
null
null
null
UTF-8
C++
false
false
960
cc
#include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Solution { public: bool isPalindrome(string s) { int l = nextAlnum(s, 0); int r = preAlnum(s, s.size() - 1); while (l <= r) { if (tolower(s[l]) != tolower(s[r])) { return false; } l = nextAlnum(s, l + 1); r = preAlnum(s, r - 1); } return true; } private: int nextAlnum(const string& s, int idx) { for (int i = idx; i < s.size(); ++i) { if (isalnum(s[i])) return i; } return s.size(); } int preAlnum(const string& s, int idx) { for (int i = idx; i >= 0; --i) { if (isalnum(s[i])) return i; } return -1; } }; int main() { Solution solution; string s = "A man, a plan, a canal: Panama"; cout << solution.isPalindrome(s) << endl; return 0; }
[ "whb227@163.com" ]
whb227@163.com
8bab559ba2da87346e7e781bc4603e154f614d9e
0c958692bb3abf99ecbd03bd75a605b202d4da5a
/CRAB/MuNu/farmoutAJ_analyzer/Submit_Valentine/W3JetLESDown_callHistoFiller.cc
954341b6de1709b4d7e106f6ff740e2d5afc6e85
[]
no_license
tmrhombus/UWAnalysis
a9ed18a7ba8726522c8d98fbdc018c77d80c5cc5
eb9e0794e1b847f36c660a55d3631176a39148e2
refs/heads/master
2021-01-23T20:46:41.578341
2017-05-01T08:26:57
2017-05-01T08:26:57
10,620,824
0
0
null
2014-10-21T11:21:16
2013-06-11T12:19:43
Python
UTF-8
C++
false
false
4,028
cc
/******************************** Instantiates histoFiller.C with the correct chain and naming for a definable set of parameters Usage: root -l -b .L W3JetLESDown_callHistoFiller.cc W3JetLESDown_callHistoFiller() root -l -b -q W3JetLESDown_callHistoFiller.cc Author: T.M.Perry UW-Madison ********************************/ #include <TStyle.h> #include <vector> #include <TChain.h> #include "TROOT.h" #include "TSystem.h" #include "TApplication.h" #include <iostream> #include <exception> void W3JetLESDown_callHistoFiller() { int error = 0; gROOT->ProcessLine(".L histoFiller.C++", &error); if(error!=0){std::cerr<<"ERROR LOADING histoFiller.C"<<std::endl;} histoFiller m; // TChain *chainDataEle = new TChain("electronEventTree/eventTree"); // TChain *chainDataMu = new TChain("muonEventTree/eventTree"); // TChain *theChain = new TChain("muEleEventTree/eventTree"); // TChain *theChainJESUp = new TChain("muEleEventTreeJetUp/eventTree"); // TChain *theChainJESDown = new TChain("muEleEventTreeJetDown/eventTree"); // TChain *theChainLESUp = new TChain("muEleEventTreeMuonUp/eventTree"); // TChain *theChainLESDown = new TChain("muEleEventTreeMuonDown/eventTree"); TString outfileName = getenv("OUTPUT"); TString inputListName = getenv("INPUT"); TChain *theChain = new TChain("muEleEventTreeMuonDown/eventTree"); // Define Sample Criteria UInt_t lumi_mu = 19778 ; UInt_t lumi_ele = 19757 ; TString sample="W3Jet"; UInt_t nrEvents = 30358906 ; Float_t crossSec = 36703.2 ; Bool_t isMC_ = kTRUE ; Bool_t isW_ = kTRUE ; TString shift="LESDown"; std::cout<<"Sample = "<<sample<<std::endl; std::cout<<"Shift = "<<shift<<std::endl; std::vector<TString> infileName_dump; ifstream inputList; inputList.open(inputListName); if( !inputList.good() ) { std::cerr << "Cannot open the file: \"" << inputListName+"\""<<std::endl; abort(); } // OK we have the file! TString infileName = ""; while( !inputList.eof() ) { infileName=""; inputList >> infileName; // Do your stuff here! maybe: if (infileName=="") continue; if (infileName== "#") continue; std::cout << "Output File Name: " << outfileName << std::endl; std::cout << "Input File Name: " << infileName << std::endl; theChain->Reset(); theChain->Add( infileName ); m.Init(theChain, isMC_); m.Loop( outfileName, shift, isMC_, isW_, lumi_mu, lumi_ele, nrEvents, crossSec); infileName_dump.push_back(infileName); } //while !inputList.eof() } // void W3JetLESDown_callHistoFiller() //std::vector<TString> EMu; //EMu.push_back("mu"); //EMu.push_back("ele"); //for (std::vector<TString>::iterator emu = EMu.begin(); emu != EMu.end(); ++emu){ // std::cout<<"xxxxxx Starting New Data Loop: EMu.emu = "<<emu<<" xxxxxx"<<std::endl; // // Name and set isMU_, isMC_, // TString name = "ETrg_Data_"+emu+"Data_aucun"; // isMC_ = kFALSE; // std::cout<<name<<std::endl; // // initialize the correct chain // if(emu->EqualTo("mu")){ // chainDataMu->Reset(); // chainDataMu->Add("/hdfs/store/user/tperry/NouvelleYear_DataA_8TeVMu-Mu-PATData/*root"); // chainDataMu->Add("/hdfs/store/user/tperry/NouvelleYear_DataB_8TeVMu-Mu-PATData/*root"); // chainDataMu->Add("/hdfs/store/user/tperry/NouvelleYear_DataC_8TeVMu-Mu-PATData/*root"); // chainDataMu->Add("/hdfs/store/user/tperry/NouvelleYear_DataD_8TeVMu-Mu-PATData/*root"); // m.Init(chainDataMu,isMC_); // } // if(emu->EqualTo("ele")){ // chainDataEle->Reset(); // chainDataEle->Add("/hdfs/store/user/tperry/NouvelleYear_DataA_8TeVEle-Ele-PATData/*root"); // chainDataEle->Add("/hdfs/store/user/tperry/NouvelleYear_DataB_8TeVEle-Ele-PATData/*root"); // chainDataEle->Add("/hdfs/store/user/tperry/NouvelleYear_DataC_8TeVEle-Ele-PATData/*root"); // chainDataEle->Add("/hdfs/store/user/tperry/NouvelleYear_DataD_8TeVEle-Ele-PATData/*root"); // m.Init(chainDataEle,isMC_); // } // m.Loop("../plots/"+name, "aucun", isMC_, kFALSE, 1, 1, 1, 1); //}
[ "tperry@cern.ch" ]
tperry@cern.ch
7d7d2fafa67ea370170ed748f8489e0ad46c3fbb
304705191380a9e3e14cbb242e076faf897d0aee
/Intelligent Systems CW/Position.h
a349df1bb343aca2f63862e093fd4afe0b941751
[]
no_license
IoIoToTM/Intelligent-Systems-CW
5f988da85c9787b2509db9f18e014450d694720d
f328e3e29194dc683882a26c868629ce37738d2b
refs/heads/master
2021-08-22T14:52:36.769022
2017-11-30T12:55:51
2017-11-30T12:55:51
111,731,863
0
0
null
null
null
null
UTF-8
C++
false
false
380
h
#pragma once #include"Direction.h" class Position { public: Position(int x, int y); Position(); ~Position(); //overloading the == operator so I can check between two positions friend bool operator==(const Position& left, const Position& right); int getX() const; int getY() const; void setX(int x); void setY(int y); void move(Direction d); private: int x, y; };
[ "ioiototm@gmail.com" ]
ioiototm@gmail.com
bb23b0ec51a947bb74d22948bc15b023ec13fe87
b090a0e18cceb50f8c9e9958bc126ee48de5dced
/UpdateVisionData.cpp
a555504cd37e7841ba8ea1dcff8f32bf2a91e4d3
[ "MIT" ]
permissive
abhishekbalu/abhishek-imageprocessing
e3089ba758c4f35c83e09c2b57fa2a0542df08ef
f234f6b2483123cf87ff66c9c5f4f204338d455f
refs/heads/master
2020-04-01T20:14:10.980759
2018-10-18T09:13:32
2018-10-18T09:13:32
153,594,730
3
0
null
null
null
null
UTF-8
C++
false
false
106
cpp
#include "UpdateVisionData.h" Write2Mem::Write2Mem(objects* thisObject){ cout<<thisObject->getX(); }
[ "abhisheklokesh6008@gmail.com" ]
abhisheklokesh6008@gmail.com
55942a347de80970c563f9420adfdd64fd0ccc46
24af3ebd842c88d87ad48282248f13feb8f3d94c
/Spells/SpellBook.h
51493b6e54974248e434fdf78e5ef8d67868e80e
[]
no_license
sergant4949/army
9fceb0cbeb9ffb6451de1fc7f7c05d8f67a08a47
015fd36708de28ecddc9e242a3433658c124a2fb
refs/heads/master
2020-05-16T20:16:03.406536
2015-01-23T22:16:27
2015-01-23T22:16:27
29,754,751
0
0
null
null
null
null
UTF-8
C++
false
false
650
h
#ifndef SPELLBOOK_H #define SPELLBOOK_H #include <iostream> #include "Spell.h" #include "../Units/SpellCasters/SpellCaster.h" class SpellCaster; class SpellBook { private: std::set<Spell*>* spellsList; SpellCaster* owner; public: SpellBook(SpellCaster* owner); ~SpellBook(); SpellCaster* getOwner() const; std::set<Spell*>* getSpellsList() const; std::string spellName(Spell* spell) const; void addSpell(Spell* newSpell); void removeSpell(Spell* removedSpell); }; std::ostream& operator << (std::ostream& out, const SpellBook& sBook); #endif // SPELLBOOK_H
[ "sergant4949@gmail.com" ]
sergant4949@gmail.com
5c5bf1593c5c17be63276f1c5bf2eb9ac61684ca
dff8651f87c067914335f6fdbb63195138add8f7
/Source/BCGJam/Game/Public/AI/Components/DamageActorComponent.h
92f571fbc65c407b3d42f77fa19a681ddfc55d90
[]
no_license
markveligod/bcgjam
71ff25aa93f9542993b9765de7076a6cdba7dab8
77dd8a1a06206df186ed4ee887e9bcc495c7486f
refs/heads/master
2023-05-05T06:35:55.682489
2021-05-18T05:59:30
2021-05-18T05:59:30
367,552,021
0
0
null
2021-05-18T04:12:33
2021-05-15T05:57:24
C++
UTF-8
C++
false
false
1,463
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "DamageActorComponent.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BCGJAM_API UDamageActorComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UDamageActorComponent(); protected: // Called when the game starts virtual void BeginPlay() override; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Param Editor") class UBoxComponent* BoxComponent; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Param Editor") float ImpulseForce = 10.f; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Param Editor") int32 DamageCount = 1; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Anim") class UAnimMontage* AttackAnim; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Anim") float InRateAnimAttack = 1.f; private: class ABCGJamAICharacter* AICharacter; class ABCGJamBaseCharacter* TempCharacter; class UHealthActorComponent* HealthComp; FTimerHandle TimerHandleAttack; void TryAttackToCharacter(); UFUNCTION() void OnDamageImpulse(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); };
[ "markveligod@yandex.ru" ]
markveligod@yandex.ru
0a1455c70ea574b366331ee4084e1cdade186ce0
c4fcddc2c5f0b02bbf3602f6f9b0c89484a2662b
/include/ThirdParty/Common/AutoPtr.h
29aeb92fbf86a237c532c2c04c6e2c722f780e92
[ "BSD-3-Clause", "MIT" ]
permissive
ternence-li/LightInk3D
a54971ccd50fb15be8a4c019a038655ed9b1b9ea
7b35419d164c9c939359f9106264841dc8c283a2
refs/heads/master
2021-06-11T20:21:44.810389
2017-01-20T09:59:44
2017-01-20T09:59:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,422
h
/* Copyright ChenDong(Wilbur), email <baisaichen@live.com>. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef LIGHTINK_COMMON_AUTOPTR_H_ #define LIGHTINK_COMMON_AUTOPTR_H_ #include "Common/SmallObject.h" namespace LightInk { template <typename T, typename DelStrategy, typename Allocator> class LIGHTINK_TEMPLATE_DECL AutoPtrWrapper : public Allocator { public: AutoPtrWrapper(); template<typename __T> explicit AutoPtrWrapper(__T * ptr); AutoPtrWrapper(const AutoPtrWrapper<T, DelStrategy, Allocator> & cp); AutoPtrWrapper<T, DelStrategy, Allocator> & operator = (const AutoPtrWrapper<T, DelStrategy, Allocator> & right); template <typename __T, typename __DelStrategy, typename __Allocator> AutoPtrWrapper(const AutoPtrWrapper<__T, __DelStrategy, __Allocator> & cp); template <typename __T, typename __DelStrategy, typename __Allocator> AutoPtrWrapper<T, DelStrategy, Allocator> & operator = (const AutoPtrWrapper<__T, __DelStrategy, __Allocator> & cp); ~AutoPtrWrapper(); template<typename __T> void reset(__T * ptr = NULL); T * get() const; T * release(); T & operator * () const; T * operator -> () const; operator bool() const; private: T * m_objPtr; }; template <typename T, typename DelStrategy, typename Allocator> bool operator == (const AutoPtrWrapper<T, DelStrategy, Allocator> & left, T * right); template <typename T, typename DelStrategy, typename Allocator> bool operator == (T * left, const AutoPtrWrapper<T, DelStrategy, Allocator> & right); template <typename T, typename DelStrategy, typename Allocator> bool operator != (const AutoPtrWrapper<T, DelStrategy, Allocator> & left, T * right); template <typename T, typename DelStrategy, typename Allocator> bool operator != (T * left,const AutoPtrWrapper<T, DelStrategy, Allocator> & right); struct PtrDelStrategy { template <typename T> static void release(T * ptr); }; struct ArrayDelStrategy { template <typename T> static void release(T * ptr); }; template <typename T> struct AutoPtr { typedef AutoPtrWrapper<T, PtrDelStrategy, SmallObject> type; }; template <typename T> struct AutoArrayPtr { typedef AutoPtrWrapper<T, ArrayDelStrategy, SmallObject> type; }; } #include "AutoPtr.cpp" #endif
[ "baisaichen@live.com" ]
baisaichen@live.com
d2f4ce82032670c1fcc4b65d3c96ab09c10217f3
41eb0837713f297134529591b66f3d4d82bcf98e
/src/Raine/source/sdl/console/console.h
80a9d442e7dd62468b9f11b8503659c19e80bd4d
[]
no_license
AlexxandreFS/Batocera.PLUS
27b196b3cbb781b6fc99e62cad855396d1d5f8f2
997ee763ae7135fdf0c34a081e789918bd2eb169
refs/heads/master
2023-08-17T21:52:39.083687
2023-08-17T15:03:44
2023-08-17T15:03:44
215,869,486
135
57
null
2023-08-14T14:46:14
2019-10-17T19:23:42
C
UTF-8
C++
false
false
1,207
h
#ifndef CONSOLE_H #define CONSOLE_H #ifdef __cplusplus extern "C" { #include "sdl/gui/tconsole.h" #include "parser.h" class TRaineConsole : public TConsole { char last_cmd[80]; int pointer_on, pointer_n, pointer_x,pointer_top,pointer_rows,pointer_end; int dump_cols; public: TRaineConsole(char *my_title, char *init_label, int maxlen, int maxlines, commands_t *mycmd) : TConsole(my_title,init_label,maxlen,maxlines,mycmd) { load_history(); pointer_on = 0; dump_cols = ((maxlen-7)/4)&~7; use_transparency = 0; } virtual void execute(); virtual void handle_mouse(SDL_Event *event); virtual void unknown_command(int argc, char **argv); virtual int run_cmd(char *field); virtual void post_print() { pointer_on = 0; // erase mouse cursor after a print } int get_dump_cols() { return dump_cols; } }; extern TRaineConsole *cons; int get_cpu_id(); } #endif #ifdef __cplusplus extern "C" { #endif int do_console(int sel); void preinit_console(); void done_console(); void run_console_command(char *command); void do_regs(int argc, char **argv); #ifdef __cplusplus UINT8 *get_ptr(UINT32 addr, UINT32 *the_block = NULL); } #endif #endif
[ "alexxandre.freire@gmail.com" ]
alexxandre.freire@gmail.com
087132ef1f2bd83f25d59d6cb200e1d61c97dfa7
c54f684c896c4537e92cc5edd6985c8f4754af48
/scintilla/lexlib/LexAccessor.h
3564dd0bcbc78f646f76167afbb3dc398b489127
[ "MIT" ]
permissive
kbuffington/foo_jscript_panel
b0678ee55c9de547770d6741563b62cd81b150bf
8e8375c109595b18e624e8709ee6d84effba66b4
refs/heads/master
2020-05-09T15:41:05.716211
2020-04-26T16:56:56
2020-04-26T16:56:56
181,238,758
21
2
MIT
2020-04-26T04:02:28
2019-04-13T23:24:14
C++
UTF-8
C++
false
false
5,031
h
// Scintilla source code edit control /** @file LexAccessor.h ** Interfaces between Scintilla and lexers. **/ // Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef LEXACCESSOR_H #define LEXACCESSOR_H namespace Scintilla { enum EncodingType { enc8bit, encUnicode, encDBCS }; class LexAccessor { private: IDocument *pAccess; enum {extremePosition=0x7FFFFFFF}; /** @a bufferSize is a trade off between time taken to copy the characters * and retrieval overhead. * @a slopSize positions the buffer before the desired position * in case there is some backtracking. */ enum {bufferSize=4000, slopSize=bufferSize/8}; char buf[bufferSize+1]; Sci_Position startPos; Sci_Position endPos; int codePage; enum EncodingType encodingType; Sci_Position lenDoc; char styleBuf[bufferSize]; Sci_Position validLen; Sci_PositionU startSeg; Sci_Position startPosStyling; int documentVersion; void Fill(Sci_Position position) { startPos = position - slopSize; if (startPos + bufferSize > lenDoc) startPos = lenDoc - bufferSize; if (startPos < 0) startPos = 0; endPos = startPos + bufferSize; if (endPos > lenDoc) endPos = lenDoc; pAccess->GetCharRange(buf, startPos, endPos-startPos); buf[endPos-startPos] = '\0'; } public: explicit LexAccessor(IDocument *pAccess_) : pAccess(pAccess_), startPos(extremePosition), endPos(0), codePage(pAccess->CodePage()), encodingType(enc8bit), lenDoc(pAccess->Length()), validLen(0), startSeg(0), startPosStyling(0), documentVersion(pAccess->Version()) { // Prevent warnings by static analyzers about uninitialized buf and styleBuf. buf[0] = 0; styleBuf[0] = 0; switch (codePage) { case 65001: encodingType = encUnicode; break; case 932: case 936: case 949: case 950: case 1361: encodingType = encDBCS; } } char operator[](Sci_Position position) { if (position < startPos || position >= endPos) { Fill(position); } return buf[position - startPos]; } IDocument *MultiByteAccess() const { return pAccess; } /** Safe version of operator[], returning a defined value for invalid position. */ char SafeGetCharAt(Sci_Position position, char chDefault=' ') { if (position < startPos || position >= endPos) { Fill(position); if (position < startPos || position >= endPos) { // Position is outside range of document return chDefault; } } return buf[position - startPos]; } bool IsLeadByte(char ch) const { return pAccess->IsDBCSLeadByte(ch); } EncodingType Encoding() const { return encodingType; } bool Match(Sci_Position pos, const char *s) { for (int i=0; *s; i++) { if (*s != SafeGetCharAt(pos+i)) return false; s++; } return true; } char StyleAt(Sci_Position position) const { return pAccess->StyleAt(position); } Sci_Position GetLine(Sci_Position position) const { return pAccess->LineFromPosition(position); } Sci_Position LineStart(Sci_Position line) const { return pAccess->LineStart(line); } Sci_Position LineEnd(Sci_Position line) const { return pAccess->LineEnd(line); } int LevelAt(Sci_Position line) const { return pAccess->GetLevel(line); } Sci_Position Length() const { return lenDoc; } void Flush() { if (validLen > 0) { pAccess->SetStyles(validLen, styleBuf); startPosStyling += validLen; validLen = 0; } } int GetLineState(Sci_Position line) const { return pAccess->GetLineState(line); } int SetLineState(Sci_Position line, int state) { return pAccess->SetLineState(line, state); } // Style setting void StartAt(Sci_PositionU start) { pAccess->StartStyling(start); startPosStyling = start; } Sci_PositionU GetStartSegment() const { return startSeg; } void StartSegment(Sci_PositionU pos) { startSeg = pos; } void ColourTo(Sci_PositionU pos, int chAttr) { // Only perform styling if non empty range if (pos != startSeg - 1) { assert(pos >= startSeg); if (pos < startSeg) { return; } if (validLen + (pos - startSeg + 1) >= bufferSize) Flush(); const char attr = static_cast<char>(chAttr); if (validLen + (pos - startSeg + 1) >= bufferSize) { // Too big for buffer so send directly pAccess->SetStyleFor(pos - startSeg + 1, attr); } else { for (Sci_PositionU i = startSeg; i <= pos; i++) { assert((startPosStyling + validLen) < Length()); styleBuf[validLen++] = attr; } } } startSeg = pos+1; } void SetLevel(Sci_Position line, int level) { pAccess->SetLevel(line, level); } void IndicatorFill(Sci_Position start, Sci_Position end, int indicator, int value) { pAccess->DecorationSetCurrentIndicator(indicator); pAccess->DecorationFillRange(start, value, end - start); } void ChangeLexerState(Sci_Position start, Sci_Position end) { pAccess->ChangeLexerState(start, end); } }; struct LexicalClass { int value; const char *name; const char *tags; const char *description; }; } #endif
[ "34617027+marc2k3@users.noreply.github.com" ]
34617027+marc2k3@users.noreply.github.com
d29e5422c75b78fd4270ab48255ab5ac58acd016
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-glue/source/model/BatchUpdatePartitionRequest.cpp
f0120d374c40fd61ace9340c381b63858358768c
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
1,548
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/glue/model/BatchUpdatePartitionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Glue::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; BatchUpdatePartitionRequest::BatchUpdatePartitionRequest() : m_catalogIdHasBeenSet(false), m_databaseNameHasBeenSet(false), m_tableNameHasBeenSet(false), m_entriesHasBeenSet(false) { } Aws::String BatchUpdatePartitionRequest::SerializePayload() const { JsonValue payload; if(m_catalogIdHasBeenSet) { payload.WithString("CatalogId", m_catalogId); } if(m_databaseNameHasBeenSet) { payload.WithString("DatabaseName", m_databaseName); } if(m_tableNameHasBeenSet) { payload.WithString("TableName", m_tableName); } if(m_entriesHasBeenSet) { Array<JsonValue> entriesJsonList(m_entries.size()); for(unsigned entriesIndex = 0; entriesIndex < entriesJsonList.GetLength(); ++entriesIndex) { entriesJsonList[entriesIndex].AsObject(m_entries[entriesIndex].Jsonize()); } payload.WithArray("Entries", std::move(entriesJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection BatchUpdatePartitionRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSGlue.BatchUpdatePartition")); return headers; }
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
1c862584ee266b8fe006328f2ed68f5276233c38
49404c7c32be5d3fb4a30002f2de4dc960c7bf0d
/AdaLab/Sorting/MergeSort.cpp
0991063d5b607cc97460c33701e90db94f3921d6
[]
no_license
Ravi02205/CppCompetitiveRepository
2b5cabc003a4c46dd01062f2a2f76bd913829c70
a43f06cbd5d34f7f1373f35355984afffbec3283
refs/heads/master
2022-02-15T09:31:32.504366
2019-09-07T10:13:00
2019-09-07T10:13:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,097
cpp
#include "iostream" #include "chrono" #include "time.h" using namespace std; using namespace std::chrono; void merge(int *arr, int start, int end) { int mid = (start+end)/2; int i = start, j = mid+1, k = start; int temp[10000]; while(i <= mid and j <= end) { if(arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } } while(i <= mid) { temp[k++] = arr[i++]; } while(j <= end) { temp[k++] = arr[j++]; } for(int i = start; i <= end; i++) { arr[i] = temp[i]; } } void mergeSort(int *arr, int start, int end) { if(start >= end) { return; } int mid = (start+end)/2; mergeSort(arr, start, mid); mergeSort(arr, mid+1, end); merge(arr, start, end); } // void printArray(int A[], int size) // { // for (int i = 0; i < size; i++) // printf("%d ", A[i]); // printf("\n"); // } // void join(int arr[], int left[], int right[], // int l, int m, int r) // { // int i; // Used in second loop // for (i = 0; i <= m - l; i++) // arr[i] = left[i]; // for (int j = 0; j < r - m; j++) // arr[i + j] = right[j]; // } // // Function to store alternate elemets in left // // and right subarray // void split(int arr[], int left[], int right[], // int l, int m, int r) // { // for (int i = 0; i <= m - l; i++) // left[i] = arr[i * 2]; // for (int i = 0; i < r - m; i++) // right[i] = arr[i * 2 + 1]; // } // void generateWorstCase(int arr[], int l, int r) // { // if (l < r) // { // int m = l + (r - l) / 2; // // create two auxillary arrays // int left[m - l + 1]; // int right[r - m]; // // Store alternate array elements in left // // and right subarray // split(arr, left, right, l, m, r); // // Recurse first and second halves // generateWorstCase(left, l, m); // generateWorstCase(right, m + 1, r); // // join left and right subarray // join(arr, left, right, l, m, r); // } // } int main(int argc, char const *argv[]) { int arr[100000]; int max = 1000, min = 1; int range = max - min + 1; int avg_result[30] = {0}; int best_result[30] = {0}; int worst_result[30] = {0}; int size[30] = {10, 50, 100, 250, 500, 750, 1000,1200, 1500, 2000, 5000, 6000, 7500,10000, 20000, 25000, 30000,45000, 50000, 75000, 85000, 95000, 100000, 150000, 250000, 400000, 500000,750000, 900000, 1000000}; // for(int i = 0; i < 14; i++) { // srand(time(0)); // for(int j = 0; j < size[i]; j++) { // arr[j] = (rand()%range)+min; // } // auto start = high_resolution_clock::now(); // mergeSort(arr, 0, size[i] - 1); // auto stop = high_resolution_clock::now(); // auto duration = duration_cast<microseconds>(stop - start); // cout<<duration.count()<<", "; // } // cout<<endl; // // for(int i = 0; i < 14; i++) { // srand(time(0)); // for(int j = 0; j < size[i]; j++) { // arr[j] = j+1; // } // auto start = high_resolution_clock::now(); // mergeSort(arr, 0, size[i]-1); // auto stop = high_resolution_clock::now(); // auto duration = duration_cast<microseconds>(stop - start); // cout<<duration.count()<<" ,"; // } // cout<<endl; // for(int i = 0; i < 14; i++) { // srand(time(0)); // int arr[size[i]]; // int temp[size[i]]; // generateWorstCase(temp, 0, size[i] - 1); // for(int j = 0; j < size[i]; j++) { // arr[j] = temp[j]; // } // auto start = high_resolution_clock::now(); // // printArray(arr, size[i]); // // cout<<endl; // mergeSort(arr, 0, size[i]-1); // auto stop = high_resolution_clock::now(); // // printArray(arr, size[i]); // // cout<<endl; // auto duration = duration_cast<microseconds>(stop - start); // cout<<duration.count()<<" ,"; // } // cout<<endl; return 0; }
[ "singhsanket143@gmail.com" ]
singhsanket143@gmail.com
5130c90784571cdd436996315ebf09d2133bf5d7
cf520a9beaf3b5abee463c285efe8130eef1f182
/pellets/z_thread_pool/z_thread_stack.h
8efa7123d259892a8e50344a08eaaa73d0e2179d
[ "Unlicense" ]
permissive
AlexXChina/zpublic
c78eb51b6c9879943d8e4b46cac3e15f837038a3
78caa5d9972c94b8c5cb69d46275d4ecac12fcc8
refs/heads/master
2021-01-22T12:48:49.712690
2015-09-01T15:33:33
2015-09-01T15:33:33
43,356,201
1
0
null
2015-09-29T08:56:35
2015-09-29T08:56:35
null
UTF-8
C++
false
false
348
h
#pragma once #include "../thread_sync/thread_sync.h" #include "z_thread.h" #include <stack> class z_thread_stack { public: z_thread_stack(); ~z_thread_stack(); public: z_thread* pop(); void push(z_thread* t); void clear(); private: std::stack<z_thread*> m_stack; z_mutex m_mutex; };
[ "278998871@qq.com" ]
278998871@qq.com
02d0b1c8e518a5875c054e48ad54fb6bebfa6295
38370ec6d3ba86570dd0efd1de8841f6ff5bad59
/CrossApp/view/CAScrollView.cpp
6a5f9b6310a032478f60a6dc21f2c2d7d13e717c
[]
no_license
RainbowMin/CrossApp
f3588907811cc5f3b9936439b95aade65eb29e5a
45b5d4893fab0bb955089e1655694b189760608d
refs/heads/master
2021-01-18T10:07:52.377093
2014-07-22T05:44:16
2014-07-22T05:44:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,109
cpp
// // CAScrollView.cpp // CrossApp // // Created by Li Yuanfeng on 14-4-23. // Copyright (c) 2014 http://9miao.com All rights reserved. // #include "CAScrollView.h" #include "CAScale9ImageView.h" #include "actions/CCActionInterval.h" #include "actions/CCActionEase.h" #include "basics/CAApplication.h" #include "basics/CAScheduler.h" #include "dispatcher/CATouch.h" #include "support/CCPointExtension.h" #include "kazmath/GL/matrix.h" #include "CCEGLView.h" NS_CC_BEGIN #pragma CAScrollView CAScrollView::CAScrollView() :m_pContainer(NULL) ,m_obViewSize(CCSizeZero) ,m_pScrollViewDelegate(NULL) ,m_bBounces(true) ,m_bBounceHorizontal(true) ,m_bBounceVertical(true) ,m_bscrollEnabled(true) ,m_bTracking(false) ,m_bDecelerating(false) ,m_bZooming(false) ,m_fMaximumZoomScale(1.0f) ,m_fMinimumZoomScale(1.0f) ,m_fZoomScale(1.0f) ,m_fTouchLength(0.0f) ,m_tInertia(CCPointZero) ,m_tCloseToPoint(CCPointZero) ,m_pIndicatorHorizontal(NULL) ,m_pIndicatorVertical(NULL) ,m_bShowsHorizontalScrollIndicator(true) ,m_bShowsVerticalScrollIndicator(true) { m_bSlideContainers = true; m_pTouches = new CCArray(2); m_pChildInThis = new CCArray(); } CAScrollView::~CAScrollView() { CC_SAFE_DELETE(m_pTouches); CC_SAFE_DELETE(m_pChildInThis); m_pScrollViewDelegate = NULL; } void CAScrollView::onEnterTransitionDidFinish() { CAView::onEnterTransitionDidFinish(); } void CAScrollView::onExitTransitionDidStart() { CAView::onExitTransitionDidStart(); m_tPointOffset.clear(); m_pTouches->removeAllObjects(); m_tInertia = CCPointZero; } CAScrollView* CAScrollView::createWithFrame(const CCRect& rect) { CAScrollView* scrollView = new CAScrollView(); if (scrollView && scrollView->initWithFrame(rect)) { scrollView->autorelease(); return scrollView; } CC_SAFE_DELETE(scrollView); return NULL; } CAScrollView* CAScrollView::createWithCenter(const CCRect& rect) { CAScrollView* scrollView = new CAScrollView(); if (scrollView && scrollView->initWithCenter(rect)) { scrollView->autorelease(); return scrollView; } CC_SAFE_DELETE(scrollView); return NULL; } bool CAScrollView::init() { if (!CAView::init()) { return false; } this->setDisplayRange(false); m_pContainer = CAView::createWithFrame(this->getBounds(), CAColor_clear); m_pChildInThis->addObject(m_pContainer); this->addSubview(m_pContainer); m_pIndicatorHorizontal = CAIndicator::create(CAIndicator::CAIndicatorTypeHorizontal); m_pChildInThis->addObject(m_pIndicatorHorizontal); this->insertSubview(m_pIndicatorHorizontal, 1); m_pIndicatorVertical = CAIndicator::create(CAIndicator::CAIndicatorTypeVertical); m_pChildInThis->addObject(m_pIndicatorVertical); this->insertSubview(m_pIndicatorVertical, 1); return true; } void CAScrollView::addSubview(CAView* subview) { do { CC_BREAK_IF(m_pChildInThis->containsObject(subview)); m_pContainer->addSubview(subview); return; } while (0); CAView::addSubview(subview); } void CAScrollView::insertSubview(CAView* subview, int z) { do { CC_BREAK_IF(m_pChildInThis->containsObject(subview)); m_pContainer->insertSubview(subview, z); return; } while (0); CAView::insertSubview(subview, z); } void CAScrollView::removeAllSubviews() { m_pContainer->removeAllSubviews(); } void CAScrollView::removeSubview(CAView* subview) { m_pContainer->removeSubview(subview); } void CAScrollView::removeSubviewByTag(int tag) { m_pContainer->removeSubviewByTag(tag); } CAView* CAScrollView::getSubviewByTag(int aTag) { return m_pContainer->getSubviewByTag(aTag); } CCArray* CAScrollView::getSubviews() { return m_pContainer->getSubviews(); } void CAScrollView::setViewSize(CrossApp::CCSize var) { CC_RETURN_IF(m_obViewSize.equals(var)); m_obViewSize = var; m_obViewSize.width = MAX(m_obViewSize.width, m_obContentSize.width); m_obViewSize.height = MAX(m_obViewSize.height, m_obContentSize.height); CC_RETURN_IF(m_pContainer == NULL); CCRect rect = m_pContainer->getFrame(); rect.size = m_obViewSize; m_pContainer->setFrame(rect); } CCSize CAScrollView::getViewSize() { return m_obViewSize; } void CAScrollView::setScrollEnabled(bool var) { m_bSlideContainers = m_bscrollEnabled = var; } bool CAScrollView::isScrollEnabled() { return m_bscrollEnabled; } void CAScrollView::setBounces(bool var) { m_bBounces = var; if (var == false) { m_bBounceHorizontal = false; m_bBounceVertical = false; } } bool CAScrollView::isBounces() { return m_bBounces; } void CAScrollView::setShowsHorizontalScrollIndicator(bool var) { m_bShowsHorizontalScrollIndicator = var; if (m_bShowsHorizontalScrollIndicator) { m_pIndicatorHorizontal->setVisible(true); } else { m_pIndicatorHorizontal->setVisible(false); } } bool CAScrollView::isShowsHorizontalScrollIndicator() { return m_bShowsHorizontalScrollIndicator; } void CAScrollView::setShowsVerticalScrollIndicator(bool var) { m_bShowsVerticalScrollIndicator = var; if (m_bShowsVerticalScrollIndicator) { m_pIndicatorVertical->setVisible(true); } else { m_pIndicatorVertical->setVisible(false); } } bool CAScrollView::isShowsVerticalScrollIndicator() { return m_bShowsVerticalScrollIndicator; } void CAScrollView::setContentOffset(CCPoint offset, bool animated) { if (animated) { m_tCloseToPoint = ccpMult(offset, -1); m_tInertia = CCPointZero; CAScheduler::unschedule(schedule_selector(CAScrollView::deaccelerateScrolling), this); CAScheduler::schedule(schedule_selector(CAScrollView::closeToPoint), this, 1/60.0f); } else { m_pContainer->setFrameOrigin(ccpMult(offset, -1)); } } CCPoint CAScrollView::getContentOffset() { return ccpMult(m_pContainer->getFrameOrigin(), -1); } void CAScrollView::setBackGroundImage(CAImage* image) { CAView::setImage(image); CCRect rect = CCRectZero; rect.size = image->getContentSize(); CAView::setImageRect(rect); } void CAScrollView::setBackGroundColor(const CAColor4B &color) { CAView::setColor(color); } void CAScrollView::setContentSize(const CrossApp::CCSize &var) { CAView::setContentSize(var); CCSize viewSize = this->getViewSize(); viewSize.width = MAX(m_obContentSize.width, viewSize.width); viewSize.height = MAX(m_obContentSize.height, viewSize.height); this->setViewSize(viewSize); CCPoint point = m_pContainer->getCenterOrigin(); point = this->getScrollWindowNotOutPoint(point); m_pContainer->setCenterOrigin(point); const char indicatorSize = 6 * CROSSAPP_ADPTATION_RATIO; if (m_pIndicatorHorizontal) { const CCRect indicatorHorizontalFrame = CCRect(indicatorSize * 2, var.height - indicatorSize * 2, var.width - indicatorSize * 4, indicatorSize); m_pIndicatorHorizontal->setFrame(indicatorHorizontalFrame); } if (m_pIndicatorVertical) { const CCRect indicatorVerticalFrame = CCRect(var.width - indicatorSize * 2, indicatorSize * 2, indicatorSize, var.height - indicatorSize * 4); m_pIndicatorVertical->setFrame(indicatorVerticalFrame); } this->update(0); } void CAScrollView::closeToPoint(float dt) { CCSize size = this->getBounds().size; CCPoint point = m_pContainer->getFrameOrigin(); CCPoint resilience = ccpSub(m_tCloseToPoint, point); if (resilience.getLength() <= 0.5f) { m_pContainer->setFrameOrigin(m_tCloseToPoint); CAScheduler::unschedule(schedule_selector(CAScrollView::closeToPoint), this); m_tCloseToPoint = this->getViewSize(); this->hideIndicator(); this->contentOffsetFinish(); } else { resilience.x /= size.width; resilience.y /= size.height; resilience = ccpMult(resilience, maxBouncesSpeed(dt)); resilience = ccpAdd(resilience, point); m_pContainer->setFrameOrigin(resilience); } } bool CAScrollView::ccTouchBegan(CATouch *pTouch, CAEvent *pEvent) { do { CC_BREAK_IF(!this->isVisible()); CC_BREAK_IF(m_pTouches->count() > 2); if (m_bscrollEnabled == false) return true; if (!m_pTouches->containsObject(pTouch)) { m_pTouches->addObject(pTouch); } if (m_pTouches->count() == 1) { CAScheduler::unschedule(schedule_selector(CAScrollView::deaccelerateScrolling), this); m_tInertia = CCPointZero; CAScheduler::unschedule(schedule_selector(CAScrollView::closeToPoint), this); m_tCloseToPoint = this->getViewSize(); m_pContainer->setAnchorPoint(CCPoint(0.5f, 0.5f)); } else if (m_pTouches->count() == 2) { CATouch* touch0 = dynamic_cast<CATouch*>(m_pTouches->objectAtIndex(0)); CATouch* touch1 = dynamic_cast<CATouch*>(m_pTouches->objectAtIndex(1)); m_fTouchLength = ccpDistance(touch0->getLocation(), touch1->getLocation()); CCPoint mid_point = ccpMidpoint(touch0->getLocation(), touch1->getLocation()); CCPoint p = m_pContainer->convertToNodeSpace(mid_point); m_pContainer->setAnchorPointInPoints(p); if (m_pScrollViewDelegate) { m_pScrollViewDelegate->scrollViewDidZoom(this); } m_bZooming = true; } return true; } while (0); return false; } void CAScrollView::ccTouchMoved(CATouch *pTouch, CAEvent *pEvent) { CC_RETURN_IF(m_bscrollEnabled == false); CCPoint p_container = m_pContainer->getCenterOrigin(); CCPoint p_off = CCPointZero; if (m_pTouches->count() == 1) { p_off = ccpSub(pTouch->getLocation(), pTouch->getPreviousLocation()); } else if (m_pTouches->count() == 2) { CATouch* touch0 = dynamic_cast<CATouch*>(m_pTouches->objectAtIndex(0)); CATouch* touch1 = dynamic_cast<CATouch*>(m_pTouches->objectAtIndex(1)); CCPoint mid_point = ccpMidpoint(touch0->getLocation(), touch1->getLocation()); if (m_fMinimumZoomScale < m_fMaximumZoomScale) { float touch_lenght = ccpDistance(touch0->getLocation(), touch1->getLocation()); float scale_off = touch_lenght - m_fTouchLength; m_fZoomScale = m_pContainer->getScale(); m_fZoomScale += m_fZoomScale * scale_off * 0.0015f; m_fZoomScale = MIN(m_fZoomScale, m_fMaximumZoomScale); m_fZoomScale = MAX(m_fZoomScale, m_fMinimumZoomScale); m_pContainer->setScale(m_fZoomScale); m_fTouchLength = touch_lenght; } p_off = ccpSub(this->convertToNodeSpace(mid_point), ccpAdd(m_pContainer->getFrameOrigin(), m_pContainer->getAnchorPointInPoints() * m_fZoomScale)); } if (m_bBounces) { CCSize size = this->getBounds().size; CCRect rect = m_pContainer->getCenter(); rect.size.width = MAX(rect.size.width, size.width); rect.size.height = MAX(rect.size.height, size.height); CCPoint scale = CCPoint(1.0f, 1.0f); if (p_container.x - rect.size.width / 2 > 0) { scale.x = MAX(0, 0.5f - (rect.origin.x - rect.size.width/2) / size.width); p_off.x *= scale.x; } if (p_container.y - rect.size.height / 2 > 0) { scale.y = MAX(0, 0.5f - (rect.origin.y - rect.size.height/2) / size.height); p_off.y *= scale.y; } if ((p_container.x + rect.size.width / 2 - size.width) < 0) { scale.x = MAX(0, (rect.size.width/2 + rect.origin.x) / size.width - 0.5f); p_off.x *= scale.x; } if ((p_container.y + rect.size.height / 2 - size.height) < 0) { scale.y = MAX(0, (rect.size.height/2 + rect.origin.y) / size.height - 0.5f); p_off.y *= scale.y; } } p_container = ccpAdd(p_container, p_off); m_tPointOffset.push_back(p_off); if (m_tPointOffset.size() > 3) { m_tPointOffset.pop_front(); } if (m_bBounces == false) { p_container = this->getScrollWindowNotOutPoint(p_container); } else { if (m_bBounceHorizontal == false) { p_container.x = this->getScrollWindowNotOutHorizontal(p_container.x); } if (m_bBounceVertical == false) { p_container.y = this->getScrollWindowNotOutVertical(p_container.y); } } if (p_container.equals(m_pContainer->getCenterOrigin()) == false) { m_pContainer->setCenterOrigin(p_container); this->showIndicator(); if (m_bTracking == false) { if (m_pScrollViewDelegate) { m_pScrollViewDelegate->scrollViewWillBeginDragging(this); } m_bTracking = true; } if (m_pScrollViewDelegate) { m_pScrollViewDelegate->scrollViewDidScroll(this); } } } void CAScrollView::ccTouchEnded(CATouch *pTouch, CAEvent *pEvent) { if (m_pTouches->containsObject(pTouch)) { if (m_pTouches->count() == 1) { CCPoint p = CCPointZero; if (m_tPointOffset.size() > 0) { for (unsigned int i=0; i<m_tPointOffset.size(); i++) { p = ccpAdd(p, m_tPointOffset.at(i)); } p = p/m_tPointOffset.size(); } m_tInertia = p * 1.5f; m_tPointOffset.clear(); CAScheduler::schedule(schedule_selector(CAScrollView::deaccelerateScrolling), this, 1/60.0f); if (m_pScrollViewDelegate) { m_pScrollViewDelegate->scrollViewDidEndDragging(this); } m_bTracking = false; } else if (m_pTouches->count() == 2) { m_bZooming = false; } m_pTouches->removeObject(pTouch); } } void CAScrollView::ccTouchCancelled(CATouch *pTouch, CAEvent *pEvent) { if (m_pTouches->containsObject(pTouch)) { if (m_pTouches->count() == 1) { m_tPointOffset.clear(); if (m_pScrollViewDelegate) { m_pScrollViewDelegate->scrollViewDidEndDragging(this); } m_bTracking = false; } else if (m_pTouches->count() == 2) { m_bZooming = false; } m_pTouches->removeObject(pTouch); } } void CAScrollView::deaccelerateScrolling(float dt) { dt = MIN(dt, 1/30.0f); dt = MAX(dt, 1/100.0f); if (m_tInertia.getLength() > maxSpeedCache(dt)) { m_tInertia = ccpMult(m_tInertia, maxSpeedCache(dt) / m_tInertia.getLength()); } CCPoint speed = CCPointZero; if (m_tInertia.getLength() > maxSpeed(dt)) { speed = ccpMult(m_tInertia, maxSpeed(dt) / m_tInertia.getLength()); } else { speed = m_tInertia; } if (!m_tInertia.equals(CCPointZero)) { m_tInertia = ccpMult(m_tInertia, 1 - decelerationRatio(dt)); } CCPoint point = m_pContainer->getCenterOrigin(); if (m_bBounces) { CCSize size = this->getBounds().size; CCSize cSize = m_pContainer->getFrame().size; cSize.width = MAX(cSize.width, size.width); cSize.height = MAX(cSize.height, size.height); CCPoint resilience = CCPointZero; if (point.x - cSize.width / 2 > 0) { resilience.x = (point.x - cSize.width / 2) / size.width; } if (point.y - cSize.height / 2 > 0) { resilience.y = (point.y - cSize.height / 2) / size.height; } if ((point.x + cSize.width / 2 - size.width) < 0) { resilience.x = (point.x + cSize.width / 2 - size.width) / size.width; } if ((point.y + cSize.height / 2 - size.height) < 0) { resilience.y = (point.y + cSize.height / 2 - size.height) / size.height; } resilience = ccpMult(resilience, maxBouncesSpeed(dt)); if (speed.getLength() < resilience.getLength()) { speed = ccpSub(speed, resilience); m_tInertia = CCPointZero; } } point = ccpAdd(point, speed); if (this->isScrollWindowNotMaxOutSide(m_pContainer->getCenterOrigin())) { m_tInertia = CCPointZero; } if (m_bBounces == false) { point = this->getScrollWindowNotOutPoint(point); } else { if (m_bBounceHorizontal == false) { point.x = this->getScrollWindowNotOutHorizontal(point.x); } if (m_bBounceVertical == false) { point.y = this->getScrollWindowNotOutVertical(point.y); } } m_bDecelerating = true; if (m_pScrollViewDelegate && point.equals(m_pContainer->getCenterOrigin()) == false) { m_pScrollViewDelegate->scrollViewDidScroll(this); } if (speed.getLength() <= 0.5f) { point = this->getScrollWindowNotOutPoint(point); m_pContainer->setCenterOrigin(point); this->hideIndicator(); m_bDecelerating = false; CAScheduler::unschedule(schedule_selector(CAScrollView::deaccelerateScrolling), this); } else if (point.equals(m_pContainer->getCenterOrigin()) == false) { this->showIndicator(); m_pContainer->setCenterOrigin(point); } } float CAScrollView::maxSpeed(float dt) { return (CCPoint(m_obContentSize).getLength() * 5 * dt); } float CAScrollView::maxSpeedCache(float dt) { return (maxSpeed(dt) * 1.5f); } float CAScrollView::decelerationRatio(float dt) { return 6 * dt; } float CAScrollView::maxBouncesSpeed(float dt) { return (CCPoint(m_obContentSize).getLength() * 6 * dt); } CCPoint CAScrollView::maxBouncesLenght() { return ccpMult(this->getBounds().size, 0.3f); } void CAScrollView::showIndicator() { if (!CAScheduler::isScheduled(schedule_selector(CAScrollView::update), this)) { CAScheduler::schedule(schedule_selector(CAScrollView::update), this, 1/60.0f); } m_pIndicatorHorizontal->setHide(false); m_pIndicatorVertical->setHide(false); this->update(0); } void CAScrollView::hideIndicator() { CAScheduler::unschedule(schedule_selector(CAScrollView::update), this); m_pIndicatorHorizontal->setHide(true); m_pIndicatorVertical->setHide(true); } void CAScrollView::update(float dt) { if (m_pIndicatorHorizontal) { m_pIndicatorHorizontal->setIndicator(m_obContentSize, m_pContainer->getFrame()); } if (m_pIndicatorVertical) { m_pIndicatorVertical->setIndicator(m_obContentSize, m_pContainer->getFrame()); } } const CCPoint& CAScrollView::getScrollWindowNotOutPoint(CCPoint& point) { point.x = this->getScrollWindowNotOutHorizontal(point.x); point.y = this->getScrollWindowNotOutVertical(point.y); return point; } float CAScrollView::getScrollWindowNotOutHorizontal(float x) { CCSize size = this->getBounds().size; CCSize cSize = m_pContainer->getFrame().size; cSize.width = MAX(cSize.width, size.width); cSize.height = MAX(cSize.height, size.height); x = MIN(x, cSize.width / 2) ; x = MAX(x, size.width - cSize.width / 2); return x; } float CAScrollView::getScrollWindowNotOutVertical(float y) { CCSize size = this->getBounds().size; CCSize cSize = m_pContainer->getFrame().size; cSize.width = MAX(cSize.width, size.width); cSize.height = MAX(cSize.height, size.height); y = MIN(y, cSize.height / 2); y = MAX(y, size.height - cSize.height / 2); return y; } bool CAScrollView::isScrollWindowNotOutSide() { CCSize size = this->getBounds().size; CCRect rect = m_pContainer->getFrame(); CCPoint point = m_pContainer->getCenter().origin; if (point.x - rect.size.width / 2 > 0.5f) { return true; } if ((point.x + rect.size.width / 2 - size.width) < -0.5f) { return true; } if (point.y - rect.size.height / 2 > 0.5f) { return true; } if ((point.y + rect.size.height / 2 - size.height) < -0.5f) { return true; } return false; } bool CAScrollView::isScrollWindowNotMaxOutSide(const CCPoint& point) { CCSize size = this->getBounds().size; CCRect rect = m_pContainer->getFrame(); if (point.x - rect.size.width / 2 - maxBouncesLenght().x > 0) { return true; } if ((point.x + rect.size.width / 2 - size.width + maxBouncesLenght().x) < 0) { return true; } if (point.y - rect.size.height / 2 - maxBouncesLenght().y > 0) { return true; } if ((point.y + rect.size.height / 2 - size.height + maxBouncesLenght().y) < 0) { return true; } return false; } #pragma CAIndicator CAIndicator::CAIndicator(CAIndicatorType type) :m_pIndicator(NULL) ,m_eType(type) { } CAIndicator::~CAIndicator() { } void CAIndicator::onEnterTransitionDidFinish() { CAView::onEnterTransitionDidFinish(); } void CAIndicator::onExitTransitionDidStart() { CAView::onExitTransitionDidStart(); this->setAlpha(0.0f); } CAIndicator* CAIndicator::create(CAIndicatorType type) { CAIndicator* indicator = new CAIndicator(type); if (indicator && indicator->init()) { indicator->autorelease(); return indicator; } CC_SAFE_DELETE(indicator); return NULL; } bool CAIndicator::init() { if (!CAView::init()) { return false; } this->setColor(CAColor_clear); CAImage* image = CAImage::create("source_material/indicator.png"); m_pIndicator = CAScale9ImageView::createWithImage(image); this->addSubview(m_pIndicator); this->setAlpha(0.0f); return true; } void CAIndicator::setIndicator(const CCSize& parentSize, const CCRect& childrenFrame) { if ( !this->isVisible()) return; CAScale9ImageView* indicator = dynamic_cast<CAScale9ImageView*>(m_pIndicator); if (m_eType == CAIndicatorTypeHorizontal) { float size_scale_x = parentSize.width / childrenFrame.size.width; size_scale_x = MIN(size_scale_x, 1.0f); float lenght_scale_x = parentSize.width / 2 - childrenFrame.origin.x; lenght_scale_x /= childrenFrame.size.width; CCRect rect; rect.size = m_obContentSize; rect.size.width *= size_scale_x; if (lenght_scale_x < size_scale_x / 2) { rect.size.width *= lenght_scale_x / (size_scale_x / 2); } if (1 - lenght_scale_x < size_scale_x / 2) { rect.size.width *= (1 - lenght_scale_x) / (size_scale_x / 2); } rect.size.width = MAX(rect.size.height, rect.size.width); rect.origin = m_obContentSize; rect.origin.y *= 0.5f; rect.origin.x *= lenght_scale_x; rect.origin.x = MAX(rect.origin.x, rect.size.width/2); rect.origin.x = MIN(rect.origin.x, m_obContentSize.width - rect.size.width/2); indicator->setCenter(rect); } else if (m_eType == CAIndicatorTypeVertical) { float size_scale_y = parentSize.height / childrenFrame.size.height; size_scale_y = MIN(size_scale_y, 1.0f); float lenght_scale_y = parentSize.height / 2 - childrenFrame.origin.y; lenght_scale_y /= childrenFrame.size.height; CCRect rect; rect.size = m_obContentSize; rect.size.height *= size_scale_y; if (lenght_scale_y < size_scale_y / 2) { rect.size.height *= lenght_scale_y / (size_scale_y / 2); } if (1 - lenght_scale_y < size_scale_y / 2) { rect.size.height *= (1 - lenght_scale_y) / (size_scale_y / 2); } rect.size.height = MAX(rect.size.height, rect.size.width); rect.origin = m_obContentSize; rect.origin.x *= 0.5f; rect.origin.y *= lenght_scale_y; rect.origin.y = MAX(rect.origin.y, rect.size.height/2); rect.origin.y = MIN(rect.origin.y, m_obContentSize.height - rect.size.height/2); indicator->setCenter(rect); } } void CAIndicator::setHide(bool var) { CAScale9ImageView* indicator = dynamic_cast<CAScale9ImageView*>(m_pIndicator); if (var == false) { CC_RETURN_IF(fabs(1.0f-this->getAlpha()) < FLT_EPSILON); this->stopActionByTag(0xfff); this->setAlpha(1.0f); } else { CC_RETURN_IF(indicator->getActionByTag(0xfff)); CC_RETURN_IF(1.0f-this->getAlpha() > FLT_EPSILON); CCDelayTime* delayTime = CCDelayTime::create(0.2f); CCFadeOut* fadeOut = CCFadeOut::create(0.3f); CCEaseSineOut* easeSineOut = CCEaseSineOut::create(fadeOut); CCSequence* actions = CCSequence::create(delayTime, easeSineOut, NULL); actions->setTag(0xfff); this->runAction(actions); } } NS_CC_END
[ "278688386@qq.com" ]
278688386@qq.com
c434c9976278beb476cdddabb42797cf98e15829
456dd0729fb6f96c8e0ad74ccf3592853cfc4752
/XSAnalyseCheckServer/LogRecorder.h
d5326c693f2332b5f153bf33b99f9d527b9834c2
[]
no_license
chxj1980/FuZhou-AnalyseCheckpoint
15bc465a8141a50cb7910ac5fd53fbdbef901b8e
af61b8625bd0301a1bc0e254bd5de5807cb24bf8
refs/heads/master
2021-09-25T17:05:25.617940
2018-10-24T09:23:46
2018-10-24T09:23:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
h
#pragma once #include <log4cxx/log4cxx.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/logstring.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/loglog.h> #ifdef __WINDOWS__ #pragma comment( lib, "log4cxx_x64.lib" ) #endif using namespace std; using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; enum LoggerLevel{TRACELEVEL, DEBUGLEVEL, INFOLEVEL, WARNLEVEL, ERRORLEVEL, FATALLEVEL}; class CLogRecorder { public: CLogRecorder(void); ~CLogRecorder(void); public: bool InitLogger(const char * pszLogConfigPath, const char * pszLoggerName, const char * pszModuleName); void WriteLog(const char * pszFunction, const char * pszLogContent, LoggerLevel nLevel=INFOLEVEL); void WriteDebugLog(const char * pszFunction, const char * pszLogContent); void WriteInfoLog(const char * pszFunction, const char * pszLogContent); void WriteWarnLog(const char * pszFunction, const char * pszLogContent); void WriteErrorLog(const char * pszFunction, const char * pszLogContent); void WriteFatalLog(const char * pszFunction, const char * pszLogContent); void WriteLogEx(LoggerLevel nLevel, const char * pszFunction, const char * pszFormat, ...); void WriteDebugLogEx(const char * pszFunction,const char * pszFormat, ...); void WriteInfoLogEx(const char * pszFunction, const char * pszFormat, ...); void WriteWarnLogEx(const char * pszFunction, const char * pszFormat, ...); void WriteErrorLogEx(const char * pszFunction, const char * pszForamt, ...); void WriteFatalLogEx(const char * pszFunction, const char * pszFormat, ...); private: char m_szModuleName[64]; // Module Name LoggerPtr m_logger; };
[ "44406210+zoujfsysu@users.noreply.github.com" ]
44406210+zoujfsysu@users.noreply.github.com
8d4e7c0c909f9768cad96d11ad32b4dcb5b57a60
0cc5a3bdf5a4f1d5ffb9b7c38b6ee9ff4c1f49fd
/信息学奥赛一本通习题/基本算法/设置矩阵为零/源.cpp
c36b00615d2b2405fee0b2146612b41ecf318e32
[]
no_license
YiuWingTan/Algorithm
96631d25d7edb272d010bd31fc78c9953127dfc7
7c1711b8cd8284a2d1064df0c642cc81fe1a3a89
refs/heads/master
2022-04-08T11:29:36.935556
2020-03-16T13:18:48
2020-03-16T13:18:48
null
0
0
null
null
null
null
GB18030
C++
false
false
1,065
cpp
#include<iostream> #include<vector> using namespace std; void setZeroes(vector<vector<int>>& matrix) { bool set_row0 = false, set_col0 = false; int row = matrix.size(); int col = matrix[0].size(); for (int i = 0; i < row; i++) { if (matrix[i][0] == 0) { set_col0 = true; break; } } for (int j = 0; j < col; j++) { if (matrix[0][j] == 0) { set_row0 = true; break; } } for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } //行设置为0 for (int i = 1; i < row; i++) { if (matrix[i][0] == 0) { for (int j = 0; j < col; j++) { matrix[i][j] = 0; } } } //将一列设置为0 for (int j = 1; j < col; j++) { if (matrix[0][j] == 0) { for (int i = 0; i < row; i++) { matrix[i][j] = 0; } } } if (set_row0) { for (int j = 0; j < col; j++) matrix[0][j] = 0; } if (set_col0) { for (int i = 0; i < row; i++) matrix[i][0] = 0; } } int main() { getchar(); return 0; }
[ "33747232+yaorongtan@users.noreply.github.com" ]
33747232+yaorongtan@users.noreply.github.com
d548073d9d0e2efe2222db6b1cc4e5f3fdd9e00a
d4b4513c6314871a268ab97d0aece052a632d57d
/soft/server/src/pvp/item_operation.cpp
c0851fe949fd24ccf65333dc161e41556550dab1
[]
no_license
atom-chen/tssj
f99b87bcaa809a99e8af0e2ba388dbaac7156a31
f4345ad6b39f7f058fac987c2fed678d719a4482
refs/heads/master
2022-03-14T22:23:50.952836
2019-10-31T11:47:28
2019-10-31T11:47:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,092
cpp
#include "item_operation.h" #include "item_config.h" #include "item_def.h" #include "treasure_list.h" #define SHOP_REFRES_TIME 7200000 void ItemOperation::item_add_template(dhc::player_t *player, uint32_t item_id, int32_t item_amount, int mode) { s_t_item *t_item = sItemConfig->get_item(item_id); if (!t_item) { return; } bool flag = false; for (int i = 0; i < player->item_ids_size(); ++i) { if (player->item_ids(i) == item_id) { player->set_item_amount(i, player->item_amount(i) + item_amount); flag = true; break; } } if (!flag) { player->add_item_ids(item_id); player->add_item_amount(item_amount); } if (t_item->type == 6001) { sTreasureList->set_rob_player_list(player, item_id); } LOG_OUTPUT(player, LOG_ITEM, item_id, item_amount, mode, LOG_ADD); } int ItemOperation::item_num_templete(dhc::player_t *player, uint32_t item_id) { for (int i = 0; i < player->item_ids_size(); ++i) { if (player->item_ids(i) == item_id) { return player->item_amount(i); } } return 0; } void ItemOperation::item_destory_templete(dhc::player_t *player, uint32_t item_id, uint32_t item_amount, int mode) { int pos = -1; for (int i = 0; i < player->item_ids_size(); ++i) { if (player->item_ids(i) == item_id) { if (player->item_amount(i) > item_amount) { player->set_item_amount(i, player->item_amount(i) - item_amount); } else { pos = i; } break; } } if (pos != -1) { for (int i = pos; i < player->item_ids_size() - 1; ++i) { player->set_item_ids(i, player->item_ids(i + 1)); player->set_item_amount(i, player->item_amount(i + 1)); } player->mutable_item_ids()->RemoveLast(); player->mutable_item_amount()->RemoveLast(); } s_t_item *t_item = sItemConfig->get_item(item_id); if (t_item && t_item->type == 6001) { sTreasureList->set_rob_player_list(player, item_id); } if (mode != -1) { LOG_OUTPUT(player, LOG_ITEM, item_id, item_amount, mode, LOG_DEC); } } void ItemOperation::refresh_role_shop(dhc::player_t *player) { while (player->shop2_ids_size() < SHOP_NUM) { player->add_shop2_ids(0); player->add_shop2_sell(0); } std::vector<int> has_refreshs; for (int i = 0; i < SHOP_NUM; ++i) { s_t_shop *t_shop = 0; if (i == 0 || i == 1) { t_shop = sItemConfig->get_random_role_shop(player, 1, has_refreshs); } else { t_shop = sItemConfig->get_random_role_shop(player, 2, has_refreshs); } if (t_shop) { has_refreshs.push_back(t_shop->value1); player->set_shop2_ids(i, t_shop->id); player->set_shop2_sell(i, 0); } } } void ItemOperation::refresh_huiyi_shop(dhc::player_t *player) { player->clear_shop4_ids(); player->clear_shop4_sell(); const s_t_huiyi_shop* huiyi_shop = 0; std::set<int> has_refreshs; int geze = 0; for (int i = 0; i < SHOP_NUM; ++i) { geze = i + 1; if (geze > 4) { geze = 4; } huiyi_shop = sItemConfig->get_huiyi_shop_random(geze, has_refreshs); if (huiyi_shop) { player->add_shop4_ids(huiyi_shop->id); } else { player->add_shop4_ids(0); } player->add_shop4_sell(0); } } std::string ItemOperation::get_color(int color, const std::string &name) { if (color == 0) { return "[ffffff]" + name ; } else if (color == 1) { return "[5cf732]" + name ; } else if (color == 2) { return "[32eef7]" + name ; } else if (color == 3) { return "[ff3fbf]" + name ; } else if (color == 4) { return "[ee9900]" + name ; } else if (color == 5) { return "[ff0000]" + name ; } return name; } void ItemOperation::item_do_role_shop(dhc::player_t *player) { uint64_t now = game::timer()->now(); if (player->shop2_refresh_num() >= 10) { player->set_shop_last_time(now); return; } uint64_t dtime = now - player->shop_last_time(); if (dtime > SHOP_REFRES_TIME) { uint64_t num = dtime / SHOP_REFRES_TIME; if (num + player->shop2_refresh_num() > 10) { player->set_shop2_refresh_num(10); player->set_shop_last_time(now); } else { player->set_shop2_refresh_num(player->shop2_refresh_num() + num); player->set_shop_last_time(player->shop_last_time() + num * SHOP_REFRES_TIME); } } } void ItemOperation::refresh_guild_shop(dhc::guild_t* guild) { guild->clear_shop_ids(); guild->clear_shop_nums(); int id = 0; std::set<int> ids; for (int i = 0; i < SHOP_NUM; ++i) { if (i == 0 || i == 1) { id = sItemConfig->get_guild_shop_xs(1, guild->level(), ids); } else { id = sItemConfig->get_guild_shop_xs(2, guild->level(), ids); } ids.insert(id); guild->add_shop_ids(id); guild->add_shop_nums(0); } } void ItemOperation::refresh_guild_shop(dhc::player_t* player) { player->clear_shop1_ids(); player->clear_shop1_sell(); } int ItemOperation::get_guild_shop_buy_num(dhc::player_t* player, int id) { for (int i = 0; i < player->shop3_ids_size(); ++i) { if (player->shop3_ids(i) == id) { return player->shop3_sell(i); } } return 0; } void ItemOperation::add_guild_shop_buy_num(dhc::player_t* player, int id, int num) { bool has = false; for (int i = 0; i < player->shop3_ids_size(); ++i) { if (player->shop3_ids(i) == id) { player->set_shop3_sell(i, player->shop3_sell(i) + num); has = true; break; } } if (!has) { player->add_shop3_ids(id); player->add_shop3_sell(num); } } int ItemOperation::get_huiyi_luckshop_buy_num(dhc::player_t* player, int id) { for (int i = 0; i < player->huiyi_shop_ids_size(); ++i) { if (player->huiyi_shop_ids(i) == id) { return player->huiyi_shop_nums(i); } } return 0; } void ItemOperation::add_huiyi_luckshop_buy_num(dhc::player_t* player, int id, int num) { bool has = false; for (int i = 0; i < player->huiyi_shop_ids_size(); ++i) { if (player->huiyi_shop_ids(i) == id) { player->set_huiyi_shop_nums(i, player->huiyi_shop_nums(i) + num); has = true; break; } } if (!has) { player->add_huiyi_shop_ids(id); player->add_huiyi_shop_nums(num); } } void ItemOperation::do_pet_shop(dhc::player_t *player) { uint64_t now = game::timer()->now(); if (player->shoppet_refresh_num() >= 10) { player->set_shoppet_last_time(now); return; } uint64_t dtime = now - player->shoppet_last_time(); if (dtime > SHOP_REFRES_TIME) { uint64_t num = dtime / SHOP_REFRES_TIME; if (num + player->shoppet_refresh_num() > 10) { player->set_shoppet_refresh_num(10); player->set_shoppet_last_time(now); } else { player->set_shoppet_refresh_num(player->shoppet_refresh_num() + num); player->set_shoppet_last_time(player->shoppet_last_time() + num * SHOP_REFRES_TIME); } } } void ItemOperation::refresh_pet_shop(dhc::player_t *player) { while (player->shoppet_ids_size() < SHOP_NUM) { player->add_shoppet_ids(0); player->add_shoppet_sell(0); } std::set<int> has_refreshs; const s_t_chongwu_shop *t_shop = 0; for (int i = 0; i < SHOP_NUM; ++i) { t_shop = sItemConfig->get_chongwu_shop_random(i + 1, player->level(), has_refreshs); if (t_shop) { has_refreshs.insert(t_shop->value1); player->set_shoppet_ids(i, t_shop->id); player->set_shoppet_sell(i, 0); } } }
[ "rocketxyfb@163.com" ]
rocketxyfb@163.com
d0a93011b79db3a1135934b0be3313e57e25f4cf
b19a9057ad64063cf7f58249a52dec39fbac3d5b
/vtk/vtk_anim.cc
0db7058240d2570847868322e7edb5fa0e65b6a4
[]
no_license
cpraveen/cfdlab
b0c8ebc1fac781dde0380162b4616182621bce1f
b5564e4f5923f1c04a8b1594d882338cc323aeca
refs/heads/master
2023-08-22T07:17:14.953155
2023-08-19T11:15:32
2023-08-19T11:15:32
34,105,489
27
17
null
2016-09-27T21:55:17
2015-04-17T08:32:34
Jupyter Notebook
UTF-8
C++
false
false
3,295
cc
#include <iostream> #include <fstream> #include <cmath> #include <string> using namespace std; // Ex: get_filename("sol_",3,42) should return "sol_042.vtk" string get_filename(const string base_name, const int ndigits, const int c) { if(c > pow(10,ndigits)-1) { cout << "get_filename: Not enough digits !!!\n"; cout << "ndigits= " << ndigits << endl; cout << "c = " << c << endl; exit(0); } string name = base_name; // first pad with zeros int d = 1; if(c > 0) d = int(floor(log10(c))) + 1; for(int i=0; i<ndigits-d; ++i) name += "0"; name += to_string(c) + ".vtk"; return name; } void write_rectilinear_grid(int nx, int ny, double *x, double *y, double **var, double t, int c, string filename) { int nz = 1; // We have a 2d grid ofstream fout; fout.open(filename); fout << "# vtk DataFile Version 3.0" << endl; fout << "Cartesian grid" << endl; fout << "ASCII" << endl; fout << "DATASET RECTILINEAR_GRID" << endl; fout << "FIELD FieldData 2" << endl; fout << "TIME 1 1 double" << endl; fout << t << endl; fout << "CYCLE 1 1 int" << endl; fout << c << endl; fout << "DIMENSIONS " << nx << " " << ny << " " << nz << endl; fout << "X_COORDINATES " << nx << " float" << endl; for(int i=0; i<nx; ++i) fout << x[i] << " "; fout << endl; fout << "Y_COORDINATES " << ny << " float" << endl; for(int j=0; j<ny; ++j) fout << y[j] << " "; fout << endl; fout << "Z_COORDINATES " << nz << " float" << endl; fout << 0.0 << endl; fout << "POINT_DATA " << nx*ny*nz << endl; fout << "SCALARS density float" << endl; fout << "LOOKUP_TABLE default" << endl; // no need for k-loop since nk=1 for(int j=0; j<ny; ++j) { for(int i=0; i<nx; ++i) fout << var[i][j] << " "; fout << endl; } fout.close(); cout << "Wrote Cartesian grid into " << filename << endl; } int main() { cout << "Saving rectilinear grid\n"; const int nx = 100, ny = 50; const double xmin = 0.0, xmax = 2.0; const double ymin = 0.0, ymax = 1.0; const double dx = (xmax-xmin)/(nx-1); const double dy = (ymax-ymin)/(ny-1); double *x, *y, **var; x = new double[nx]; y = new double[ny]; for(int i=0; i<nx; ++i) x[i] = xmin + i*dx; for(int j=0; j<ny; ++j) y[j] = ymin + j*dy; var = new double*[nx]; for(int i=0; i<nx; ++i) var[i] = new double[ny]; double u = 1.0, v = 1.0; double t = 0.0, dt = 0.1, Tf = 10.0; int c = 0; while(t < Tf) { for(int i=0; i<nx; ++i) for(int j=0; j<ny; ++j) { double xx = x[i] - u*t; double yy = y[j] - v*t; var[i][j] = sin(2.0*M_PI*xx) * sin(2.0*M_PI*yy); } string filename = get_filename("sol_",3,c); write_rectilinear_grid(nx, ny, x, y, var, t, c, filename); t += dt; ++c; } // Deallocate memory here delete[] x; delete[] y; for(int i=0; i<nx; ++i) delete[] var[i]; delete[] var; return 0; }
[ "cpraveen@gmail.com" ]
cpraveen@gmail.com
bb473442d256651d04c02daaf31d0e952e3fa896
0a5645154953b0a09d3f78753a1711aaa76928ff
/common/c/abpal/src/winmobile/gps/lpsgpsid.h
7a8f38783d672a5ebda885150646d710df030960
[]
no_license
GENIVI/navigation-next
3a6f26063350ac8862b4d0e2e9d3522f6f249328
cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36
refs/heads/master
2023-08-04T17:44:45.239062
2023-07-25T19:22:19
2023-07-25T19:22:19
116,230,587
17
11
null
2018-05-18T20:00:38
2018-01-04T07:43:22
C++
UTF-8
C++
false
false
5,517
h
/* Copyright (c) 2018, TeleCommunication Systems, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the TeleCommunication Systems, Inc., nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL TELECOMMUNICATION SYSTEMS, INC.BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*!-------------------------------------------------------------------------- @file lpsgpsid.h */ /* (C) Copyright 2014 by TeleCommunication Systems, Inc. The information contained herein is confidential, proprietary to TeleCommunication Systems, Inc., and considered a trade secret as defined in section 499C of the penal code of the State of California. Use of this information by anyone other than authorized employees of TeleCommunication Systems is granted only under a written non-disclosure agreement, expressly prescribing the scope and manner of such use. ---------------------------------------------------------------------------*/ /*! @addtogroup abpalgpswinmobile @{ */ #pragma once #include <map> #include <string> #include "locationprovider.h" #include "lbsdriver.h" typedef struct _GPS_POSITION GPS_POSITION; typedef struct _GPS_DEVICE GPS_DEVICE; // Needed to load procs dynamically typedef HANDLE (WINAPI *LPSGPSID_OpenDevice)(HANDLE, HANDLE, const WCHAR *, DWORD); typedef DWORD (WINAPI *LPSGPSID_GetPosition)(HANDLE, GPS_POSITION *, DWORD, DWORD); typedef DWORD (WINAPI *LPSGPSID_GetDeviceState)(HANDLE, GPS_DEVICE *); typedef DWORD (WINAPI *LPSGPSID_CloseDevice)(HANDLE); typedef DWORD (WINAPI *LPSGPSID_GetDeviceParam)(HANDLE, DWORD , BYTE* , DWORD*); typedef DWORD (WINAPI *LPSGPSID_SetDeviceParam)(HANDLE, DWORD , BYTE* , DWORD); #define LPSGPS_ROAMING_MODE_ALL L"all" #define LPSGPS_ROAMING_MODE_MSA L"MSA" #define LPSGPS_ROAMING_MODE_MSB L"MSB" #define LPSGPS_ROAMING_MODE_MSS L"MSS" class LpsGpsId : public LocationProvider { public: LpsGpsId(GpsContext* gpsContext, std::map<std::string, std::wstring> parameters); virtual ~LpsGpsId(); /* Update listeners requested parameters */ virtual void UpdateFixRequestParameters(bool listenersPresent, uint32 lowestCommonInterval, uint32 lowestCommonAccuracy); protected: virtual PAL_Error CreateInstance(); virtual PAL_Error DestroyInstance(); HANDLE m_gpsDevice; HMODULE m_gpsapiDll; HANDLE m_gpsidNewLocationAvailable; HANDLE m_gpsidDeviceStateChanged; HANDLE m_gpsidFixRequestParametersChanged; LPSGPSID_OpenDevice m_pGpsOpenDevice; LPSGPSID_GetPosition m_pGpsGetPosition; LPSGPSID_GetDeviceState m_pGpsGetDeviceState; LPSGPSID_CloseDevice m_pGpsCloseDevice; LPSGPSID_GetDeviceParam m_pGpsGetDeviceParam; LPSGPSID_SetDeviceParam m_pGpsSetDeviceParam; CRITICAL_SECTION m_fixParametersLock; uint16 m_fixInterval; uint16 m_fixAccuracy; DWORD m_inactivityTimeout; private: DWORD LoadDriver(); void UnloadDriver(); DWORD OpenDevice(); void CloseDevice(); void LockFixParameters() { EnterCriticalSection(&m_fixParametersLock); }; void UnlockFixParameters() { LeaveCriticalSection(&m_fixParametersLock); }; void RequestNextFix(bool& rFixQueryPending, uint32& rFixCount); DWORD RestartDevice(bool& rGpsServiceInitialized, bool& rFixQueryPending, uint32& rFixCount); DWORD SetMode(DWORD mode); DWORD SetQOS(DWORD dwAccuracy, DWORD dwPerformance); DWORD SetFixRate(WORD wNumberOfFixes, WORD wDelayBetweenFixes); void TranslateGpsPosition(const GPS_POSITION& rGpsPosition, Location& rLocation); PAL_Error TranslateGpsError(DWORD gpsError); GPS_MODE GetRoamingGpsMode(GPS_MODE requestedMode); DWORD AcquisitionThreadProc(); std::map<std::string, std::wstring> m_parameters; }; /*! @} */
[ "caavula@telecomsys.com" ]
caavula@telecomsys.com
851ff74e563b40172ca18ccf471ec4d8ca8f03f2
92640ec261e7875a5e65e95d6408be2df3cdd9a3
/japan/Domestic 2003/1005.cpp
279b5a13f14e7a41eabb51d69b23cb87a955d766
[]
no_license
gaolichen/contest
c20c79d1a05ea6c015329bc2068a3bbb946de775
4ac5112f150210c6345312922dc96494327cbf55
refs/heads/master
2021-01-19T04:45:59.100014
2017-04-06T06:46:09
2017-04-06T06:46:09
87,392,728
0
0
null
null
null
null
UTF-8
C++
false
false
4,923
cpp
#define WIN32 #ifdef WIN32 # pragma warning(disable:4786) #define for if(0);else for #endif #include <iostream> #include <vector> #include <string> #include <deque> #include <map> #include <set> #include <list> #include <algorithm> #include <utility> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <sstream> using namespace std; //64 bit integer definition #ifdef WIN32 #define in_routine(type,spec) \ istream& operator>>(istream& s,type &d){char b[30];s>>b;sscanf(b,spec,&d);return s;} #define out_routine(type,spec) \ ostream& operator<<(ostream& s,type d){char b[30];sprintf(b,spec,d);s<<b;return s;} typedef signed __int64 i64; in_routine(i64,"%I64d") out_routine(i64,"%I64d") typedef unsigned __int64 u64; in_routine(u64,"%I64u") out_routine(u64,"%I64u") #else typedef signed long long i64; typedef unsigned long long u64; #endif //common routines #ifdef WIN32 #define min(a,b) _cpp_min(a,b) #define max(a,b) _cpp_max(a,b) #endif #define abs(a) ((a)>0?(a):-(a)) #define mit(a,b) map<a,b>::iterator #define fr(a,b) for(int a=0;a<(b);a++) #define all(a) a.begin(),a.end() #define inmat(i,j,m,n) ((i)>=0&&(i)<(m)&&(j)>=0&&(j)<(n)) #define cls(a) memset((a),0,sizeof(a)) #define isCap(a) ((a)>='A'&&(a)<='Z') #define isLow(a) ((a)>='a'&&(a)<='z') #define inf 2100000000 #define eps 1e-8 typedef istringstream iss; typedef ostringstream oss; typedef vector<int> VI; typedef vector<vector<int> > VVI; typedef vector<i64> V64; typedef vector<vector<i64> > VV64; typedef vector<string> VS; typedef vector<vector<string> > VVS; typedef vector<double> VD; typedef vector<vector<double> > VVD; int mx[8]={0,1,0,-1,1,1,-1,-1}; int my[8]={1,0,-1,0,1,-1,-1,1}; template <class T> T gcd(T a,T b){for(T c;b;c=a,a=b,b=c%b);return a;} template <class T> T lcm(T a,T b){return a/gcd(a,b)*b;} template <class T> void remove(vector<T>&v,const T&e){ v.resize(remove(v.begin(),v.end(),e)-v.begin()); } template <class T> void insert(vector<T>&v,int isnum,const T&e){ v.resize(v.size()+1); for(int i=v.size()-1;i>isnum;v[i--]=v[i-1]); v[isnum]=e; } void insert(string &s,int isnum,const string&is){ string t=s;s.resize(isnum);s+=is+(t.c_str()+isnum); } //output routine ostream& operator<<(ostream& s,string d){ s<<'\"'<<d.c_str()<<'\"'; return s; } template <class T> ostream& operator<<(ostream& s,vector<T> d){ s<<"{"; for (typename vector<T>::iterator i=d.begin();i!=d.end();i++) s<<(i!=d.begin()?",":"")<<*i; s<<"}"; s<<endl; return s; } //parsing routine template <class T> vector<basic_string<T> > parse(const basic_string<T> &s,const basic_string<T> &delim){ vector<basic_string<T> > ret(0); for (int b,e=0;;ret.push_back(s.substr(b,e-b))) if ((b=s.find_first_not_of(delim,e))==(e=s.find_first_of(delim,b))) return ret; } VVI mat,rec; int w,h; char mark[11000]; int ret; int searchCnt; struct NODE { int x,y,a; bool operator<(const NODE & t)const { if(a!=t.a)return a>t.a; if(x!=t.x)return x>t.x; return y>t.y; } }; vector<NODE > vn1,vn; vector< vector< vector<int > > > rect; NODE sn[200],tsn[200]; void dfs(int x,int y,int ans){ if(searchCnt>100000)return ; if(ans>=ret)return ; if(x>=h){ ret=ans; // cout<<ret<<' '<<searchCnt<<endl; return ; } if(y>=w){ dfs(x+1,0,ans);return ; } if(mat[x][y]!=1){ dfs(x,y+1,ans); return ; } searchCnt++; fr(i,rect[x][y].size())if(!mark[rect[x][y][i]]){ NODE tmp=vn[rect[x][y][i]]; mark[rect[x][y][i]]=1; for(int j=tmp.x;j<tmp.x+tmp.a;j++) for(int k=tmp.y;k<tmp.y+tmp.a;k++) mat[j][k]++; dfs(x,y+1,ans+1); mark[rect[x][y][i]]=0; for(int j=tmp.x;j<tmp.x+tmp.a;j++) for(int k=tmp.y;k<tmp.y+tmp.a;k++) mat[j][k]--; } } int calc(int x,int y){ for(int i=1;i+x<=h&&i+y<=w;i++){ for(int j=x;j<x+i;j++)for(int k=y;k<y+i;k++)if(!mat[j][k])return i-1; } return min(h-x,w-y); } int contain(NODE &n1,NODE &n2){ if(n2.x>=n1.x&&n2.x<n1.x+n1.a&& n2.y>=n1.y&&n2.y<n1.y+n1.a&& n2.x+n2.a>=n1.x&&n2.x+n2.a<=n1.x+n1.a&& n2.y+n2.a>=n1.y&&n2.y+n2.a<=n1.y+n1.a)return 1; return 0; } void run(){ ret=inf; vn1.clear();vn.clear();rect.clear(); for(int i=0;i<h;i++)for(int j=0;j<w;j++)if(mat[i][j]){ NODE tmp; tmp.x=i;tmp.y=j; tmp.a=calc(i,j); vn1.push_back(tmp); } fr(i,vn1.size()){ int flag=1; fr(j,vn1.size())if(i!=j&&contain(vn1[j],vn1[i])){flag=0;break;} if(flag)vn.push_back(vn1[i]); } sort(all(vn)); // fr(i,vn.size())cout<<vn[i].x<<' '<<vn[i].y<<' '<<vn[i].a<<endl; // cout<<endl; rect.resize(h,vector<vector<int > >(w)); fr(i,vn.size()){ for(int j=vn[i].x;j<vn[i].x+vn[i].a;j++) for(int k=vn[i].y;k<vn[i].y+vn[i].a;k++) rect[j][k].push_back(i); } cls(mark); // fr(i,h){cout<<endl;fr(j,w)cout<<rect[i][j].size()<<' ';} // fr(i,h)fr(j,w)sort(all(rect[i][j])); searchCnt=0; dfs(0,0,0); cout<<ret<<endl; } int main(){ while(cin>>w>>h){ if(!w&&!h)break; mat.resize(h); fr(i,h)mat[i].resize(w); fr(i,h)fr(j,w)cin>>mat[i][j]; run(); } return 0; }
[ "gchen@ufl.edu" ]
gchen@ufl.edu
7d63a7aa55d8357214e960adc6c832d8b3095daf
8f1c5fc3ff04b78005fb0f797193bd49f5d0721a
/src/compiler/node-cache.cc
7cda167bac91dc153ee3a55425d8a7ffd001edd0
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
btongminh/android_v8
91011c50e289a29847683479e71b73e94578e5bf
92b03b37ca04c6812fe2eaf6df82e9e1ef564c63
refs/heads/lxss
2022-10-28T20:56:59.348747
2016-12-23T15:18:52
2016-12-23T15:18:52
77,245,772
0
2
NOASSERTION
2022-10-06T05:33:38
2016-12-23T19:12:56
null
UTF-8
C++
false
false
3,036
cc
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/node-cache.h" namespace v8 { namespace internal { namespace compiler { #define INITIAL_SIZE 16 #define LINEAR_PROBE 5 template <typename Key> int32_t NodeCacheHash(Key key) { UNIMPLEMENTED(); return 0; } template <> inline int32_t NodeCacheHash(int32_t key) { return ComputeIntegerHash(key, 0); } template <> inline int32_t NodeCacheHash(int64_t key) { return ComputeLongHash(key); } template <> inline int32_t NodeCacheHash(double key) { return ComputeLongHash(bit_cast<int64_t>(key)); } template <> inline int32_t NodeCacheHash(void* key) { return ComputePointerHash(key); } template <typename Key> bool NodeCache<Key>::Resize(Zone* zone) { if (size_ >= max_) return false; // Don't grow past the maximum size. // Allocate a new block of entries 4x the size. Entry* old_entries = entries_; int old_size = size_ + LINEAR_PROBE; size_ = size_ * 4; int num_entries = size_ + LINEAR_PROBE; entries_ = zone->NewArray<Entry>(num_entries); memset(entries_, 0, sizeof(Entry) * num_entries); // Insert the old entries into the new block. for (int i = 0; i < old_size; i++) { Entry* old = &old_entries[i]; if (old->value_ != NULL) { int hash = NodeCacheHash(old->key_); int start = hash & (size_ - 1); int end = start + LINEAR_PROBE; for (int j = start; j < end; j++) { Entry* entry = &entries_[j]; if (entry->value_ == NULL) { entry->key_ = old->key_; entry->value_ = old->value_; break; } } } } return true; } template <typename Key> Node** NodeCache<Key>::Find(Zone* zone, Key key) { int32_t hash = NodeCacheHash(key); if (entries_ == NULL) { // Allocate the initial entries and insert the first entry. int num_entries = INITIAL_SIZE + LINEAR_PROBE; entries_ = zone->NewArray<Entry>(num_entries); size_ = INITIAL_SIZE; memset(entries_, 0, sizeof(Entry) * num_entries); Entry* entry = &entries_[hash & (INITIAL_SIZE - 1)]; entry->key_ = key; return &entry->value_; } while (true) { // Search up to N entries after (linear probing). int start = hash & (size_ - 1); int end = start + LINEAR_PROBE; for (int i = start; i < end; i++) { Entry* entry = &entries_[i]; if (entry->key_ == key) return &entry->value_; if (entry->value_ == NULL) { entry->key_ = key; return &entry->value_; } } if (!Resize(zone)) break; // Don't grow past the maximum size. } // If resized to maximum and still didn't find space, overwrite an entry. Entry* entry = &entries_[hash & (size_ - 1)]; entry->key_ = key; entry->value_ = NULL; return &entry->value_; } template class NodeCache<int64_t>; template class NodeCache<int32_t>; template class NodeCache<void*>; } } } // namespace v8::internal::compiler
[ "benm@google.com" ]
benm@google.com
2b67a59a0daaa062c22c4dcc3a326c8698fd2419
c6b483cc2d7bc9eb6dc5c08ae92aa55ff9b3a994
/hazelcast/generated-sources/src/hazelcast/client/protocol/codec/ListCompareAndRemoveAllCodec.cpp
277ec9c1f05304be924baa7abaec0ed0b1f432c9
[ "Apache-2.0" ]
permissive
oguzdemir/hazelcast-cpp-client
ebffc7137a3a14b9fc5d96e1a1b0eac8aac1e60f
95c4687634a8ac4886d0a9b9b4c17622225261f0
refs/heads/master
2021-01-21T02:53:05.197319
2016-08-24T21:08:14
2016-08-24T21:08:14
63,674,978
0
0
null
2016-07-19T08:16:24
2016-07-19T08:16:23
null
UTF-8
C++
false
false
3,716
cpp
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hazelcast/client/protocol/codec/ListCompareAndRemoveAllCodec.h" #include "hazelcast/client/exception/UnexpectedMessageTypeException.h" #include "hazelcast/client/serialization/pimpl/Data.h" namespace hazelcast { namespace client { namespace protocol { namespace codec { const ListMessageType ListCompareAndRemoveAllCodec::RequestParameters::TYPE = HZ_LIST_COMPAREANDREMOVEALL; const bool ListCompareAndRemoveAllCodec::RequestParameters::RETRYABLE = false; const int32_t ListCompareAndRemoveAllCodec::ResponseParameters::TYPE = 101; std::auto_ptr<ClientMessage> ListCompareAndRemoveAllCodec::RequestParameters::encode( const std::string &name, const std::vector<serialization::pimpl::Data > &values) { int32_t requiredDataSize = calculateDataSize(name, values); std::auto_ptr<ClientMessage> clientMessage = ClientMessage::createForEncode(requiredDataSize); clientMessage->setMessageType((uint16_t)ListCompareAndRemoveAllCodec::RequestParameters::TYPE); clientMessage->setRetryable(RETRYABLE); clientMessage->set(name); clientMessage->setArray<serialization::pimpl::Data >(values); clientMessage->updateFrameLength(); return clientMessage; } int32_t ListCompareAndRemoveAllCodec::RequestParameters::calculateDataSize( const std::string &name, const std::vector<serialization::pimpl::Data > &values) { int32_t dataSize = ClientMessage::HEADER_SIZE; dataSize += ClientMessage::calculateDataSize(name); dataSize += ClientMessage::calculateDataSize<serialization::pimpl::Data >(values); return dataSize; } ListCompareAndRemoveAllCodec::ResponseParameters::ResponseParameters(ClientMessage &clientMessage) { if (TYPE != clientMessage.getMessageType()) { throw exception::UnexpectedMessageTypeException("ListCompareAndRemoveAllCodec::ResponseParameters::decode", clientMessage.getMessageType(), TYPE); } response = clientMessage.get<bool >(); } ListCompareAndRemoveAllCodec::ResponseParameters ListCompareAndRemoveAllCodec::ResponseParameters::decode(ClientMessage &clientMessage) { return ListCompareAndRemoveAllCodec::ResponseParameters(clientMessage); } ListCompareAndRemoveAllCodec::ResponseParameters::ResponseParameters(const ListCompareAndRemoveAllCodec::ResponseParameters &rhs) { response = rhs.response; } //************************ EVENTS END **************************************************************************// } } } }
[ "ihsan@hazelcast.com" ]
ihsan@hazelcast.com
1d044f6d6be0d417bbe8ba401909910135a9e3ed
5a44eac7ce27893035604c412412b71a7cccb343
/hardware/arm/Nuvoton/libraries/FreeRTOS/examples/FreeRTOSBookExamples/Example013/Example013.ino
6e18b2f7648a2311b613b450a09fc71a610c3a7c
[]
no_license
huaweiwx/ARDUINO_Nuvoton
d0e3b6e95eb35f508aad925afa814ff13e0978e4
e4a8b841c4027bde715c34f2745b23593c590b5d
refs/heads/master
2020-04-05T12:44:29.382129
2019-04-03T12:18:02
2019-04-03T12:18:02
156,878,513
8
2
null
null
null
null
UTF-8
C++
false
false
7,525
ino
/* Example 13. Using a Counting Semaphore to Synchronize a Task with an Interrupt 使用计数信号量将任务与中断同步 FreeRTOS.org V9.0.0 - Copyright (C) 2003-2017 Richard Barry. This file is part of the FreeRTOS.org distribution. FreeRTOS.org is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FreeRTOS.org is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA A special exception to the GPL can be applied should you wish to distribute a combined work that includes FreeRTOS.org, without being obliged to provide the source code for any proprietary components. See the licensing section of http://www.FreeRTOS.org for full details of how and when the exception can be applied. */ #include "FreeRTOS.h" /* The tasks to be created. */ static void vHandlerTask( void *pvParameters ); static void vPeriodicTask( void *pvParameters ); /* The service routine for the interrupt. This is the interrupt that the task will be synchronized with. */ static void vExampleInterruptHandler( void ); /*-----------------------------------------------------------*/ /* Declare a variable of type SemaphoreHandle_t. This is used to reference the semaphore that is used to synchronize a task with an interrupt. */ SemaphoreHandle_t xCountingSemaphore; // pins to generate interrupts - they must be connected const uint8_t inputPin = PB6; const uint8_t outputPin = PB8; void setup( void ) { Serial.begin(115200); /*set param: 115200bps 8N1 (default 115200bps 8N1) */ /* Before a semaphore is used it must be explicitly created. In this example a counting semaphore is created. The semaphore is created to have a maximum count value of 10, and an initial count value of 0. */ xCountingSemaphore = xSemaphoreCreateCounting( 10, 0 ); /* Check the semaphore was created successfully. */ if( xCountingSemaphore != NULL ) { /* Create the 'handler' task. This is the task that will be synchronized with the interrupt. The handler task is created with a high priority to ensure it runs immediately after the interrupt exits. In this case a priority of 3 is chosen. */ xTaskCreate( vHandlerTask, "Handler", 200, NULL, 3, NULL ); /* Create the task that will periodically generate a software interrupt. This is created with a priority below the handler task to ensure it will get preempted each time the handler task exist the Blocked state. */ xTaskCreate( vPeriodicTask, "Periodic", 200, NULL, 1, NULL ); /* Install the interrupt handler. */ pinMode(inputPin, INPUT); pinMode(outputPin, OUTPUT); digitalWrite(outputPin, HIGH); bool tmp = digitalRead(inputPin); digitalWrite(outputPin, LOW); if (digitalRead(inputPin) || !tmp) { Serial.println("inputpin must be connected to outputpin"); while(1); } attachInterrupt(inputPin, vExampleInterruptHandler, RISING); /* Start the scheduler so the created tasks start executing. */ vTaskStartScheduler(); } /* If all is well we will never reach here as the scheduler will now be running the tasks. If we do reach here then it is likely that there was insufficient heap memory available for a resource to be created. */ for( ;; ); } /*-----------------------------------------------------------*/ static void vHandlerTask( void *pvParameters ) { /* As per most tasks, this task is implemented within an infinite loop. */ for( ;; ) { /* Use the semaphore to wait for the event. The semaphore was created before the scheduler was started so before this task ran for the first time. The task blocks indefinitely meaning this function call will only return once the semaphore has been successfully obtained - so there is no need to check the returned value. */ xSemaphoreTake( xCountingSemaphore, portMAX_DELAY ); /* To get here the event must have occurred. Process the event (in this case we just print out a message). */ vPrintString( "Handler task - Processing event.\r\n" ); } } /*-----------------------------------------------------------*/ static void vPeriodicTask( void *pvParameters ) { /* As per most tasks, this task is implemented within an infinite loop. */ for( ;; ) { /* This task is just used to 'simulate' an interrupt. This is done by periodically generating a software interrupt. */ vTaskDelay( 500 / portTICK_PERIOD_MS ); /* Generate the interrupt, printing a message both before hand and afterwards so the sequence of execution is evident from the output. */ vPrintString( "Perodic task - About to generate an interrupt.\r\n" ); // __asm{ int 0x82 } digitalWrite(outputPin, LOW); digitalWrite(outputPin, HIGH); vPrintString( "Periodic task - Interrupt generated.\r\n\r\n\r\n" ); } } /*-----------------------------------------------------------*/ static void vExampleInterruptHandler( void ) { static portBASE_TYPE xHigherPriorityTaskWoken; xHigherPriorityTaskWoken = pdFALSE; /* 'Give' the semaphore multiple times. The first will unblock the handler task, the following 'gives' are to demonstrate that the semaphore latches the events to allow the handler task to process them in turn without any events getting lost. This simulates multiple interrupts being taken by the processor, even though in this case the events are simulated within a single interrupt occurrence.*/ xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken ); xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken ); xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken ); /* xHigherPriorityTaskWoken was initialised to pdFALSE. It will have then been set to pdTRUE only if reading from or writing to a queue caused a task of equal or greater priority than the currently executing task to leave the Blocked state. When this is the case a context switch should be performed. In all other cases a context switch is not necessary. NOTE: The syntax for forcing a context switch within an ISR varies between FreeRTOS ports. The portEND_SWITCHING_ISR() macro is provided as part of the Cortex-M3 port layer for this purpose. taskYIELD() must never be called from an ISR! */ portEND_SWITCHING_ISR( xHigherPriorityTaskWoken ); } /**************** default idle hook callback if configUSE_IDLE_HOOK *************************** * 1 NUVOTON loop() is call by default idle hook if enable(set configUSE_IDLE_HOOK to 1) * * 2 Idle loop has a very small stack (check or set configMINIMAL_STACK_SIZE) * * 3 Loop must never block. * * 4 This default idle hook can be overload by vApplicationIdleHook() * ***********************************************************************************************/ void loop() { for(;;){} //This example Not used. }
[ "huaweiwx@sina.com" ]
huaweiwx@sina.com
bc7c00d68eb6c512354a33740022ef3c6d8939b2
54a07fd33c86d0aff21a73a4a3b30596937a29de
/FileWatcherDemo/file_activity/idirectory_watcher.h
1a3c565ba7ab60f43a4c5401bd6246a3977f2aaf
[ "BSL-1.0" ]
permissive
pvthuyet/file-watcher-demo
739ed241eb3333cd092616be4c32944ea1c61a76
37fb2022fb27952db294b253fe2817d4548817bc
refs/heads/main
2023-02-08T06:18:21.783014
2021-01-03T01:33:05
2021-01-03T01:33:05
323,820,493
0
0
null
null
null
null
UTF-8
C++
false
false
326
h
#pragma once #include "file_notify_info.h" #include <memory> namespace died { class idirectory_watcher { public: virtual ~idirectory_watcher() noexcept = default; void notify(file_notify_info&& info) { filter_notify(std::move(info)); } private: virtual void filter_notify(file_notify_info info) = 0; }; }
[ "pvthuyet@gmail.com" ]
pvthuyet@gmail.com
42b1208734e610331b652a2d47070ab1d82da180
bdcb3ddb9c9f5226e6a1581861bab1fadac30f5e
/src/core/API.h
b1b01a66f768c8386fd75a7cfbb3ab84219eefe4
[ "MIT" ]
permissive
bacahillsmu/benbot
fdcc33de59f03a3ae2e5e7a0fb2b60564ae3ebb3
f6eeadac99690c5c2a5575d8c0d661e6bed3b604
refs/heads/master
2021-07-13T09:26:52.583365
2019-12-20T20:40:24
2019-12-20T20:40:24
210,927,936
0
0
null
null
null
null
UTF-8
C++
false
false
7,495
h
// The MIT License (MIT) // // Copyright (c) 2017-2019 Alexander Kurbatov #pragma once #include "Order.h" #include "WrappedUnits.hpp" #include <sc2api/sc2_control_interfaces.h> #include <sc2api/sc2_gametypes.h> #include <sc2api/sc2_interfaces.h> #include <sc2api/sc2_score.h> #include <memory> #include <set> namespace API { constexpr float OrbitalScanCost = 50.0f; constexpr float OrbitalMuleCost = 50.0f; constexpr float OrbitalScanRadius = 12.3f; typedef std::function<bool(const WrappedUnit* unit)> Filter; // ---------------------------------------------------------------------------- // Action; // ---------------------------------------------------------------------------- struct Action { explicit Action(sc2::ActionInterface* action_); void Build(const Order& order_); void Build(const Order& order_, const WrappedUnit* unit_); void Build(const Order& order_, const sc2::Point2D& point_); void Attack(const WrappedUnits& units_, const sc2::Point2D& point_); void Attack(const WrappedUnit& unit_, const WrappedUnit& target_); void Attack(const WrappedUnit& unit_, const sc2::Point2D& point_); void MoveTo(const WrappedUnit& unit_, const sc2::Point2D& point_); void MoveTo(const WrappedUnits& units_, const sc2::Point2D& point_); void Cast(const WrappedUnit& assignee_, sc2::ABILITY_ID ability_); void Cast(const WrappedUnit& assignee_, sc2::ABILITY_ID ability_, const WrappedUnit& target_); void Cast(const WrappedUnit& assignee_, sc2::ABILITY_ID ability_, const sc2::Point2D& point_); void Stop(const WrappedUnit& unit_, bool queue_ = false); void Stop(const WrappedUnits& units_, bool queue_ = false); void Cancel(const WrappedUnit& assignee_); void CancelConstruction(const WrappedUnit& assignee_); void OpenGate(const WrappedUnit& assignee_); void SendMessage(const std::string& text_); private: sc2::ActionInterface* m_action; }; // ---------------------------------------------------------------------------- // Control; // ---------------------------------------------------------------------------- struct Control { explicit Control(sc2::ControlInterface* control_); void SaveReplay(); private: sc2::ControlInterface* m_control; }; // ---------------------------------------------------------------------------- // Debug; // ---------------------------------------------------------------------------- struct Debug { explicit Debug(sc2::DebugInterface* debug_); void DrawText(const std::string& message_) const; void DrawText(const std::string& message_, const sc2::Point2D& point_) const; void DrawText(const std::string& message_, const sc2::Point2DI& point_) const; void DrawText(float value_, const sc2::Point2DI& point_) const; void DrawText(const std::string& message_, const sc2::Point3D& pos_) const; void DrawSphere(const sc2::Point3D& center_, float radius_) const; void DrawBox(const sc2::Point3D& min_, const sc2::Point3D& max_) const; void DrawLine(const sc2::Point3D& start_, const sc2::Point3D& end_) const; void EndGame() const; void SendDebug() const; private: sc2::DebugInterface* m_debug; }; // ---------------------------------------------------------------------------- // Observer; // ---------------------------------------------------------------------------- struct Observer { explicit Observer(const sc2::ObservationInterface* observer_, std::unordered_map<sc2::Tag, std::unique_ptr<WrappedUnit>>& unit_map_, std::vector<WrappedUnit*>& last_step_units_); //WrappedUnits GetUnits() const; WrappedUnit* GetUnit(sc2::Tag tag_) const; WrappedUnits GetUnits(sc2::Unit::Alliance alliance_) const; WrappedUnits GetUnits(const Filter& filter_) const; WrappedUnits GetUnits(const Filter& filter_, sc2::Unit::Alliance alliance_ = sc2::Unit::Alliance::Self) const; size_t CountUnitType(sc2::UNIT_TYPEID type_) const; size_t CountUnitsTypes(const std::set<sc2::UNIT_TYPEID>& types_); const sc2::GameInfo& GameInfo() const; sc2::Point3D StartingLocation() const; float GetFoodCap() const; float GetFoodUsed() const; uint32_t GetMinerals() const; uint32_t GetVespene() const; float GetAvailableFood() const; sc2::UnitTypeData* GetUnitTypeData(sc2::UNIT_TYPEID id_); sc2::UpgradeData GetUpgradeData(sc2::UPGRADE_ID id_) const; sc2::AbilityData GetAbilityData(sc2::ABILITY_ID id_) const; sc2::Race GetCurrentRace() const; const std::vector<sc2::ChatMessage>& GetChatMessages() const; uint32_t GetGameLoop() const; const sc2::ScoreDetails GetScoreDetails() const; bool HasCreep(const sc2::Point2D& point_) const; void OnUpgradeCompleted(); sc2::Visibility GetVisibility(const sc2::Point2D& pos_) const; const sc2::ObservationInterface* m_observer; private: std::unordered_map<sc2::UNIT_TYPEID, std::unique_ptr<sc2::UnitTypeData>> m_unit_data_cache; std::unordered_map<sc2::Tag, std::unique_ptr<WrappedUnit>>& m_unit_map; std::vector<WrappedUnit*>& m_last_step_units; }; // ---------------------------------------------------------------------------- // Query; // ---------------------------------------------------------------------------- struct Query { explicit Query(sc2::QueryInterface* query_); bool CanBePlaced(sc2::ABILITY_ID ability_id_, const sc2::Point2D& point_); bool CanBePlaced(const Order& order_, const sc2::Point2D& point_); std::vector<bool> CanBePlaced(const std::vector<sc2::QueryInterface::PlacementQuery>& queries_); float PathingDistance(const sc2::Point2D& start_, const sc2::Point2D& end_) const; float PathingDistance(const sc2::Unit* start_, const sc2::Point2D& end_) const; std::vector<float> PathingDistances(const std::vector<sc2::QueryInterface::PathingQuery>& queries_) const; sc2::AvailableAbilities GetAbilitiesForUnit(const sc2::Unit* unit_, bool ignore_resource_requirements_) const; private: sc2::QueryInterface* m_query; }; // ---------------------------------------------------------------------------- // Interface; // ---------------------------------------------------------------------------- struct Interface { Interface( sc2::ActionInterface* action_, sc2::ControlInterface* control_, sc2::DebugInterface* debug_, const sc2::ObservationInterface* observer_, sc2::QueryInterface* query_); Action& action() { return m_action; } Control& control() { return m_control; } Debug& debug() { return m_debug; } Observer& observer() { return m_observer; } Query& query() { return m_query; } void Init(); void OnStep(); void OnUpgradeComplete(); WrappedUnit* WrapAndUpdateUnit(const sc2::Unit* unit_); inline const std::vector<WrappedUnit*> GetLastStepUnits() { return m_last_step_units; } inline const WrappedUnits GetLastStepAllies() { return m_last_step_allies; } inline const WrappedUnits GetLastStepEnemies() { return m_last_step_enemies; } private: Action m_action; Control m_control; Debug m_debug; Observer m_observer; Query m_query; std::unordered_map<sc2::Tag, std::unique_ptr<WrappedUnit>> m_unit_map; std::vector<WrappedUnit*> m_last_step_units; WrappedUnits m_last_step_allies; WrappedUnits m_last_step_enemies; }; } // namespace API // Globals extern std::unique_ptr<API::Interface> gAPI;
[ "bacahillsmu@gmail.com" ]
bacahillsmu@gmail.com
fc3e2e3ecff8032d3e47bae5eea678b98d056c4d
541d76c59ad6395d2020a376bce0b50c133fc223
/DLL/Serial/SerialDialog.cpp
903088fd382b84cb0cc35f80c36c43421de01c12
[]
no_license
wilson9chen/WinLIRC
8ce981beaa7bfb6928bad7883928075ca90e4fd7
75a232d1032fc24e4d955f70404fe02abc83c4e0
refs/heads/master
2021-08-30T10:11:13.835347
2017-12-17T12:29:46
2017-12-17T12:29:46
114,534,095
0
0
null
null
null
null
UTF-8
C++
false
false
3,982
cpp
/* * This file is part of the WinLIRC package, which was derived from * LIRC (Linux Infrared Remote Control) 0.8.6. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Copyright (C) 2010 Ian Curtis */ #include "stdafx.h" #include "SerialDialog.h" #include "Globals.h" #include "../Common/LIRCDefines.h" #include "Transmit.h" // SerialDialog dialog IMPLEMENT_DYNAMIC(SerialDialog, CDialog) SerialDialog::SerialDialog(CWnd* pParent /*=NULL*/) : CDialog(SerialDialog::IDD, pParent) { animax = FALSE; deviceType = -1; virtualPulse = 0; transmitterPin = -1; hardwareCarrier = FALSE; inverted = FALSE; } SerialDialog::~SerialDialog() { } void SerialDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_PORT, port); DDX_Control(pDX, IDC_SPEED, speed); DDX_Control(pDX, IDC_SENSE, sense); DDX_Radio(pDX, IDC_RADIORX, deviceType); DDX_Radio(pDX, IDC_RADIODTR, transmitterPin); DDX_Check(pDX, IDC_CHECKANIMAX, animax); DDX_Check(pDX, IDC_CHECKHARDCARRIER, hardwareCarrier); DDX_Check(pDX, IDC_INVERTED, inverted); DDX_Text(pDX, IDC_VIRTPULSE, virtualPulse); DDV_MinMaxInt(pDX, virtualPulse, 0, 16777215); } BEGIN_MESSAGE_MAP(SerialDialog, CDialog) ON_BN_CLICKED(IDC_RADIORX, &SerialDialog::OnBnClickedRadiorx) ON_BN_CLICKED(IDC_RADIODCD, &SerialDialog::OnBnClickedRadiodcd) ON_BN_CLICKED(IDOK, &SerialDialog::OnBnClickedOk) END_MESSAGE_MAP() // SerialDialog message handlers BOOL SerialDialog::OnInitDialog() { //=========== CComboBox *p; int x; //=========== CDialog::OnInitDialog(); settings.loadSettings(); p = (CComboBox *)GetDlgItem(IDC_PORT); x = p->FindStringExact(0,settings.port); if(x != CB_ERR) { p->SetCurSel(x); } else { p->SetCurSel(0); } p = (CComboBox *)GetDlgItem(IDC_SPEED); x = p->FindStringExact(0,settings.speed); if(x != CB_ERR) { p->SetCurSel(x); } else { p->SetCurSel(0); } ((CComboBox *)GetDlgItem(IDC_SENSE))->SetCurSel(settings.sense+1); animax = settings.animax; hardwareCarrier = settings.transmitterType & HARDCARRIER; transmitterPin = (settings.transmitterType & TXTRANSMITTER)>>1; inverted = (settings.transmitterType & INVERTED)>>2; virtualPulse = settings.virtualPulse; deviceType = settings.deviceType; UpdateData(FALSE); OnBnClickedRadiorx(); return TRUE; } void SerialDialog::OnBnClickedRadiorx() { UpdateData(TRUE); GetDlgItem(IDC_SENSE)->EnableWindow(deviceType); GetDlgItem(IDC_VIRTPULSE)->EnableWindow(!deviceType); GetDlgItem(IDC_CHECKANIMAX)->EnableWindow(deviceType); } void SerialDialog::OnBnClickedRadiodcd() { OnBnClickedRadiorx(); } void SerialDialog::OnBnClickedOk() { //=========== CString temp; //=========== OnOK(); settings.transmitterType = (inverted<<2)|(transmitterPin<<1)|hardwareCarrier; int sense=((CComboBox *)GetDlgItem(IDC_SENSE))->GetCurSel(); if(sense>=1 && sense<=2) sense--; else sense=-1; settings.sense=sense; port.GetWindowText(temp); settings.port = temp; speed.GetWindowText(temp); settings.speed = temp; settings.deviceType = deviceType; settings.virtualPulse = virtualPulse; settings.animax = animax; settings.saveSettings(); }
[ "dukeeeey@92c2518b-485e-4ca2-9c37-138eef3f838b" ]
dukeeeey@92c2518b-485e-4ca2-9c37-138eef3f838b
3246ee60e38c470cfd5f47f2ff4d7eb6b1768321
3c9455b1ac8791a850c9088556e71395cf2486f8
/week6/knapsack.cpp
12f6c2f8634cea580ffd0fa1b5ae68b50572358c
[]
no_license
Henrai/HihoCoder
ff72b8c4e06b59058920b5017517e38f694cabde
24fd387de5d9fc3782623b3d6030ee0b646d48dc
refs/heads/master
2021-01-21T13:25:40.544794
2016-07-21T01:21:21
2016-07-21T01:21:21
58,835,901
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include <iostream> using namespace std; int value[555]; int cost[555]; int dp[100005]; int main() { int n,m; cin>>n>>m; for(int i = 0; i <= m; i++) dp[i] = 0; for(int i = 1; i <= n; i++) cin>>cost[i]>>value[i]; for(int i = 1; i <= n; i++) for(int j = m; j >= cost[i]; j--) dp[j] = max(dp[j], dp[j-cost[i]] + value[i]); cout<<dp[m]<<endl; }
[ "wanganzec@gmail.com" ]
wanganzec@gmail.com
5a187cc52518383ff0ced7625ce7065de9153776
c358397368d34a4f3b6d0bab4a03179f1c155a73
/lab09/lab09/SimpleString.h
bb89bff11def2687de879c2316dd7d0925c08938
[]
no_license
nguyengiahy/COS30008
b0e7d5e4ae6fe2dddca319e86123cef7e5061ea8
e70b1aa0c6e4460163dc8761088ad4853cb1f910
refs/heads/master
2021-09-26T16:41:40.884106
2021-09-11T17:52:19
2021-09-11T17:52:19
249,945,885
1
3
null
null
null
null
UTF-8
C++
false
false
444
h
#pragma once #include<string> #include "Test.h" class SimpleString { private: char* fChacracters; public: SimpleString(); virtual ~SimpleString(); #if TEST >= 1 SimpleString(const SimpleString& aOtherString); #endif #if TEST >= 3 SimpleString& operator=( const SimpleString& aOtherString ); #endif #if TEST >= 5 virtual SimpleString* clone(); #endif SimpleString& operator+(const char aCharacter); const char* operator*() const; };
[ "nguyengiahy2911@gmail.com" ]
nguyengiahy2911@gmail.com