blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f0f15fd3e34a1a949899bcd444c85b672ba0c2ca | 0d0e78c6262417fb1dff53901c6087b29fe260a0 | /cdn/src/v20180606/model/EnableCachesResponse.cpp | 61f0b2c3741270bf469751aa2065c447936a51e4 | [
"Apache-2.0"
] | permissive | li5ch/tencentcloud-sdk-cpp | ae35ffb0c36773fd28e1b1a58d11755682ade2ee | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | refs/heads/master | 2022-12-04T15:33:08.729850 | 2020-07-20T00:52:24 | 2020-07-20T00:52:24 | 281,135,686 | 1 | 0 | Apache-2.0 | 2020-07-20T14:14:47 | 2020-07-20T14:14:46 | null | UTF-8 | C++ | false | false | 3,221 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdn/v20180606/model/EnableCachesResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace rapidjson;
using namespace std;
EnableCachesResponse::EnableCachesResponse() :
m_cacheOptResultHasBeenSet(false)
{
}
CoreInternalOutcome EnableCachesResponse::Deserialize(const string &payload)
{
Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("CacheOptResult") && !rsp["CacheOptResult"].IsNull())
{
if (!rsp["CacheOptResult"].IsObject())
{
return CoreInternalOutcome(Error("response `CacheOptResult` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_cacheOptResult.Deserialize(rsp["CacheOptResult"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_cacheOptResultHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
CacheOptResult EnableCachesResponse::GetCacheOptResult() const
{
return m_cacheOptResult;
}
bool EnableCachesResponse::CacheOptResultHasBeenSet() const
{
return m_cacheOptResultHasBeenSet;
}
| [
"jimmyzhuang@tencent.com"
] | jimmyzhuang@tencent.com |
75b8ff7117eb3fc0a742a40db38d627d8adeef2a | 35237f70f00637667dfc05747262415f00ad48cb | /echo_server_sync.cpp | c2f5a4742cf865dfde96a52bca8956ac3e372887 | [] | no_license | mtclinton/boost-asio-practice | 8f55087f65cb9aefe91c2ff8b2d7376ecf5ae447 | 504943c85d1d6df8ab203e183ed16a4be60cdcad | refs/heads/main | 2023-06-03T15:45:49.488509 | 2021-06-09T23:44:23 | 2021-06-09T23:44:23 | 366,200,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,591 | cpp | #include <array>
#include <iostream>
#include <string>
#include "boost/asio.hpp"
using boost::asio::ip::tcp;
enum { BUF_SIZE = 1024 };
void Session(tcp::socket socket) {
try {
while (true) {
std::array<char, BUF_SIZE> data;
boost::system::error_code ec;
std::size_t length = socket.read_some(boost::asio::buffer(data), ec);
if (ec == boost::asio::error::eof) {
std::cout << "Connection closed cleanly by peer." << std::endl;
break;
} else if (ec) {
// Some other error
throw boost::system::system_error(ec);
}
boost::asio::write(socket, boost::asio::buffer(data, length));
}
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <port>" << std::endl;
return 1;
}
unsigned short port = std::atoi(argv[1]);
boost::asio::io_context io_context;
// Create an acceptor to listen for new connections.
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port));
try {
// Handle one connection at a time.
while (true) {
// The socket object returned from accept will be moved to Session's
// parameter without any copy cost.
Session(acceptor.accept());
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
} | [
"maxtclinton@gmail.com"
] | maxtclinton@gmail.com |
bfc8559aa479251acf8a00e665067a2cf63f5a39 | 2d42a50f7f3b4a864ee19a42ea88a79be4320069 | /source/loader/parser/parse_sun.cpp | b14a33d35a87d69428540b8616a7ff9822bc766b | [] | no_license | Mikalai/punk_project_a | 8a4f55e49e2ad478fdeefa68293012af4b64f5d4 | 8829eb077f84d4fd7b476fd951c93377a3073e48 | refs/heads/master | 2016-09-06T05:58:53.039941 | 2015-01-24T11:56:49 | 2015-01-24T11:56:49 | 14,536,431 | 1 | 0 | null | 2014-06-26T06:40:50 | 2013-11-19T20:03:46 | C | UTF-8 | C++ | false | false | 1,121 | cpp | //#include <attributes/data/lights/sun.h>
//#include "parser.h"
//#include "parse_simple.h"
//#include "parse_sun.h"
//
//PUNK_ENGINE_BEGIN
//namespace IoModule
//{
// bool ParseSun(Core::Buffer &buffer, Attributes::Sun &value)
// {
// CHECK_START(buffer);
// while (1)
// {
// const Core::String word = buffer.ReadWord();
// KeywordCode code = ParseKeyword(word);
// switch(code)
// {
// case WORD_CLOSE_BRACKET:
// return true;
// case WORD_ENERGY:
// {
// float v;
// ParseBlockedFloat(buffer, v);
// value.SetEnergy(v);
// }
// break;
// case WORD_COLOR:
// {
// Math::vec3 v;
// ParseBlockedVector3f(buffer, v);
// value.SetColor(v);
// }
// break;
// default:
// throw Error::LoaderException(L"Unexpected keyword " + word);
// }
// }
// return false;
// }
//}
//PUNK_ENGINE_END
| [
"nickolaib2004@gmail.com"
] | nickolaib2004@gmail.com |
7184315448dcfa624bc9564ff3efc691f0bb52e7 | 18da01143c6a560df34884eeb5be6e4a7c744e24 | /I_GGX64/6/6对4/1车1马4兵对2炮2马.cpp | d290fb1b41a0f315c6704d889e27496195547b36 | [] | no_license | alanthinker/NewGG | 974832e6738b1cd0df01ab2c5b94489a4ccf53e9 | ead7b553954336b76a476922005cc578f68cc6f1 | refs/heads/master | 2022-07-05T02:46:18.030741 | 2020-05-16T14:03:36 | 2020-05-16T14:03:36 | 264,444,924 | 0 | 0 | null | 2020-05-16T13:37:04 | 2020-05-16T13:37:04 | null | WINDOWS-1252 | C++ | false | false | 1,024 | cpp | #ifndef END_my_m_MT_R_1che1ma4pawn_B_2pao2ma
#define END_my_m_MT_R_1che1ma4pawn_B_2pao2ma
#include "..\\..\\chess.h"
#include "..\\..\\preGen.h"
#include "..\\..\\endgame\mat.h"
#include "1³µ1Âí4±ø¶Ô2ÅÚ2Âí.cpp"
#include "..\\..\\white.h"
#else
#include "..\\..\\black.h"
#endif
void my_m_MT_R_1che1ma4pawn_B_2pao2ma(typePOS &POSITION, EvalInfo &ei){
if((my_xiang_num + my_shi_num) >= 3){
MY_EV_ADD(EV_MY_CAN * 32);
}
}
//void m_MT_B_1che1ma4pawn_R_2pao2ma(typePOS &POSITION, EvalInfo &ei){
///*
// int bcan = BpawnCanOverLiver(board);
// Square bk = PieceListStart(board,BKING);
// Square rk = PieceListStart(board,RKING);
//
//
// // fen 3ak1c2/3c2n2/3ab4/2R5N/2n2P1P1/2B6/9/9/4A4/4KA3 b - - 0 0
// if((board->B_shi + board->B_xiang) >= 3){
// board->mulScore -= bcan * 32;
// }
//
// if(board->B_shi == 2 && board->B_xiang == 2 && StoY(bk) == 0x3){
// if(bcan >= 2){
// if(Is_B_PawnControl_R_Ma(board)){
// board->mulScore -= ADD_Che2PawnCan_PawnControlMa;
// }
// }
// }
//
//
// */
//} | [
"keersun@qq.com"
] | keersun@qq.com |
cf5a8a3a93583a4e589250f09364bb86f2074d6b | 8fcdb086cf576d7305df0c3008bf4722b35cff2f | /src/otlib/OTTrade.cpp | 71e41ee51f6a6bb4f3f351bce4bfa964892ca062 | [] | no_license | albertocabello/Open-Transactions | c7c6272fdeeadd55062b6843295774f56654b1a1 | d88c36f0b2d281e3d2745666c8d4fe6b107dfe7f | refs/heads/master | 2021-01-16T21:19:41.363272 | 2013-05-15T15:35:19 | 2013-05-15T15:35:19 | 10,205,341 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,098 | cpp | /************************************************************************************
*
* OTTrade.cpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* 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 Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#include <cstring>
#include "irrxml/irrXML.h"
using namespace irr;
using namespace io;
#include "OTStorage.h"
#include "OTIdentifier.h"
#include "OTPseudonym.h"
#include "OTCron.h"
#include "OTAccount.h"
#include "OTTrade.h"
#include "OTOffer.h"
#include "OTMarket.h"
#include "OTLog.h"
#ifndef TRADE_PROCESS_INTERVAL
#define TRADE_PROCESS_INTERVAL 10 // 10 seconds
#endif
// This class is like: you are placing an order to do a trade.
// Your order will continue processing until it is complete.
// PART of that process is putting an offer on the market. See OTOffer for that.
//
// Trades are like cron items, they can expire, they can have rules.
//
// An OTTrade is derived from OTCronItem. OTCron has a list of those items.
// Used to be I could just call pTrade->VerifySignature(theNym), which is what
// I still call here, inside this function. But that's a special case -- an override
// from the OTScriptable / OTSmartContract version, which verifies parties and agents, etc.
//
bool OTTrade::VerifyNymAsAgent(const OTPseudonym & theNym,
OTPseudonym & theSignerNym, // Not needed in this version of the override.
mapOfNyms * pmap_ALREADY_LOADED/*=NULL*/)
{
return this->VerifySignature(theNym);
}
// This is an override. See note above.
//
bool OTTrade::VerifyNymAsAgentForAccount(OTPseudonym & theNym, const OTAccount & theAccount)
{
return theAccount.VerifyOwner(theNym);
}
// -------------------------------------------------------------
// return -1 if error, 0 if nothing, and 1 if the node was processed.
int OTTrade::ProcessXMLNode(irr::io::IrrXMLReader*& xml)
{
int nReturnVal = 0;
// Here we call the parent class first.
// If the node is found there, or there is some error,
// then we just return either way. But if it comes back
// as '0', then nothing happened, and we'll continue executing.
//
// -- Note you can choose not to call the parent if
// you don't want to use any of those xml tags.
// As I do below, in the case of OTAccount.
//
if (0 != (nReturnVal = ot_super::ProcessXMLNode(xml)))
return nReturnVal;
if (!strcmp("trade", xml->getNodeName()))
{
m_strVersion = xml->getAttributeValue("version");
m_nTradesAlreadyDone= atoi( xml->getAttributeValue("completedNoTrades"));
SetTransactionNum( atol(xml->getAttributeValue("transactionNum")) );
SetCreationDate( atoi(xml->getAttributeValue("creationDate")));
SetValidFrom( atoi(xml->getAttributeValue("validFrom")));
SetValidTo( atoi(xml->getAttributeValue("validTo")));
// ---------------------
OTString strActivated(xml->getAttributeValue("hasActivated"));
if (strActivated.Compare("true"))
m_bHasTradeActivated = true;
else
m_bHasTradeActivated = false;
// ---------------------
const OTString strServerID(xml->getAttributeValue("serverID")),
strUserID(xml->getAttributeValue("userID")),
strAssetTypeID(xml->getAttributeValue("assetTypeID")),
strAssetAcctID(xml->getAttributeValue("assetAcctID")),
strCurrencyTypeID(xml->getAttributeValue("currencyTypeID")),
strCurrencyAcctID(xml->getAttributeValue("currencyAcctID"));
const OTIdentifier SERVER_ID(strServerID), USER_ID(strUserID),
ASSET_TYPE_ID(strAssetTypeID), ASSET_ACCT_ID(strAssetAcctID),
CURRENCY_TYPE_ID(strCurrencyTypeID), CURRENCY_ACCT_ID(strCurrencyAcctID);
SetServerID(SERVER_ID);
SetSenderUserID(USER_ID);
SetAssetID(ASSET_TYPE_ID);
SetSenderAcctID(ASSET_ACCT_ID);
SetCurrencyID(CURRENCY_TYPE_ID);
SetCurrencyAcctID(CURRENCY_ACCT_ID);
// ---------------------
OTLog::vOutput(3, "\n\nTrade. Transaction Number: %ld Completed # of Trades: %d\n",
m_lTransactionNum, m_nTradesAlreadyDone);
OTLog::vOutput(1,
" Creation Date: %d Valid From: %d\n Valid To: %d\n"
" assetTypeID: %s\n assetAcctID: %s\n"
" ServerID: %s\n UserID: %s\n "
" currencyTypeID: %s\n currencyAcctID: %s\n ",
GetCreationDate(), GetValidFrom(), GetValidTo(),
strAssetTypeID.Get(), strAssetAcctID.Get(),
strServerID.Get(), strUserID.Get(),
strCurrencyTypeID.Get(), strCurrencyAcctID.Get());
nReturnVal = 1;
}
if (!strcmp("stopOrder", xml->getNodeName()))
{
OTString strSign(xml->getAttributeValue("sign"));
if (strSign.Compare("0"))
{
m_cStopSign = 0; // Zero means it isn't a stop order. So why is the tag in the file?
OTLog::vError("Strange: Stop order tag found in trade, but sign character set to 0.\n"
"(Zero means: NOT a stop order.)\n", strSign.Get());
return (-1);
}
else if (strSign.Compare("<"))
m_cStopSign = '<';
else if (strSign.Compare(">"))
m_cStopSign = '>';
else
{
m_cStopSign = 0;
OTLog::vError("Unexpected or nonexistent value in stop order sign: %s\n", strSign.Get());
return (-1);
}
// ---------------------
// Now we know the sign is properly formed, let's grab the price value.
m_lStopPrice = atol(xml->getAttributeValue("price"));
// ---------------------
OTString strActivated(xml->getAttributeValue("hasActivated"));
if (strActivated.Compare("true"))
m_bHasStopActivated = true;
else
m_bHasStopActivated = false;
// ---------------------
OTLog::vOutput(3,
"\n\nStop order -- %s when price %s %s: %ld.\n",
(m_bHasStopActivated ? "Already activated" : "Will activate"),
(m_bHasStopActivated ? "was" : "reaches"),
(('<' == m_cStopSign) ? "LESS THAN" : "GREATER THAN"),
m_lStopPrice);
nReturnVal = 1;
}
else if (!strcmp("offer", xml->getNodeName()))
{
if (false == OTContract::LoadEncodedTextField(xml, m_strOffer))
{
OTLog::Error("Error in OTTrade::ProcessXMLNode: offer field without value.\n");
return (-1); // error condition
}
nReturnVal = 1;
}
return nReturnVal;
}
void OTTrade::UpdateContents()
{
// I release this because I'm about to repopulate it.
m_xmlUnsigned.Release();
m_xmlUnsigned.Concatenate("<?xml version=\"%s\"?>\n\n", "1.0");
// -------------------------------------------------------------
const OTString SERVER_ID(GetServerID()), USER_ID(GetSenderUserID()),
ASSET_TYPE_ID(GetAssetID()), ASSET_ACCT_ID(GetSenderAcctID()),
CURRENCY_TYPE_ID(GetCurrencyID()), CURRENCY_ACCT_ID(GetCurrencyAcctID());
m_xmlUnsigned.Concatenate("<trade\n version=\"%s\"\n"
" hasActivated=\"%s\"\n"
" serverID=\"%s\"\n"
" assetTypeID=\"%s\"\n"
" assetAcctID=\"%s\"\n"
" currencyTypeID=\"%s\"\n"
" currencyAcctID=\"%s\"\n"
" userID=\"%s\"\n"
" completedNoTrades=\"%d\"\n"
" transactionNum=\"%ld\"\n"
" creationDate=\"%d\"\n"
" validFrom=\"%d\"\n"
" validTo=\"%d\""
" >\n\n",
m_strVersion.Get(),
(m_bHasTradeActivated ? "true" : "false"),
SERVER_ID.Get(),
ASSET_TYPE_ID.Get(),
ASSET_ACCT_ID.Get(),
CURRENCY_TYPE_ID.Get(),
CURRENCY_ACCT_ID.Get(),
USER_ID.Get(),
m_nTradesAlreadyDone,
m_lTransactionNum,
GetCreationDate(),
GetValidFrom(), GetValidTo() );
// -------------------------------------------------------------
// There are "closing" transaction numbers, used to CLOSE a transaction.
// Often where Cron items are involved such as this payment plan, or in baskets,
// where many asset accounts are involved and require receipts to be closed out.
for (int i = 0; i < GetCountClosingNumbers(); i++)
{
long lClosingNumber = GetClosingTransactionNoAt(i);
OT_ASSERT(lClosingNumber > 0);
m_xmlUnsigned.Concatenate("<closingTransactionNumber value=\"%ld\"/>\n\n",
lClosingNumber);
}
// -------------------------------------------------------------
if (('<' == m_cStopSign) || ('>' == m_cStopSign))
{
m_xmlUnsigned.Concatenate("<stopOrder\n"
" hasActivated=\"%s\"\n"
" sign=\"%c\"\n"
" price=\"%ld\""
" />\n\n",
(m_bHasStopActivated ? "true" : "false"),
m_cStopSign,
m_lStopPrice);
}
// -------------------------------------------------------------
if (m_strOffer.Exists())
{
OTASCIIArmor ascOffer(m_strOffer);
m_xmlUnsigned.Concatenate("<offer>\n%s</offer>\n\n", ascOffer.Get());
}
// -------------------------------------------------------------
m_xmlUnsigned.Concatenate("</trade>\n");
}
// The trade stores a copy of the Offer in string form.
// This function verifies that offer against the trade,
// and also verifies the signature on the offer.
//
// The Nym's ID is compared to theOffer's SenderUserID, and then the Signature is checked
// on the offer. It also compares the server ID, asset and currency IDs, transaction #, etc
// between this trade and the offer, in order to fully verify the offer's authenticity.
//
bool OTTrade::VerifyOffer(OTOffer & theOffer)
{
// At this point, I have a working, loaded, model of the Offer.
// Let's verify the thing.
if (GetTransactionNum() != theOffer.GetTransactionNum())
{
OTLog::Error("While verifying offer, failed matching transaction number.\n");
return false;
}
else if (GetServerID() != theOffer.GetServerID())
{
OTLog::Error("While verifying offer, failed matching Server ID.\n");
return false;
}
else if (GetAssetID() != theOffer.GetAssetID())
{
OTLog::Error("While verifying offer, failed matching asset type ID.\n");
return false;
}
else if (GetCurrencyID() != theOffer.GetCurrencyID())
{
OTLog::Error("While verifying offer, failed matching currency type ID.\n");
return false;
}
// -------------------------------------------------
// the Offer validates properly for this Trade.
//
return true;
}
// Assuming the offer is ON the market, this will get the pointer to that offer.
// Otherwise it will try to add it to the market.
// Otherwise it will fail. (Perhaps it's a stop order, and not ready to activate yet.)
//
OTOffer * OTTrade::GetOffer(OTIdentifier * pOFFER_MARKET_ID/*=NULL*/, OTMarket ** ppMarket/*=NULL*/)
{
OT_ASSERT(NULL != GetCron());
// See if the offer has already been instantiated onto a market...
if (NULL != m_pOffer)
{
m_pOffer->SetTrade(*this); // Probably don't need this line. I'll remove it someday while optimizing.
// In fact since it should already be set, having this here would basically
// hide it from me if the memory was ever walked on from a bug somewhere.
// It loaded. Let's get the Market ID off of it so we can locate the market.
const OTIdentifier OFFER_MARKET_ID(*m_pOffer);
if (NULL != ppMarket)
{
OTMarket * pMarket = GetCron()->GetMarket(OFFER_MARKET_ID);
// Sometimes the caller function would like a copy of this market pointer, when available.
// So I pass it back to him here, if he wants. That way he doesn't have to do this work again
// to look it up.
if (NULL != pMarket)
*ppMarket = pMarket; // <=================
else
OTLog::Error("OTTrade::GetOffer: m_pOffer already exists, yet unable to find the market it's supposed to be on.\n");
}
if (NULL != pOFFER_MARKET_ID)
{
// Sometimes the caller function would like a copy of this ID. So I
// give the option to pass in a pointer so I can give it here.
pOFFER_MARKET_ID->Assign(OFFER_MARKET_ID);
}
return m_pOffer;
} // if m_pOffer ALREADY EXISTS.
// else (BELOW) m_pOffer IS NULL, and thus it didn't exist yet...
// --------------------------------------------------
if (!m_strOffer.Exists())
{
OTLog::Error("OTTrade::GetOffer called with empty m_strOffer.\n");
return NULL;
}
// --------------------------------------------------
OTOffer * pOffer = new OTOffer();
OT_ASSERT(NULL != pOffer);
// Trying to load the offer from the trader's original signed request
// (So I can use it to lookup the Market ID, so I can see the offer is
// already there on the market.)
if (!pOffer->LoadContractFromString(m_strOffer))
{
OTLog::Error("Error loading offer from string in OTTrade::GetOffer\n");
delete pOffer; pOffer = NULL;
return NULL;
}
// No need to do any additional security verification here on the Offer,
// since the Offer is already heavily verified in OTServer::NotarizeMarketOffer().
// So as long as you feel safe about the Trade, then you can feel safe about
// the Offer already, with no further checks.
// *Also remember we saved a copy of the original in the cron folder.
// It loaded. Let's get the Market ID off of it so we can locate the market.
OTIdentifier OFFER_MARKET_ID(*pOffer);
if (NULL != pOFFER_MARKET_ID)
{
// Sometimes the caller function would like a copy of this ID. So I
// give the option to pass in a pointer so I can give it here.
pOFFER_MARKET_ID->Assign(OFFER_MARKET_ID);
}
// ---------------------------------------------------------------
// Previously if a user tried to use a market that didn't exist, I'd just return failure.
// But now we will create any market that doesn't already exist.
// (Remember, the server operator could just erase the market folder--it wouldn't
// affect anyone's balances!) Update: he probably couldn't just wipe the markets folder,
// actually, without making it impossible for certain Nyms to get rid of certain issued #s.
//
// OTMarket * pMarket = m_pCron->GetMarket(OFFER_MARKET_ID);
OTMarket * pMarket = GetCron()->GetOrCreateMarket(GetAssetID(), GetCurrencyID(), pOffer->GetScale());
// Couldn't find (or create) the market.
if (NULL == pMarket)
{
OTLog::Output(3, "Unable to find or create market within requested parameters in OTTrade::GetOffer.");
delete pOffer; pOffer = NULL;
return NULL;
}
// If the caller passed in the address of a market pointer (optional)
if (NULL != ppMarket)
{
// Sometimes the caller function would like a copy of this market pointer, when available.
// So I pass it back to him here, if he wants. That way he doesn't have to do this work again
// to look it up.
*ppMarket = pMarket;
}
// --------------------------------------------------
// At this point, I have heap-allocated the offer, used it to get the Market ID, and successfully
// used that to get a pointer to the market matching that ID.
//
// Let's see if the offer is ALREADY allocated and on this market!
// If so, delete the one I just allocated. If not, add it to the market.
OTOffer * pMarketOffer = pMarket->GetOffer(pOffer->GetTransactionNum());
// The Offer is already on the Market.
// NOTE: It may just start out this way, without ever being added.
// How is that possible? Because maybe it was in the market file when we first loaded up,
// and had been added on some previous run of the software. So since we started running,
// the pMarket->AddOffer() code below has literally never run for that offer. Instead we
// first find it here, and thus return the pointer before getting any farther.
//
// IN ALL CASES, we make sure to call m_pOffer->SetTrade() so that it has a pointer BACK to
// this Trade object! (When actually processing the offer, the market will need the account
// numbers and Nym IDs... which are stored here on the trade.)
if (NULL != pMarketOffer)
{
m_pOffer = pMarketOffer;
// Since the Offer already exists on the market, no need anymore for the
// one we allocated above (to get the market ID.) So we delete it now.
delete pOffer;
pOffer = NULL;
m_pOffer->SetTrade(*this);
return m_pOffer;
}
// ************************************************************************
// Okay so the offer ISN'T already on the market. If it's not a stop order, let's ADD the one we
// allocated to the market now! (Stop orders are activated through their own logic, which is below
// this, in the else block.)
//
if (!IsStopOrder())
{
if (m_bHasTradeActivated)
{
// Error -- how has the trade already activated, yet not on the market and null in my pointer?
OTLog::Error("How has the trade already activated, yet not on the market and null in my pointer?\n");
}
else if (!pMarket->AddOffer(*pOffer, true)) // Since we're actually adding an offer to the market (not just
{ // loading from disk) the we actually want to save the market. bSaveFile=true.
// Error adding the offer to the market!
OTLog::Error("Error adding the offer to the market! (Even though supposedly the right market.)\n");
}
else
{
// SUCCESS!
m_pOffer = pOffer;
m_bHasTradeActivated = true;
// The Trade (stored on Cron) has a copy of the Original Offer, with the User's signature on it.
// A copy of that original Trade object (itself with the user's signature) is already stored in
// the cron folder (by transaction number.) This happens when the Trade is FIRST added to cron,
// so it's already safe before we even get here.
//
// So thus I am FREE to release the signatures on the offer, and sign with the server instead.
// The server-signed offer will be stored by the OTMarket.
m_pOffer->ReleaseSignatures();
m_pOffer->SignContract(*(GetCron()->GetServerNym()));
m_pOffer->SaveContract();
pMarket->SaveMarket();
// Now when the market loads next time, it can verify this offer using the server's signature,
// instead of having to load the user. Because the server has verified it and added it, and now
// signs it, vouching for it.
// The Trade itself (all its other variables) are now allowed to change, since its signatures
// are also released and it is now server-signed. (With a copy stored of the original.)
m_pOffer->SetTrade(*this);
return m_pOffer;
}
}
// -----------------------------------------------------------------
// It's a stop order, and not activated yet.
// Should we activate it now?
//
else if (IsStopOrder() && !m_bHasStopActivated)
{
long lRelevantPrice = 0;
// If the stop order is trying to sell something, then it cares about the highest bidder.
if (pOffer->IsAsk())
lRelevantPrice = pMarket->GetHighestBidPrice();
else // But if the stop order is trying to buy something, then it cares about the lowest ask price.
lRelevantPrice = pMarket->GetLowestAskPrice();
// It's a stop order that hasn't activated yet. SHOULD IT ACTIVATE NOW?
if ((IsGreaterThan() && (lRelevantPrice > GetStopPrice())) ||
(IsLessThan() && (lRelevantPrice < GetStopPrice())))
{
// Activate the stop order!
if (!pMarket->AddOffer(*pOffer, true)) // Since we're actually adding an offer to the market (not just
{ // loading from disk) the we actually want to save the market. bSaveFile=true.
// Error adding the offer to the market!
OTLog::Error("Error adding the stop order to the market! (Even though supposedly the right market.)\n");
}
else
{
// SUCCESS!
m_pOffer = pOffer;
m_bHasStopActivated = true;
m_bHasTradeActivated = true;
// The Trade (stored on Cron) has a copy of the Original Offer, with the User's signature on it.
// A copy of that original Trade object (itself with the user's signature) is already stored in
// the cron folder (by transaction number.) This happens when the Trade is FIRST added to cron,
// so it's already safe before we even get here.
//
// So thus I am FREE to release the signatures on the offer, and sign with the server instead.
// The server-signed offer will be stored by the OTMarket.
m_pOffer->ReleaseSignatures();
m_pOffer->SignContract(*(GetCron()->GetServerNym()));
m_pOffer->SaveContract();
pMarket->SaveMarket();
// Now when the market loads next time, it can verify this offer using the server's signature,
// instead of having to load the user. Because the server has verified it and added it, and now
// signs it, vouching for it.
// The Trade itself (all its other variables) are now allowed to change, since its signatures
// are also released and it is now server-signed. (With a copy stored of the original.)
m_pOffer->SetTrade(*this);
return m_pOffer;
}
}
}
delete pOffer;
pOffer = NULL;
return NULL;
}
// Cron only removes an item when that item REQUESTS to be removed (by setting the flag.)
// Once this happens, Cron has full permission to remove it. Thus, this hook is forceful. It
// is cron saying, YOU ARE BEING REMOVED. Period. So cleanup whatever you have to clean up.
//
// In this case, it removes the corresponding offer from the market.
//
void OTTrade::onRemovalFromCron()
{
OTCron * pCron = GetCron();
OT_ASSERT(NULL != pCron);
// If I don't already have an offer on the market, then I will have trouble figuring out
// my SCALE, which is stored on the Offer. Therefore I will instantiate an offer (since I
// store the original internally) and I will look up the scale.
//
long lScale = 1; // todo stop hardcoding.
long lTransactionNum = 0;
if (NULL == m_pOffer)
{
if (!m_strOffer.Exists())
{
OTLog::Error("OTTrade::onRemovalFromCron called with NULL m_pOffer and empty m_strOffer.\n");
return;
}
OTOffer * pOffer = NULL;
OTCleanup<OTOffer> theOfferAngel;
// ---------------------------
pOffer = new OTOffer();
OT_ASSERT(NULL != pOffer);
theOfferAngel.SetCleanupTarget(*pOffer);
// --------------------------------------------------
// Trying to load the offer from the trader's original signed request
// (So I can use it to lookup the Market ID, so I can see if the offer is
// already there on the market.)
if (!pOffer->LoadContractFromString(m_strOffer))
{
OTLog::Error("Error loading offer from string in OTTrade::onRemovalFromCron\n");
return;
}
lScale = pOffer->GetScale();
lTransactionNum = pOffer->GetTransactionNum();
}
else
{
lScale = m_pOffer->GetScale();
lTransactionNum = m_pOffer->GetTransactionNum();
}
// -----------------------------------------------------------
OTMarket * pMarket = pCron->GetOrCreateMarket(GetAssetID(), GetCurrencyID(), lScale);
// Couldn't find (or create) the market.
//
if (NULL == pMarket)
{
OTLog::Error("Unable to find market within requested parameters in OTTrade::onRemovalFromCron.\n");
return;
}
// -----------------------------------------------------------
//
// Let's see if the offer is ALREADY allocated and on this market!
//
OTOffer * pMarketOffer = pMarket->GetOffer(lTransactionNum);
// The Offer is already on the Market.
//
if (NULL != pMarketOffer)
{
m_pOffer = pMarketOffer;
m_pOffer->SetTrade(*this);
}
// -----------------------------------------------------------
pMarket->RemoveOffer(lTransactionNum);
// -----------------------------------------------------------
}
// GetSenderAcctID() -- asset account.
// GetCurrencyAcctID() -- currency account.
long OTTrade::GetClosingNumber(const OTIdentifier & theAcctID) const
{
const OTIdentifier & theAssetAcctID = this->GetSenderAcctID();
const OTIdentifier & theCurrencyAcctID = this->GetCurrencyAcctID();
if (theAcctID == theAssetAcctID)
return GetAssetAcctClosingNum();
else if (theAcctID == theCurrencyAcctID)
return GetCurrencyAcctClosingNum();
// else...
return 0;
}
// ---------------------------------------------------
long OTTrade::GetAssetAcctClosingNum() const
{
return (GetCountClosingNumbers() > 0) ? GetClosingTransactionNoAt(0) : 0; // todo stop hardcoding.
}
long OTTrade::GetCurrencyAcctClosingNum() const
{
return (GetCountClosingNumbers() > 1) ? GetClosingTransactionNoAt(1) : 0; // todo stop hardcoding.
}
/// See if theNym has rights to remove this item from Cron.
///
bool OTTrade::CanRemoveItemFromCron(OTPseudonym & theNym)
{
// I don't call the parent class' version of this function, in the case of OTTrade,
// since it would just be redundant.
// ---------------------------------------------------------------------------------------
// You don't just go willy-nilly and remove a cron item from a market unless you check first
// and make sure the Nym who requested it actually has said trans# (and 2 related closing #s)
// signed out to him on his last receipt...
//
if (false == theNym.CompareID(GetSenderUserID()))
{
OTLog::Output(5, "OTTrade::CanRemoveItem: theNym is not the originator of this CronItem. "
"(He could be a recipient though, so this is normal.)\n");
return false;
}
// By this point, that means theNym is DEFINITELY the originator (sender)...
else if (this->GetCountClosingNumbers() < 2)
{
OTLog::vOutput(0, "OTTrade::CanRemoveItem Weird: Sender tried to remove a market trade; expected at "
"least 2 closing numbers to be available--that weren't. (Found %d).\n", this->GetCountClosingNumbers());
return false;
}
// ------------------------------------------
//
const OTString strServerID(GetServerID());
if (false == theNym.VerifyIssuedNum(strServerID, this->GetAssetAcctClosingNum()))
{
OTLog::Output(0, "OTTrade::CanRemoveItemFromCron: Closing number didn't verify for asset account.\n");
return false;
}
if (false == theNym.VerifyIssuedNum(strServerID, this->GetCurrencyAcctClosingNum()))
{
OTLog::Output(0, "OTTrade::CanRemoveItemFromCron: Closing number didn't verify for currency account.\n");
return false;
}
// By this point, we KNOW theNym is the sender, and we KNOW there are the proper number of transaction
// numbers available to close. We also know that this cron item really was on the cron object, since
// that is where it was looked up from, when this function got called! So I'm pretty sure, at this point,
// to authorize removal, as long as the transaction num is still issued to theNym (this check here.)
//
return theNym.VerifyIssuedNum(strServerID, this->GetOpeningNum());
// Normally this will be all we need to check. The originator will have the transaction
// number signed-out to him still, if he is trying to close it. BUT--in some cases, someone
// who is NOT the originator can cancel. Like in a payment plan, the sender is also the depositor,
// who would normally be the person cancelling the plan. But technically, the RECIPIENT should
// also have the ability to cancel that payment plan. BUT: the transaction number isn't signed
// out to the RECIPIENT... In THAT case, the below VerifyIssuedNum() won't work! In those cases,
// expect that the special code will be in the subclasses override of this function. (OTPaymentPlan::CanRemoveItem() etc)
// P.S. If you override this function, MAKE SURE to call the parent (OTCronItem::CanRemoveItem) first,
// for the VerifyIssuedNum call above. Only if that fails, do you need to dig deeper...
}
// This is called by OTCronItem::HookRemovalFromCron
// (After calling this method, HookRemovalFromCron then calls onRemovalFromCron.)
//
void OTTrade::onFinalReceipt(OTCronItem & theOrigCronItem, const long & lNewTransactionNumber,
OTPseudonym & theOriginator,
OTPseudonym * pRemover)
{
const char * szFunc = "OTTrade::onFinalReceipt";
// -----------------------------------------------------------------
OTCron * pCron = GetCron();
OT_ASSERT(NULL != pCron);
OTPseudonym * pServerNym = pCron->GetServerNym();
OT_ASSERT(NULL != pServerNym);
// -----------------------------------------------------------------
// First, we are closing the transaction number ITSELF, of this cron item,
// as an active issued number on the originating nym. (Changing it to CLOSED.)
//
// Second, we're verifying the CLOSING number, and using it as the closing number
// on the FINAL RECEIPT (with that receipt being "InReferenceTo" this->GetTransactionNum())
//
const long lOpeningNumber = theOrigCronItem.GetTransactionNum();
// ---------------------------------------------------------------------------
const long lClosingAssetNumber = (theOrigCronItem.GetCountClosingNumbers() > 0) ? theOrigCronItem.GetClosingTransactionNoAt(0) : 0;
const long lClosingCurrencyNumber = (theOrigCronItem.GetCountClosingNumbers() > 1) ? theOrigCronItem.GetClosingTransactionNoAt(1) : 0;
// ---------------------------------------------------------------------
const OTString strServerID(GetServerID());
// The marketReceipt ITEM's NOTE contains the UPDATED TRADE.
// And the **UPDATED OFFER** is stored on the ATTACHMENT on the **ITEM.**
//
// BUT!!! This is not a marketReceipt Item, is it? ***This is a finalReceipt ITEM!***
// I'm reversing pstrNote and pstrAttachment for finalReceipt, with the intention of
// eventually reversing them for marketReceipt as well. (Making them all in line with paymentReceipt.)
//
// WHY? Because I want a standard convention:
// 1. ORIGINAL (user-signed) Cron Items are always stored "in reference to" on cron receipts in the Inbox (an OTTransaction).
// 2. The UPDATED VERSION of that same cron item (a trade or payment plan) is stored in the ATTACHMENT on the OTItem member.
// 3. ADDITIONAL INFORMATION is stored in the NOTE field of the OTItem member.
//
// Unfortunately, marketReceipt doesn't adhere to this convention, as it stores the Updated Cron Item (the trade) in
// the note instead of the attachment, and it stores the updated Offer (the additional info) in the attachment instead
// of the note.
// Perhaps this is for the best -- it will certainly kick out any accidental confusions between marketReceipt and finalReceipt!
// todo: switch marketReceipt over to be like finalReceipt as described in this paragraph.
//
// Once everything is consistent on the above convention -- starting here and now with finalReceipt -- then we will ALWAYS
// be able to count on a Cron Item being in the Transaction Item's Attachment! We can load it using the existing factory class,
// without regard to type, KNOWING it's a cron item every time.
// todo: convert marketReceipt to do the same.
// -------------------------------------------------
// The finalReceipt Item's ATTACHMENT contains the UPDATED Cron Item.
// (With the SERVER's signature on it!)
//
OTString strUpdatedCronItem(*this); OTString * pstrAttachment = &strUpdatedCronItem; // the Updated TRADE.
OTString strUpdatedOffer; OTString * pstrNote = NULL; // the updated Offer (if available.)
if (m_pOffer)
{
m_pOffer->SaveContractRaw(strUpdatedOffer);
pstrNote = &strUpdatedOffer;
}
const OTString strOrigCronItem(theOrigCronItem);
bool bDroppedReceiptAssetAcct = false;
bool bDroppedReceiptCurrencyAcct = false;
// -----------------------------------------------------------------
OTPseudonym * pActualNym = NULL; // use this. DON'T use theActualNym.
OTPseudonym theActualNym; // unused unless it's really not already loaded. (use pActualNym.)
// -----------------------------------------------------------------
// The OPENING transaction number must still be signed-out.
// It is this act of placing the final receipt, which then finally closes the opening number.
// The closing number, by contrast, is not closed out until the final Receipt is ACCEPTED
// (which happens in a "process inbox" transaction.)
//
if ((lOpeningNumber > 0) &&
theOriginator.VerifyIssuedNum(strServerID, lOpeningNumber))
{
// The Nym (server side) stores a list of all opening and closing cron #s.
// So when the number is released from the Nym, we also take it off that list.
//
std::set<long> & theIDSet = theOriginator.GetSetOpenCronItems();
theIDSet.erase(lOpeningNumber);
theOriginator.RemoveIssuedNum(*pServerNym, strServerID, lOpeningNumber, false); //bSave=false
theOriginator.SaveSignedNymfile(*pServerNym); // forcing a save here, since multiple things have changed.
// -----------------------
const OTIdentifier ACTUAL_NYM_ID = GetSenderUserID();
if ( (NULL != pServerNym) && pServerNym->CompareID(ACTUAL_NYM_ID) )
pActualNym = pServerNym;
else if (theOriginator.CompareID(ACTUAL_NYM_ID))
pActualNym = &theOriginator;
else if ( (NULL != pRemover) && pRemover->CompareID(ACTUAL_NYM_ID) )
pActualNym = pRemover;
// --------------------------
else // We couldn't find the Nym among those already loaded--so we have to load
{ // it ourselves (so we can update its NymboxHash value.)
theActualNym.SetIdentifier(ACTUAL_NYM_ID);
if (false == theActualNym.LoadPublicKey()) // Note: this step may be unnecessary since we are only updating his Nymfile, not his key.
{
OTString strNymID(ACTUAL_NYM_ID);
OTLog::vError("%s: Failure loading public key for Nym: %s. "
"(To update his NymboxHash.) \n", szFunc, strNymID.Get());
}
else if (theActualNym.VerifyPseudonym() && // this line may be unnecessary.
theActualNym.LoadSignedNymfile(*pServerNym)) // ServerNym here is not theActualNym's identity, but merely the signer on this file.
{
OTLog::vOutput(3, "%s: Loading actual Nym, since he wasn't already loaded. "
"(To update his NymboxHash.)\n", szFunc);
pActualNym = &theActualNym; // <=====
}
else
{
OTString strNymID(ACTUAL_NYM_ID);
OTLog::vError("%s: Failure loading or verifying Actual Nym public key: %s. "
"(To update his NymboxHash.)\n", szFunc, strNymID.Get());
}
}
// -------------
if (false == this->DropFinalReceiptToNymbox(GetSenderUserID(),
lNewTransactionNumber,
strOrigCronItem,
pstrNote,
pstrAttachment,
pActualNym))
{
OTLog::vError("%s: Failure dropping receipt into nymbox.\n", szFunc);
}
}
else
{
OTLog::vError("%s: Problem verifying Opening Number when calling "
"VerifyIssuedNum(lOpeningNumber)\n", szFunc);
}
// ***************************************************************************************
// ASSET ACCT
//
if ((lClosingAssetNumber > 0) &&
theOriginator.VerifyIssuedNum(strServerID, lClosingAssetNumber)
)
{
bDroppedReceiptAssetAcct = this->DropFinalReceiptToInbox(GetSenderUserID(),
GetSenderAcctID(),
lNewTransactionNumber,
lClosingAssetNumber, // The closing transaction number to put on the receipt.
strOrigCronItem,
pstrNote,
pstrAttachment);
}
else
{
OTLog::vError("%s: Failed verifying lClosingAssetNumber=theOrigCronItem.GetClosingTransactionNoAt(0)>0 && "
"theOriginator.VerifyTransactionNum(lClosingAssetNumber)\n", szFunc);
}
// ***************************************************************************************
// CURRENCY ACCT
//
if ((lClosingCurrencyNumber > 0) &&
theOriginator.VerifyIssuedNum(strServerID, lClosingCurrencyNumber)
)
{
bDroppedReceiptCurrencyAcct = this->DropFinalReceiptToInbox(GetSenderUserID(),
GetCurrencyAcctID(),
lNewTransactionNumber,
lClosingCurrencyNumber, // closing transaction number for the receipt.
strOrigCronItem,
pstrNote,
pstrAttachment);
}
else
{
OTLog::vError("%s: Failed verifying lClosingCurrencyNumber=theOrigCronItem.GetClosingTransactionNoAt(1)>0 "
"&& theOriginator.VerifyTransactionNum(lClosingCurrencyNumber)\n", szFunc);
}
// ***************************************************************************************
// the RemoveIssued call means the original transaction# (to find this cron item on cron) is now CLOSED.
// But the Transaction itself is still OPEN. How? Because the CLOSING number is still signed out.
// The closing number is also USED, since the NotarizePaymentPlan or NotarizeMarketOffer call, but it
// remains ISSUED, until the final receipt itself is accepted during a process inbox.
//
// if (bDroppedReceiptAssetAcct || bDroppedReceiptCurrencyAcct) // ASSET ACCOUNT and CURRENCY ACCOUNT
// {
// This part below doesn't happen until you ACCEPT the finalReceipt (when processing your inbox.)
//
// if (bDroppedReceiptAssetAcct)
// theOriginator.RemoveIssuedNum(strServerID, lClosingAssetNumber, true); //bSave=false
// else if (bDroppedReceiptCurrencyAcct)
// theOriginator.RemoveIssuedNum(strServerID, lClosingCurrencyNumber, true); //bSave=false
// }
// else
// {
// OTLog::Error("OTTrade::onFinalReceipt: Failure dropping receipt into asset or currency inbox.\n");
// }
// QUESTION: Won't there be Cron Items that have no asset account at all?
// In which case, there'd be no need to drop a final receipt, but I don't think
// that's the case, since you have to use a transaction number to get onto cron
// in the first place.
// -----------------------------------------------------------------
}
// OTCron calls this regularly, which is my chance to expire, etc.
// Return True if I should stay on the Cron list for more processing.
// Return False if I should be removed and deleted.
bool OTTrade::ProcessCron()
{
// -----------------------------------------------------------------
// Right now Cron is called 10 times per second.
// I'm going to slow down all trades so they are once every GetProcessInterval()
if (GetLastProcessDate() > 0)
{
// (Default ProcessInterval is 1 second, but Trades will use 10 seconds,
// and Payment Plans will use an hour or day.)
if ((GetCurrentTime() - GetLastProcessDate()) <= GetProcessInterval())
return true;
}
// Keep a record of the last time this was processed.
// (NOT saved to storage, only used while the software is running.)
// (Thus no need to release signatures, sign contract, save contract, etc.)
SetLastProcessDate(GetCurrentTime());
// -----------------------------------------------------------------
// PAST END DATE? --------------------------------
// First call the parent's version (which this overrides) so it has
// a chance to check its stuff. Currently it checks IsExpired().
if (false == ot_super::ProcessCron())
return false; // It's expired or flagged for removal--remove it from Cron.
// You might ask, why not check here if this trade is flagged for removal?
// Supposedly the answer is, because it's only below that I have the market pointer,
// and am able to remove the corresponding trade from the market.
// Therefore I am adding a hook for "onRemoval" so that Objects such as OTTrade ALWAYS
// have the opportunity to perform such cleanup, without having to juggle such logic.
// REACHED START DATE? --------------------------------
// Okay, so it's not expired. But might not have reached START DATE yet...
if (!VerifyCurrentDate())
return true; // The Trade is not yet valid, so we return. BUT, we return
// true, so it will stay on Cron until it BECOMES valid.
// TRADE-specific stuff below. --------------------------------
bool bStayOnMarket = true; // by default stay on the market (until some rule expires me.)
OTIdentifier OFFER_MARKET_ID;
OTMarket * pMarket = NULL;
// If the Offer is already active on a market, then I already have a pointer to
// it. This function returns that pointer. If NULL, it tries to find the offer on
// the market and then sets the pointer and returns. If it can't find it, IT TRIES
// TO ADD IT TO THE MARKET and sets the pointer and returns it.
OTOffer * pOffer = GetOffer(&OFFER_MARKET_ID, &pMarket); // Both of these parameters are optional.
// In this case, the offer is NOT on the market.
// Perhaps it wasn't ready to activate yet.
if (NULL == pOffer)
{
// The offer SHOULD HAVE been on the market, since we're within the valid range,
// and GetOffer adds it when it's not already there.
OTLog::Error("OTTrade::ProcessCron: Offer SHOULD have been on Market. I might ASSERT this.\n"); // comment this out
// Actually! If it's a Stop Order, then it WOULD be within the valid range, yet would
// not yet have activated. So I don't want to log some big error every time a stop order
// checks its prices.
}
else if (NULL == pMarket)
{
//todo. (This will already leave a log above in GetOffer somewhere.)
OTLog::Error("OTTrade::ProcessCron: Market was NULL.\n"); // comment this out
}
else // If a valid pointer was returned, that means the offer is on the market.
{
// Make sure it hasn't already been flagged by someone else...
if (this->IsFlaggedForRemoval()) // This is checked above in OTCronItem::ProcessCron().
bStayOnMarket = false; // I'm leaving the check here in case the flag was set since then
else
{ // Process it! <===================
OTLog::vOutput(2, "Processing trade: %ld.\n", GetTransactionNum());
bStayOnMarket = pMarket->ProcessTrade(*this, *pOffer);
// No need to save the Trade or Offer, since they will
// be saved inside this call if they are changed.
}
}
// Return True if I should stay on the Cron list for more processing.
// Return False if I should be removed and deleted.
return bStayOnMarket; // defaults true, so if false, that means someone is removing it for a reason.
}
/*
X OTIdentifier m_CURRENCY_TYPE_ID; // GOLD (Asset) is trading for DOLLARS (Currency).
X OTIdentifier m_CURRENCY_ACCT_ID; // My Dollar account, used for paying for my Gold (say) trades.
X long m_lStopPrice; // The price limit that activates the STOP order.
X char m_cStopSign; // Value is 0, or '<', or '>'.
X time_t m_CREATION_DATE; // The date, in seconds, when the trade was authorized.
X int m_nTradesAlreadyDone; // How many trades have already processed through this order? We keep track.
*/
// This is called by the client side. First you call MakeOffer() to set up the Offer,
// then you call IssueTrade() and pass the Offer into it here.
bool OTTrade::IssueTrade(OTOffer & theOffer, char cStopSign/*=0*/, long lStopPrice/*=0*/)
{
// Make sure the Stop Sign is within parameters (0, '<', or '>')
if ((cStopSign == 0 ) ||
(cStopSign == '<') ||
(cStopSign == '>'))
m_cStopSign = cStopSign;
else
{
OTLog::vError("Bad data in Stop Sign while issuing trade: %c\n", cStopSign);
return false;
}
// Make sure, if this IS a Stop order, that the price is within parameters and set.
if ((m_cStopSign == '<') ||
(m_cStopSign == '>'))
{
if (0 >= lStopPrice)
{
OTLog::Error("Expected Stop Price for trade.\n");
return false;
}
m_lStopPrice = lStopPrice;
}
m_nTradesAlreadyDone = 0;
SetCreationDate(time(NULL)); // This time is set to TODAY NOW (OTCronItem)
// ------------------------------------------------------------------------
// Validate the Server ID, Asset Type ID, Currency Type ID, and Date Range.
if ((GetServerID() != theOffer.GetServerID()) ||
(GetCurrencyID() != theOffer.GetCurrencyID()) ||
(GetAssetID() != theOffer.GetAssetID()) ||
(theOffer.GetValidFrom() < 0) ||
(theOffer.GetValidTo() < theOffer.GetValidFrom()) )
{
return false;
}
// m_CURRENCY_TYPE_ID // This is already set in the constructors of this and the offer. (And compared.)
// m_CURRENCY_ACCT_ID // This is already set in the constructor of this.
// Set the (now validated) date range as per the Offer.
SetValidFrom(theOffer.GetValidFrom());
SetValidTo(theOffer.GetValidTo());
// Get the transaction number from the Offer.
SetTransactionNum(theOffer.GetTransactionNum());
// Save a copy of the offer, in XML form, here on this Trade.
OTString strOffer(theOffer);
m_strOffer.Set(strOffer);
return true;
}
OTTrade::OTTrade() : ot_super(), m_pOffer(NULL),
m_bHasTradeActivated(false),
m_lStopPrice(0),
m_cStopSign(0),
m_bHasStopActivated(false),
m_nTradesAlreadyDone(0)
{
// m_pOffer = NULL; // NOT responsible to clean this up. Just keeping the pointer for convenience.
// You might ask, "but what if it goes bad?" Actually only THIS object should ever decide that.
// Only the Trade object decides when to add or remove an offer from any market.
InitTrade();
}
OTTrade::OTTrade(const OTIdentifier & SERVER_ID, const OTIdentifier & ASSET_ID) :
ot_super(SERVER_ID, ASSET_ID), m_pOffer(NULL),
m_bHasTradeActivated(false),
m_lStopPrice(0),
m_cStopSign(0),
m_bHasStopActivated(false),
m_nTradesAlreadyDone(0)
{
// m_pOffer = NULL; // NOT responsible to clean this up. Just keeping the pointer for convenience.
// You might ask, "but what if it goes bad?" Actually only THIS object should ever decide that.
// Only the Trade object decides when to add or remove an offer from any market.
InitTrade();
}
OTTrade::OTTrade(const OTIdentifier & SERVER_ID,
const OTIdentifier & ASSET_ID, const OTIdentifier & ASSET_ACCT_ID,
const OTIdentifier & USER_ID,
const OTIdentifier & CURRENCY_ID, const OTIdentifier & CURRENCY_ACCT_ID) :
ot_super(SERVER_ID, ASSET_ID, ASSET_ACCT_ID, USER_ID), m_pOffer(NULL),
m_bHasTradeActivated(false),
m_lStopPrice(0),
m_cStopSign(0),
m_bHasStopActivated(false),
m_nTradesAlreadyDone(0)
{
// m_pOffer = NULL; // NOT responsible to clean this up. Just keeping the pointer for convenience.
// You might ask, "but what if it goes bad?" Actually only THIS object should ever decide that.
// Only the Trade object decides when to add or remove an offer from any market.
InitTrade();
SetCurrencyID(CURRENCY_ID);
SetCurrencyAcctID(CURRENCY_ACCT_ID);
}
OTTrade::~OTTrade()
{
Release_Trade();
}
// the framework will call this at the right time.
void OTTrade::Release_Trade()
{
// If there were any dynamically allocated objects, clean them up here.
m_CURRENCY_TYPE_ID.Release();
m_CURRENCY_ACCT_ID.Release();
m_strOffer.Release();
}
// the framework will call this at the right time.
void OTTrade::Release()
{
Release_Trade();
ot_super::Release();
// Then I call this to re-initialize everything
// (Only cause it's convenient...)
InitTrade();
}
// This CAN have values that are reset
void OTTrade::InitTrade()
{
// initialization here. Sometimes also called during cleanup to zero values.
m_strContractType = "TRADE";
SetProcessInterval(TRADE_PROCESS_INTERVAL); // Trades default to processing every 10 seconds.
// (vs 1 second for Cron items and 1 hour for payment plans)
m_nTradesAlreadyDone= 0;
m_cStopSign = 0; // IS THIS a STOP order? Value is 0, or '<', or '>'.
m_lStopPrice = 0; // The price limit that activates the STOP order.
m_bHasStopActivated = false;// Once the Stop Order activates, it puts the order on the market.
// I'll put a "HasOrderOnMarket()" bool method that answers this for u.
m_bHasTradeActivated = false;// I want to keep track of general activations as well, not just stop orders.
}
bool OTTrade::SaveContractWallet(std::ofstream & ofs)
{
return true;
}
| [
"F3llowTraveler@gmail.com"
] | F3llowTraveler@gmail.com |
0925380eedf12b9ec808534795fc0c5dfd5e4f92 | 756a3480b2d2b124d626d6b212fe9ffd9a69bded | /dependencies/include/asio/detail/executor_function.hpp | e3f6b7d02ab8eb98803d19415d092ec8ceb4bf37 | [
"MIT"
] | permissive | tamakoji/rpclib | 4b6b62f48f4385c75ca55afcc334fdc8eb629641 | 02fc98499b18601747fa2cebe2c05d5ce169eadd | refs/heads/master | 2022-09-14T06:44:37.161858 | 2020-05-30T23:35:29 | 2020-05-31T03:14:46 | 267,945,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,566 | hpp | //
// detail/executor_function.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef ASIO_DETAIL_EXECUTOR_FUNCTION_HPP
#define ASIO_DETAIL_EXECUTOR_FUNCTION_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/handler_alloc_helpers.hpp"
#include "asio/detail/push_options.hpp"
namespace clmdep_asio {
namespace detail {
class executor_function_base
{
public:
void complete()
{
func_(this, true);
}
void destroy()
{
func_(this, false);
}
protected:
typedef void (*func_type)(executor_function_base*, bool);
executor_function_base(func_type func)
: func_(func)
{
}
// Prevents deletion through this type.
~executor_function_base()
{
}
private:
func_type func_;
};
template <typename Function, typename Alloc>
class executor_function : public executor_function_base
{
public:
ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR(
thread_info_base::executor_function_tag, executor_function);
template <typename F>
executor_function(ASIO_MOVE_ARG(F) f, const Alloc& allocator)
: executor_function_base(&executor_function::do_complete),
function_(ASIO_MOVE_CAST(F)(f)),
allocator_(allocator)
{
}
static void do_complete(executor_function_base* base, bool call)
{
// Take ownership of the function object.
executor_function* o(static_cast<executor_function*>(base));
Alloc allocator(o->allocator_);
ptr p = { detail::addressof(allocator), o, o };
// Make a copy of the function so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the function may be the true owner of the memory
// associated with the function. Consequently, a local copy of the function
// is required to ensure that any owning sub-object remains valid until
// after we have deallocated the memory here.
Function function(ASIO_MOVE_CAST(Function)(o->function_));
p.reset();
// Make the upcall if required.
if (call)
{
function();
}
}
private:
Function function_;
Alloc allocator_;
};
} // namespace detail
} // namespace clmdep_asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_EXECUTOR_FUNCTION_HPP
| [
"tamakoji@gmail.com"
] | tamakoji@gmail.com |
babf50df5a47f86b03be2ae1eefb756312af58c3 | 1299ac96720d9c6c050a2c066f108e8fd7f8e1df | /assign3/network.cpp | 3657461665191aaf54fb7bf55a7b2e7ea7fa825b | [] | no_license | JaegarSarauer/LinuxChat | 8a9b4bf8c2af017b75cbd3f829c0cc83c828bee4 | 361d61d4437badbfbbd292b688dece80b231494d | refs/heads/master | 2020-04-01T15:09:06.601381 | 2016-03-06T07:34:58 | 2016-03-06T07:34:58 | 53,284,278 | 0 | 0 | null | 2016-03-07T00:38:34 | 2016-03-07T00:38:33 | C++ | UTF-8 | C++ | false | false | 2,072 | cpp | #include "network.h"
#include "mainwindow.h"
int file = 0;
int sd, connected;
char name[BUFLEN];
time_t t;
struct tm *tm;
MainWindow *window;
void startConnection(MainWindow *w, const char *username, const char *IP , int port, const char *fileName){
struct hostent *hp;
struct sockaddr_in server;
window = w;
sprintf(name,username);
connected = 1;
if(fileName != NULL){
file = creat(fileName, O_RDWR);
}
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("Cannot create socket");
exit(1);
}
bzero((char *)&server, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
if ((hp = gethostbyname(IP)) == NULL){
fprintf(stderr, "Unknown server address\n");
exit(1);
}
bcopy(hp->h_addr, (char *)&server.sin_addr, hp->h_length);
// Connecting to the server
if (connect (sd, (struct sockaddr *)&server, sizeof(server)) == -1){
fprintf(stderr, "Can't connect to server\n");
perror("connect");
exit(1);
}else{
window->successfulConnection();
}
std::thread t1(receiveFromServer);
t1.detach();
}
void receiveFromServer(){
char *bp, rbuf[BUFLEN];
int bytes_to_read, n;
while(connected){
bp = rbuf;
bytes_to_read = BUFLEN;
// client makes repeated calls to recv until no more data is expected to arrive.
n = 0;
while ((n = recv (sd, bp, bytes_to_read, 0)) < BUFLEN){
bp += n;
bytes_to_read -= n;
}
window->Print(rbuf);
if(file){
t = time(NULL);
tm = localtime(&t);
write(file, asctime(tm), strlen(asctime(tm)));
write(file, rbuf, strlen(rbuf));
}
}
}
void sendToServer(const char *msg){
char sbuf[BUFLEN];
sprintf(sbuf,"%s: %s",name, msg);
send (sd, sbuf, BUFLEN, 0);
window->Print(rbuf);
if(file){
t = time(NULL);
tm = localtime(&t);
write(file, asctime(tm), strlen(asctime(tm)));
write(file, sbuf, strlen(sbuf));
write(file,"\n",1);
}
}
void disconnect(){
if(file){
close(file);
}
connected = 0;
close(sd);
}
| [
"tomtang_13@hotmail.com"
] | tomtang_13@hotmail.com |
c2ef46ee80a1b9216d5399b48c797f7816be9de6 | ea3719ca6418482df5d1bbe38851114684794e9f | /Algorithms/206. Reverse Linked List/206. Reverse Linked List - stack.cpp | 656324b22574776e5a6114d1f8fbae14906d81db | [] | no_license | JokerLbz/Leetcode | 131335a48b1607df31c1e1b23b81b3acb1eaad38 | 26f0e97c5168c45929dac5d7d41c78eef8321a56 | refs/heads/master | 2020-04-25T08:59:41.535235 | 2019-04-20T12:58:07 | 2019-04-20T12:58:07 | 172,664,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | //Approach : stack
// √ 27/27 cases passed (12 ms)
// √ Your runtime beats 55.09 % of cpp submissions
// √ Your memory usage beats 58.29 % of cpp submissions (9.2 MB)
// T/S Complexity : O(n)/O(n)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return nullptr;
stack<ListNode* > s;
while(head)
{
ListNode* temp = head;
s.push(head);
head = head->next;
temp->next = nullptr;
}
ListNode *dummy = new ListNode(0);
head = dummy;
while(!s.empty())
{
head->next = s.top();
head = head->next;
s.pop();
}
return dummy->next;
}
}; | [
"lbz1996@hotmail.com"
] | lbz1996@hotmail.com |
555ab7e2c155e89333a65183e1e348ab784806ba | 03ee754445d2dc6abbb3c1f2a57a35519f8acc96 | /New Folder/Antora.cpp | b3db49a5bb96257a58c6f57a94bfe79f2fd70c35 | [] | no_license | mizan-cs/Practise-Code | d34a67d1f3ea7a9a81e8096020227b705ca5ec13 | 74b21d810c242af249a17ec8fef683fdb3c0d1b0 | refs/heads/master | 2021-01-19T21:19:25.831029 | 2017-09-09T03:23:47 | 2017-09-09T03:23:47 | 101,249,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
double x,y=0;
cin>>x;
y=((x-1)/x)+(1/2)*pow(((x-1)/x),2)+(1/3)*pow(((x-1)/x),3);
cout<<y;
}
| [
"mysalfe02@gmail.com"
] | mysalfe02@gmail.com |
00d631f52488b678ba188ab5bf20085af68c8c72 | 94b34f4b099166bdda3c69e2b224718e890b9fa4 | /tv_src/libraries/include/blockchain/ChainDatabaseImpl.hpp | 893179fb0d33d98b6c30acfa24b63116babe06d5 | [] | no_license | HomeFourtune/Ti-Value | 426714bbf46d81ae2cb26738ac578657921a8f1d | 46f7f72ba64eddcd5fd836041d85182e3f5f45f6 | refs/heads/master | 2021-05-05T12:12:29.223559 | 2017-11-30T10:05:54 | 2017-11-30T10:05:54 | 104,722,073 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 20,357 | hpp | #pragma once
#include <blockchain/ChainDatabase.hpp>
#include <db/CachedLevelMap.hpp>
#include <db/FastLevelMap.hpp>
#include <fc/thread/mutex.hpp>
#include <utilities/ThreadPool.hpp>
namespace TiValue {
namespace blockchain {
struct fee_index
{
ShareType _fees = 0;
TransactionIdType _trx;
fee_index(ShareType fees = 0, TransactionIdType trx = TransactionIdType())
:_fees(fees), _trx(trx){}
friend bool operator == (const fee_index& a, const fee_index& b)
{
return std::tie(a._fees, a._trx) == std::tie(b._fees, b._trx);
}
friend bool operator < (const fee_index& a, const fee_index& b)
{
// Reverse so that highest fee is placed first in sorted maps
return std::tie(a._fees, a._trx) > std::tie(b._fees, b._trx);
}
};
struct data_version
{
BlockIdType id;
int version;
};
namespace detail
{
class ChainDatabaseImpl
{
public:
/**
* load checkpoints from file
* @param data_dir directory that stores checkpoints
*
* @return void
*/
void load_checkpoints(const fc::path& data_dir)const;
/**
* Checks whether replaying is require
* Get database_version from property database and check whether it equals to TIV_BLOCKCHAIN_DATABASE_VERSION
* @param data_dir path of property database
*
* @return bool
*/
bool replay_required(const fc::path& data_dir);
/**
* load database from specified directory
* @param data_dir path of database
*
* @return void
*/
void open_database(const fc::path& data_dir);
/** clear_invalidation_of_future_blocks
* Remove blocks whose block time is 2 days ago from future block list and clear other blocks' invalid flag
*
* @return void
*/
void clear_invalidation_of_future_blocks();
/** initialize_genesis
* Load data of genesis into database
* @param optional<path>& path of the genesis file.If it's invalid,load data from builtin genesis
* @param bool statistics_enabled
*
* @return DigestType
*/
DigestType initialize_genesis(const optional<path>& genesis_file,
const bool statistics_enabled);
/** populate_indexes
*
* Sorts delegates according votes and puts transaction into unique set
*
* @return void
*/
void populate_indexes();
/** store_and_index
* Store a block into database and organize related data
* @param block_id id of the block
* @param block_data FullBlock
*
* @return std::pair<BlockIdType,
*/
std::pair<BlockIdType, BlockForkData> store_and_index(const BlockIdType& id, const FullBlock& blk);
/** clear_pending
* Remove transactions which are contained in specified block and start a revalidating procedure
* @param block_data FullBlock
*
* @return void
*/
void clear_pending(const FullBlock& block_data);
/*
* revalidate transactions in pending database
*
* @return void
*/
void revalidate_pending();
/** switch_to_fork
* Marks the fork which the specified block are in it to be the current chain
* @param block_id id of the specified block
*
* @return void
*/
void switch_to_fork(const BlockIdType& block_id);
/** extend_chain
* Performs all of the block validation steps and throws if error.
* @param block_data FullBlock
*
* @return void
*/
void extend_chain(const FullBlock& blk);
/** get_fork_history
* Traverse the previous links of all blocks in fork until we find one that is_included
*
* The last item in the result will be the only block id that is already included in
* the blockchain.
*
* @param id BlockIdType
*
* @return std::vector<BlockIdType>
*/
vector<BlockIdType> get_fork_history(const BlockIdType& id);
/** pop_block
*
* Pop the headblock from current chain and undo changes which are made by the head block
*
* @return void
*/
void pop_block();
void repair_block(BlockIdType block_id);
/** mark_invalid
* fetch the fork data for block_id, mark it as invalid and
* then mark every item after it as invalid as well.
* @param block_id BlockIdType
* @param reason fc::exception
*
* @return void
*/
void mark_invalid(const BlockIdType& id, const fc::exception& reason);
/** mark_as_unchecked
* fetch the fork data for block_id, mark it as unchecked
* @param block_id BlockIdType
*
* @return void
*/
void mark_as_unchecked(const BlockIdType& id);
/** mark_included
* fetch the fork data for block_id, mark it as included or not included
* @param block_id BlockIdType
* @param included bool
*
* @return void
*/
void mark_included(const BlockIdType& id, bool state);
/** fetch_blocks_at_number
* fetch ids of block at specified number
* @param block_num uint32_t
*
* @return std::vector<BlockIdType>
*/
std::vector<BlockIdType> fetch_blocks_at_number(uint32_t block_num);
/** recursive_mark_as_linked
* fetch the fork data for block_id, mark it as linked and
* then mark every item after it as linked as well.
*
* @param ids std::unordered_set<BlockIdType>
*
* @return std::pair<BlockIdType,
*/
std::pair<BlockIdType, BlockForkData> recursive_mark_as_linked(const std::unordered_set<BlockIdType>& ids);
/** recursive_mark_as_invalid
* Mark blocks as invalid recursively
* @param ids std::unordered_set<BlockIdType>
* @param reason fc::exception
*
* @return void
*/
void recursive_mark_as_invalid(const std::unordered_set<BlockIdType>& ids,
const fc::exception& reason);
/** verify_header
* Verify signee of the block
* @param block_digest DigestBlock
* @param block_signee PublicKeyType
*
* @return void
*/
void verify_header(const DigestBlock& block_digest,
const PublicKeyType& block_signee)const;
/** update_delegate_production_info
* Update production info for signing delegate
* @param block_header BlockHeader
* @param block_id BlockIdType
* @param block_signee public key of signing delegate
* @param pending_state PendingChainStatePtr
*
* @return void
*/
void update_delegate_production_info(const BlockHeader& BlockHeader,
const BlockIdType& block_id,
const PublicKeyType& block_signee,
const PendingChainStatePtr& pending_state)const;
/** pay_delegate
* Pay salaries to specified delegates
* @param block_id BlockIdType
* @param block_signee public key of the delegate to be paid
* @param pending_state PendingChainStatePtr
* @param entry oBlockEntry
*
* @return void
*/
void pay_delegate(const BlockIdType& block_id,
const PublicKeyType& block_signee,
const PendingChainStatePtr& pending_state,
oBlockEntry& block_entry)const;
// void execute_markets( const time_point_sec timestamp,
// const pending_chain_state_ptr& pending_state )const;
/** apply_transactions
* Apply transactions contained in the block
* @param block_data the block that contains transactions
* @param pending_state PendingChainStatePtr
*
* @return void
*/
void apply_transactions(const FullBlock& block_data,
const PendingChainStatePtr& pending_state);
/** update_active_delegate_list
* Get a list of active delegate that would participate in generating blocks in next round
* @param block_num uint32_t
* @param pending_state PendingChainStatePtr
*
* @return void
*/
void update_active_delegate_list(const uint32_t block_num,
const PendingChainStatePtr& pending_state)const;
/** update_random_seed
* Caculate the random seed based on a secret and the random seed
* @param new_secret
* @param pending_state PendingChainStatePtr
* @param entry oBlockEntry
*
* @return void
*/
void update_random_seed(const SecretHashType& new_secret,
const PendingChainStatePtr& pending_state,
oBlockEntry& block_entry)const;
/** save_undo_state
* Save current state and block_id into undo_state map
* @param block_num number of the block
* @param block_id id of the block
* @param pending_state State need to be saved
*
* @return void
*/
void save_undo_state(const uint32_t block_num,
const BlockIdType& block_id,
const PendingChainStatePtr& pending_state);
/** update_head_block
* Update information about head block
* @param block_header SignedBlockHeader
* @param block_id BlockIdType
*
* @return void
*/
void update_head_block(const SignedBlockHeader& block_header,
const BlockIdType& block_id);
void pay_delegate_v2(const BlockIdType& block_id,
const PublicKeyType& block_signee,
const PendingChainStatePtr& pending_state,
oBlockEntry& block_entry)const;
void pay_delegate_v1(const BlockIdType& block_id,
const PublicKeyType& block_signee,
const PendingChainStatePtr& pending_state,
oBlockEntry& block_entry)const;
//void update_active_delegate_list_v1( const uint32_t block_num,
// const pending_chain_state_ptr& pending_state )const;
ChainDatabase* self = nullptr;
unordered_set<ChainObserver*> _observers;
/* Transaction propagation */
/** revalidate_pending
*
*
* @return void
*/
fc::future<void> _revalidate_pending;
ThreadPool _thread_pool;
PendingChainStatePtr _pending_trx_state = nullptr;
TiValue::db::LevelMap<TransactionIdType, SignedTransaction> _pending_transaction_db;
map<fee_index, TransactionEvaluationStatePtr> _pending_fee_index;
ShareType _relay_fee = TIV_BLOCKCHAIN_DEFAULT_RELAY_FEE;
/* Block processing */
uint32_t /* Only used to skip undo states when possible during replay */ _min_undo_block = 0;
fc::mutex _push_block_mutex;
ShareType _block_per_account_reword_amount = TIV_MAX_DELEGATE_PAY_PER_BLOCK;
TiValue::db::LevelMap<BlockIdType, FullBlock> _block_id_to_full_block;
TiValue::db::fast_level_map<BlockIdType, PendingChainState> _block_id_to_undo_state;
TiValue::db::LevelMap<uint32_t, vector<BlockIdType>> _fork_number_db; // All siblings
TiValue::db::LevelMap<BlockIdType, BlockForkData> _fork_db;
TiValue::db::LevelMap<BlockIdType, int32_t> _revalidatable_future_blocks_db; //int32_t is unused, this is a set
TiValue::db::LevelMap<uint32_t, BlockIdType> _block_num_to_id_db; // Current chain
TiValue::db::LevelMap<BlockIdType, BlockEntry> _block_id_to_block_entry_db; // Statistics
/* Current primary state */
BlockIdType _head_block_id;
SignedBlockHeader _head_block_header;
TiValue::db::fast_level_map<uint8_t, PropertyEntry> _property_id_to_entry;
TiValue::db::fast_level_map<AccountIdType, AccountEntry> _account_id_to_entry;
TiValue::db::fast_level_map<string, AccountIdType> _account_name_to_id;
TiValue::db::fast_level_map<Address, AccountIdType> _account_address_to_id;
set<VoteDel> _delegate_votes;
TiValue::db::fast_level_map<AssetIdType, AssetEntry> _asset_id_to_entry;
TiValue::db::fast_level_map<string, AssetIdType> _asset_symbol_to_id;
TiValue::db::fast_level_map<SlateIdType, SlateEntry> _slate_id_to_entry;
TiValue::db::fast_level_map<BalanceIdType, BalanceEntry> _balance_id_to_entry;
TiValue::db::LevelMap<TransactionIdType, TransactionEntry> _transaction_id_to_entry;
set<UniqueTransactionKey> _unique_transactions;
TiValue::db::LevelMap<Address, unordered_set<TransactionIdType>> _address_to_transaction_ids;
TiValue::db::LevelMap<SlotIndex, SlotEntry> _slot_index_to_entry;
TiValue::db::LevelMap<time_point_sec, AccountIdType> _slot_timestamp_to_delegate;
TiValue::db::LevelMap<int, data_version> _block_extend_status;
// TODO: Just store whitelist in asset_entry
//TiValue::db::level_map<pair<asset_id_type,address>, object_id_type> _auth_db;
map<OperationTypeEnum, std::deque<Operation>> _recent_operations;
// contract related db
TiValue::db::fast_level_map<ContractIdType, ContractEntry> _contract_id_to_entry;
TiValue::db::fast_level_map<ContractIdType, ContractStorageEntry> _contract_id_to_storage;
TiValue::db::fast_level_map<ContractName, ContractIdType> _contract_name_to_id;
TiValue::db::fast_level_map<TransactionIdType, ResultTIdEntry> _request_to_result_iddb;
TiValue::db::fast_level_map<TransactionIdType, RequestIdEntry> _result_to_request_iddb;
TiValue::db::fast_level_map<TransactionIdType, ContractinTrxEntry> _trx_to_contract_iddb;
TiValue::db::fast_level_map<ContractIdType,ContractTrxEntry> _contract_to_trx_iddb;
// sandbox contract related
PendingChainStatePtr _sandbox_pending_state = nullptr;
bool _is_in_sandbox = false;
//TiValue related db
TiValue::db::fast_level_map<FileIdType, UploadRequestEntry> _upload_request_db;
TiValue::db::fast_level_map<FilePieceIdType, StoreRequestEntry> _store_request_db;
TiValue::db::fast_level_map<FilePieceIdType, PieceSavedEntry> _piece_saved_db;
TiValue::db::fast_level_map<FileIdType, FileSavedEntry> _file_saved_db;
TiValue::db::fast_level_map<FileIdType, EnableAccessEntry> _enable_access_db;
TiValue::db::fast_level_map<FilePieceIdType, StoreRejectEntry> _reject_store_db;
TiValue::db::fast_level_map<FilePieceIdType, PieceSavedDeclEntry> _save_decl_db;
};
} // detail
}
} // TiValue::blockchain
FC_REFLECT_TYPENAME(std::vector<TiValue::blockchain::BlockIdType>)
FC_REFLECT_TYPENAME(std::unordered_set<TiValue::blockchain::TransactionIdType>)
FC_REFLECT(TiValue::blockchain::fee_index, (_fees)(_trx))
FC_REFLECT(TiValue::blockchain::data_version, (id)(version))
| [
"lester123@live.cn"
] | lester123@live.cn |
a7001e9ad80c8c9bb67dbffeb48674713c9726a8 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /extensions/renderer/file_system_natives.h | 87ad8c1b962a7610d6558b5e303fac86bb2a0852 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_RENDERER_FILE_SYSTEM_NATIVES_H_
#define EXTENSIONS_RENDERER_FILE_SYSTEM_NATIVES_H_
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "extensions/renderer/object_backed_native_handler.h"
namespace extensions {
class ScriptContext;
// Custom bindings for the nativeFileSystem API.
class FileSystemNatives : public ObjectBackedNativeHandler {
public:
explicit FileSystemNatives(ScriptContext* context);
private:
void GetFileEntry(const v8::FunctionCallbackInfo<v8::Value>& args);
void GetIsolatedFileSystem(const v8::FunctionCallbackInfo<v8::Value>& args);
void CrackIsolatedFileSystemName(
const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_COPY_AND_ASSIGN(FileSystemNatives);
};
} // namespace extensions
#endif // EXTENSIONS_RENDERER_FILE_SYSTEM_NATIVES_H_
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
29728f1c4fa6f9555513efab7cc3ca540071b139 | 310f18858c60fbfdf0948f5c519608a7f51bbb83 | /2020-10-31-A/main.cpp | 73e8236844ac59e243be3b488bf78a2cb9659be9 | [] | no_license | seal-git/atcoder | 03cece20a6189e79472c57cb9313a35db43b5754 | 13a7fb95eb34ee1d791f6fc838cf9c3dd056f9d5 | refs/heads/main | 2023-06-08T15:25:50.825569 | 2021-06-30T20:24:04 | 2021-06-30T20:24:04 | 361,208,122 | 0 | 0 | null | 2021-04-24T17:20:54 | 2021-04-24T16:13:37 | JavaScript | UTF-8 | C++ | false | false | 460 | cpp | #include <iostream>
#include <string>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <utility>
#include <vector>
#include <tuple>
#include <numeric>
using namespace std;
long long sum(long long i){
return(i*(i+1)/2);
}
int main(int argc, char* argv[]){
long long A,B,C;
cin >> A>>B>>C;
long long n = 998244353;
long long ans = (sum(A)%n);
ans *= (sum(B)%n);
ans %= n;
ans *= (sum(C)%n);
ans %= n;
cout << ans <<endl;
}
| [
"seal0828.4477@gmail.com"
] | seal0828.4477@gmail.com |
9a512aaaa8063b985e887eea29bb304c70cd56d6 | 03caddaec01057d953c6d17091cd37102f8fbec1 | /Source/Librarys/Library_GLFW3.h | 014b8a94fe85b84bfb2172a1e3d4599fb3ad2efa | [
"MIT"
] | permissive | STEAKISAWAKE/Vengence | debc7dad77fc4b62e1fb7848fe2d21a64d1d62a7 | b5010a41760fd8e47bee6c2b016eeb31d931f787 | refs/heads/master | 2020-12-13T15:21:40.718505 | 2020-01-18T16:51:36 | 2020-01-18T16:51:36 | 234,456,927 | 0 | 0 | null | 2020-01-17T03:08:29 | 2020-01-17T02:48:03 | C++ | UTF-8 | C++ | false | false | 249 | h | #ifndef ALIBRARY_GLFW3_H
#define ALIBRARY_GLFW3_H
#include "Library.h"
class ALibrary_GLFW3 : public ALibrary
{
public:
ALibrary_GLFW3();
virtual ~ALibrary_GLFW3();
protected:
private:
};
#endif // ALIBRARY_GLFW3_H
| [
"steakisawake@gitlab.com"
] | steakisawake@gitlab.com |
d2c9ff32b54287753b04e3a69b454f3d9c22961d | 5b32da16ecb16bba08a79d9cf8b46ce2b08662e0 | /Project3/view.cpp | fbc7737e9ce85cba9ba6d42dc8dde8fb12daf38f | [] | no_license | DashaMilitskaya/x-0 | 36ae14530469834dbb11157cf1520925abc02c57 | 914583206a2e30abad8a40776538f9dcc699d255 | refs/heads/main | 2023-01-05T10:14:04.685718 | 2020-10-23T09:13:29 | 2020-10-23T09:13:29 | 306,584,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp |
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "view.h"
using namespace Project3;
BoardView::BoardView(Board* _board)
{
board = _board;
}
/*
void BoardView::show(MyForm^ myForm)
{
unsigned int size = board->GetSize();
for (unsigned int i = 0; i < size; i++) {
for (unsigned int j = 0; j < size; j++) {
//gotoxy(i+1+i, j+1);
if (board->GetCell(i, j) == X) {
//std::cout << "X";
myForm->Controls->Add(Label)
}
else {
if (board->GetCell(i, j) == O) {
//std::cout << "0";
}
else {
//std::cout << "-";
}
}
}
}
}
*/
WinType BoardView::StartGame(MyForm^ myForm)
{
WinType winner = NONE;
unsigned int size = board->GetSize();
TableLayoutPanel^ table = gcnew TableLayoutPanel();
table->ColumnCount = size;
//table->AutoSize = true;
unsigned int x, y;
while (true) {
do{
// std::cout << "Player X move \n";
// std::cin >> x;
//std::cin >> y;
} while (!(board->MakeMove(x, y, X)));
winner = board->IsWin(X, x, y);
if (winner != NONE) break;
//gotoxy(1, size + 10);
do {
//std::cout << "Player 0 move";
// std::cin >> x;
//std::cin >> y;
} while (!(board->MakeMove(x, y, O)));
////show();
//winner = board->IsWin(O, x, y);
// if (winner != NONE) break;
}
return winner;
}
| [
"milic2012121@yandex.ru"
] | milic2012121@yandex.ru |
280224edc7719a4d7edf7b61e7b4b70692517787 | b558c57c46d8bc5897f8b162747ac03911819206 | /projects/matio/matio_fuzzer.cc | c97b8c89a5c341b8cd8ab6da5bdc80f7bc7dfd5b | [
"Apache-2.0"
] | permissive | intrigus-lgtm/oss-fuzz | f1f02ed98b8b509a21b3682ef92b39855bb86924 | a479ad9aa32cbcc8e37d7246e2a2bdd59766db92 | refs/heads/master | 2022-10-04T16:11:13.518378 | 2019-08-28T20:43:03 | 2019-08-28T20:43:03 | 260,313,814 | 0 | 0 | Apache-2.0 | 2020-04-30T20:39:30 | 2020-04-30T20:39:29 | null | UTF-8 | C++ | false | false | 1,287 | cc | // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Adapter utility from fuzzer input to a temporary file, for fuzzing APIs that
// require a file instead of an input buffer.
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>
#include "fuzzer_temp_file.h"
#include "matio.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
FuzzerTemporaryFile temp_file(data, size);
mat_t* matfd = Mat_Open(temp_file.filename(), MAT_ACC_RDONLY);
if (matfd == nullptr) {
return 0;
}
// TODO(https://github.com/google/oss-fuzz/pull/2761): use more complicated APIs
// such as Mat_VarReadDataAll, Mat_VarReadDataLinear, Mat_VarReadNext, etc.
Mat_Close(matfd);
return 0;
}
| [
"31354670+jonathanmetzman@users.noreply.github.com"
] | 31354670+jonathanmetzman@users.noreply.github.com |
a20d17fa2aae65a62c090fa84895039de67bdbaa | c61a4fcad61ac93225d55a8da06bb05c87c2a20d | /linkit_trunk/sketch_nov11a/sketch_nov11a.ino | a0c3ea1ed523701f02b68645428ae69994f1e4df | [] | no_license | j900155/Trunk | 33d5dad74b7481b8b05ad6c852c896b52f080cc0 | 11d6e1e18f9f4af8f95243e698664260ea87caf1 | refs/heads/master | 2021-01-10T10:25:51.816601 | 2015-11-22T01:19:05 | 2015-11-22T01:19:05 | 46,641,211 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 301 | ino | #include <UARTClass.h>
char val; // 儲存接收資料的變數
void setup() {
Serial.begin(9600); // 與電腦序列埠連線
Serial1.begin(9600);
Serial.println("BT is ready!");
}
void loop() {
if (Serial1.available()) {
val=Serial1.read();
Serial.println(val);
}
}
| [
"zack@localhost.localdomain"
] | zack@localhost.localdomain |
bf6a9914f3611bc42ecd7fa4059621d1047dc566 | 0f2b08b31fab269c77d4b14240b8746a3ba17d5e | /onnxruntime/core/providers/armnn/activation/activations.h | b75b7a836639534903dc4fb64e207f7f598b9360 | [
"MIT"
] | permissive | microsoft/onnxruntime | f75aa499496f4d0a07ab68ffa589d06f83b7db1d | 5e747071be882efd6b54d7a7421042e68dcd6aff | refs/heads/main | 2023-09-04T03:14:50.888927 | 2023-09-02T07:16:28 | 2023-09-02T07:16:28 | 156,939,672 | 9,912 | 2,451 | MIT | 2023-09-14T21:22:46 | 2018-11-10T02:22:53 | C++ | UTF-8 | C++ | false | false | 1,368 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) 2020, NXP Semiconductor, Inc. All rights reserved.
// Licensed under the MIT License
#ifdef RELU_ARMNN
#pragma once
#include "core/framework/op_kernel.h"
#include "core/providers/cpu/activation/activations.h"
#include "core/providers/armnn/armnn_execution_provider.h"
#include "armnn/ArmNN.hpp"
#include <thread>
#include <mutex>
namespace onnxruntime {
namespace armnn_ep {
typedef std::map<OpKernel*, armnn::NetworkId>::iterator ReluLayersIterator;
template <typename T>
class Relu : public OpKernel {
public:
explicit Relu(const OpKernelInfo& info) : OpKernel(info) {
provider_ = (const_cast<ArmNNExecutionProvider*>(
static_cast<const ArmNNExecutionProvider*>(info.GetExecutionProvider())));
run = Relu<T>::initRuntime();
}
~Relu() {
Relu::reluLayers.erase(this);
}
Status Compute(OpKernelContext* context) const override;
static armnn::IRuntimePtr initRuntime() {
if (Relu::run)
return std::move(Relu::run);
armnn::IRuntime::CreationOptions options;
return std::move(armnn::IRuntime::Create(options));
}
private:
static thread_local std::map<OpKernel*, armnn::NetworkId> reluLayers;
ArmNNExecutionProvider* provider_;
static armnn::IRuntimePtr run;
};
} // namespace armnn_ep
} // namespace onnxruntime
#endif
| [
"noreply@github.com"
] | noreply@github.com |
3ab0bea378b288678aa6304b6224c4427945b585 | c33241f524d5147f0296a035746b4335e0a0e0a1 | /Oboe/app/src/main/cpp/SineGenerator.h | fda8195995762dfd147fa2b42c4181fbb1a67ddc | [] | no_license | shengyi123/HtsEngine_Oboe | b3f52ec88684f7f0c50fc525fcc02c4d3225dd2c | b9c6788e102aeb24a3200f5929cc5632fd7aff70 | refs/heads/master | 2020-04-16T10:47:00.386042 | 2019-01-13T17:02:23 | 2019-01-13T17:02:23 | 165,516,726 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | //
// Created by Admin on 2019/1/11.
//
#ifndef HTS_OBOE_SINEGENERATOR_H
#define HTS_OBOE_SINEGENERATOR_H
#include <math.h>
#include <cstdint>
class SineGenerator
{
public:
SineGenerator();
~SineGenerator() = default;
void setup(double frequency, int32_t frameRate);
void setup(double frequency, int32_t frameRate, float amplitude);
void setSweep(double frequencyLow, double frequencyHigh, double seconds);
void render(int16_t *buffer, int32_t channelStride, int32_t numFrames);
void render(float *buffer, int32_t channelStride, int32_t numFrames);
private:
double mAmplitude;
double mPhase = 0.0;
int32_t mFrameRate;
double mPhaseIncrement;
double mPhaseIncrementLow;
double mPhaseIncrementHigh;
double mUpScaler = 1.0;
double mDownScaler = 1.0;
bool mGoingUp = false;
bool mSweeping = false;
void advancePhase();
double getPhaseIncremement(double frequency);
};
#endif //HTS_OBOE_SINEGENERATOR_H
| [
"rabbit26745780@"
] | rabbit26745780@ |
2b9b404bf5ef24a977d24494b5c8d06b9a7ddc7b | 73cfd20ef1c8fa0b6dd38d06dadede6160108665 | /Exercise/TestBFS.cpp | f77c0a07b2b01a45805376ce1581e97a15fa743e | [] | no_license | robgao/LeetCode | 5af028365250ed23e19d0196713216fb68941f6f | 83b27075886d9297bc7c0470a9261626b4e506cd | refs/heads/master | 2020-12-15T19:10:38.936000 | 2020-01-20T23:04:53 | 2020-01-20T23:04:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,195 | cpp | #pragma once
#include "..\LeetCode\LeetCode.h"
#include "..\LeetCode\LeetCodeBFS.h"
#include "TestBFS.h"
void TestLeetCode1197(void)
{
Logger::WriteMessage("Test Leet Code 1197");
LeetCodeBFS leetCode;
int x = 2;
int y = 1;
int result = leetCode.minKnightMoves(x, y);
Logger::WriteMessage("x = " + to_string(x) + "; y = " + to_string(y) + "; result = " + to_string(result));
x = 5;
y = 5;
result = leetCode.minKnightMoves(x, y);
Logger::WriteMessage("x = " + to_string(x) + "; y = " + to_string(y) + "; result = " + to_string(result));
x = 300;
y = 0;
result = leetCode.minKnightMoves(x, y);
Logger::WriteMessage("x = " + to_string(x) + "; y = " + to_string(y) + "; result = " + to_string(result));
}
void TestLeetCode1215(void)
{
Logger::WriteMessage("Test Leet Code 1215");
LeetCodeBFS leetCode;
int low = 0;
int high = 1000;
vector<int> result = leetCode.countSteppingNumbers(low, high);
Logger::WriteMessage("low = " + to_string(low) + "; high = " + to_string(high));
Logger::WriteMessage(result);
}
void TestLeetCode1284(void)
{
Logger::WriteMessage("Test Leet Code 1284");
LeetCodeBFS leetCode;
vector<vector<int>> mat = { {0, 0},{0, 1} };
int result = leetCode.minFlips(mat);
Logger::WriteMessage(mat);
Logger::WriteMessage("result = " + to_string(result));
mat = {{ 0 }};
result = leetCode.minFlips(mat);
Logger::WriteMessage(mat);
Logger::WriteMessage("result = " + to_string(result));
mat = { {1, 1, 1},{1, 0, 1},{0, 0, 0} };
result = leetCode.minFlips(mat);
Logger::WriteMessage(mat);
Logger::WriteMessage("result = " + to_string(result));
mat = { {1, 0, 0},{1, 0, 0} };
result = leetCode.minFlips(mat);
Logger::WriteMessage(mat);
Logger::WriteMessage("result = " + to_string(result));
mat = { {0}, {1}, {1} };
result = leetCode.minFlips(mat);
Logger::WriteMessage(mat);
Logger::WriteMessage("result = " + to_string(result));
}
void TestLeetCodeBFS(void)
{
TestLeetCode1284();
TestLeetCode1215();
TestLeetCode1197();
} | [
"noreply@github.com"
] | noreply@github.com |
b7602d0ca9c2401f4cea8c84c7c2626321411bae | f92f86ae5595fa82f46eddaf005fd4e12150237a | /ClassMgr2/Base.h | a34263a468f50750ea6841f7864c3814b610ae64 | [] | no_license | charles-pku-2013/CodeRes_Cpp | 0b3d84412303c42a64fd943e8d0259dacd17954f | a2486495062743c1ec752b26989391f7e580d724 | refs/heads/master | 2023-08-31T19:44:34.784744 | 2023-08-30T06:28:21 | 2023-08-30T06:28:21 | 44,118,898 | 3 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 311 | h | #ifndef _BASE_H_
#define _BASE_H_
#include <iostream>
#include <boost/format.hpp>
class Base {
public:
Base(int _ID) : m_nID(_ID)
{ std::cout << "Base construct" << std::endl; }
virtual ~Base() {}
int id() const { return m_nID; }
protected:
int m_nID;
};
#endif /* _BASE_H_ */
| [
"sunchao14@meituan.com"
] | sunchao14@meituan.com |
ce701900a3431870d8c614e4f7994b5e6c6042a7 | 70261d2c3111d9b44478a6b007b25e01bfaee138 | /Desktop/C.P/Sublime Text 3/programs/mew11.cpp | adf177af3df4dbf7410326b0788e3053d35123b8 | [] | no_license | AmarShukla1/Competitive-Programming | 05a16ddb1cbc5b3c6223ca589608388957a754c0 | 782f0c9f1382581185bc497614ec09a5af846085 | refs/heads/master | 2023-06-05T09:19:45.428801 | 2021-06-26T08:49:20 | 2021-06-26T08:49:20 | 296,541,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | cpp | //Tonight's the night and it is going to happen again and again.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mp make_pair
#define pb push_back
#define T ll t; cin>>t; while(t--)
#define mod 1000000007
#define f(n) for(ll i = 0;i<n;i++)
#define endl "\n"
ll gcd(ll a,ll b){if(b==0){return a;}return gcd(b,a%b);}
ll dp[60001];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ll n;cin>>n;ll inf=1000000000;//greedy soln here doesnt work
for(ll i=0;i<=n;i++){dp[i]=inf;}
for(ll i=1;i<=244;i++)
{
dp[i*i]=1;
}
for(ll i=1;i<=n;i++)
{
for(ll j=1;j*j<=n;j++)
{
if(i>j*j){
dp[i]=min(dp[i],dp[i-j*j]+1);}
else{break;}
}
}cout<<dp[n];
} | [
"spamfreemenow12345@gmail.com"
] | spamfreemenow12345@gmail.com |
7d0791618917cda865fd222af2e45113230e863b | 0ae61467dc21f997e868d31eb5a555b59c463cd4 | /21days_CPlusPlus/chapter6/6.15_test_reverse.cpp | 02ec085e2bc876e82d5d4ab2b3e3a27313465db1 | [] | no_license | eoGqzPzYlN/C-and-C-plus-plus | c9ed101c7da1e3d8525c003d900640cc12db0f02 | 30a5838f9b9641b7cb67bfa322d355cc50826bc7 | refs/heads/master | 2023-07-26T01:36:02.854345 | 2021-09-06T05:43:45 | 2021-09-06T05:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | #include <iostream>
int main(int argc, char** argv)
{
const int ARRAY_LEG_ONE = 5;
int numOne[ARRAY_LEG_ONE] = {24, 20, -1, 20, -1};
for (int index = ARRAY_LEG_ONE - 1; index >= 0; --index)
{
std::cout << "numOne[" << index << "] = " << numOne[index] << std::endl;
}
std::cout << std::endl;
return 0;
}
// $ g++ -o main 6.15_test_reverse.cpp
// $ ./main.exe
// numOne[4] = -1
// numOne[3] = 20
// numOne[2] = -1
// numOne[1] = 20
// numOne[0] = 24
| [
"2694048168@qq.com"
] | 2694048168@qq.com |
644df2f93c8fe039838c3778cef9cdb70e18a5d9 | 6500d374cef9c8b664aa5dd7df38475f2958308b | /test_src/mydisambig_opt.cpp | eab36a9387bea8f0cbc6b2a27328d6b0b7bd9228 | [] | no_license | michael0703/dsp-hw3 | fcb10faab5009ad0213f42f220faf882d77ee142 | f12171725c724523108d9fbb12931c465cd1bcaf | refs/heads/master | 2023-01-31T09:18:26.072135 | 2020-12-15T15:12:36 | 2020-12-15T15:12:36 | 320,999,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,155 | cpp | #include <stdio.h>
#include "Ngram.h"
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
using namespace std;
#define INV_PROB -1e4
// --- global vars
vector<vector<string>> input_sentences;
map<string, vector<string>> ZhuYin_Lookup;
Vocab voc;
Ngram lm(voc, 2);
int max_state = -1;
int max_input = -1;
// --- end of global vars
vector<string> split_string(string s){
istringstream s_in(s);
string seg_term;
vector<string> split_terms;
while(s_in >> seg_term) {
split_terms.push_back(seg_term);
}
return split_terms;
}
void read_seg_file(char* infile, char* outfile){
ifstream f_in(infile, ios::in);
ofstream f_out(outfile, ios::out);
string line;
while(getline(f_in, line)){
vector<string> split_terms = split_string(line);
input_sentences.push_back(split_terms);
if ((int)split_terms.size() > max_input) max_input = (int)split_terms.size();
/*
for(int i=0; i<split_terms.size(); i++){
printf("term size in char array: %d, %x %x\n", strlen(split_terms[i].c_str()), split_terms[i].c_str()[0], split_terms[i].c_str()[1]);
}*/
}
f_in.close();
f_out.close();
}
void parse_mapping(char* infile, char* outfile){
ifstream f_in(infile, ios::in);
ofstream f_out(outfile, ios::out);
string line;
while(getline(f_in, line)){
vector<string> split_terms = split_string(line);
vector<string> empty_vec;
ZhuYin_Lookup.insert(pair<string, vector<string>>(split_terms[0], empty_vec));
for(int i=1; i<split_terms.size(); i++){
ZhuYin_Lookup.at(split_terms[0]).push_back(split_terms[i]);
}
if ((int)split_terms.size() - 1 > max_state){
max_state = (int)split_terms.size() - 1;
}
}
}
// get prob of P(a | b)
float get_prob(string a, string b = ""){
VocabIndex context[] = {};
if (b == ""){
context[0] = Vocab_None;
}
else{
VocabIndex b_id = voc.getIndex(b.c_str());
context[0] = b_id != Vocab_None ? b_id : voc.getIndex(Vocab_Unknown);
}
VocabIndex a_id = voc.getIndex(a.c_str());
a_id = (a_id != Vocab_None) ? a_id : voc.getIndex(Vocab_Unknown);
//cout << "this is a_id " << a_id << endl;
return lm.wordProb(a_id, context);
}
void viterbi(char* out_file){
ofstream f_out(out_file, ios::in);
// init viterbi for every input
for(int input_idx = 0; input_idx < (int)input_sentences.size(); input_idx ++){
printf("Start Num: %d sentences\n", input_idx);
printf("%d %d\n", max_input, max_state);
// init first column
float viterbi[max_input][max_state];
int backtrack[max_input][max_state];
string observe_term = input_sentences[input_idx][0];
vector<string> state_list = ZhuYin_Lookup.at(observe_term);
int state_num = (int)state_list.size();
for(int i =0; i < max_state; i ++){
if (i >= state_num){
break;
//viterbi[0][i] = INV_PROB;
}
else{
viterbi[0][i] = get_prob(state_list[i], "");
printf("observe 0, state : %d has Prob : %f\n", i, viterbi[0][i]);
}
}
/* debug viterbi
for(int i=0; i<max_state; i++){
if (viterbi[0][i] > INV_PROB){
printf("observe 0, state : %d has Prob : %f", i, viterbi[0][i]);
}
}
induction of viterbi */
for(int chr_idx = 1; chr_idx < (int)input_sentences[input_idx].size(); chr_idx ++ ){
printf("working on num %d words\n", chr_idx);
observe_term = input_sentences[input_idx][chr_idx];
state_list = ZhuYin_Lookup.at(observe_term);
state_num = (int)state_list.size();
for(int i=0; i<max_state; i++){
// this means O_j doesnt have state i, then this is not valid path;
if (input_idx == 1 && chr_idx == 12)
cout << "working on state i : " << i << endl;
if (i >= state_num){
break;
}
else{
float maxP = -1e9;
int maxPreIndex = -1;
string pre_observ = input_sentences[input_idx][chr_idx - 1];
int PreStateLen = (int)ZhuYin_Lookup.at(pre_observ).size();
for(int j=0; j<max_state; j++){
if (PreStateLen <= j){
break;
}
else{
string pre_term = ZhuYin_Lookup.at(pre_observ)[j];
float given_prob = get_prob(state_list[i], pre_term);
if (given_prob + viterbi[chr_idx - 1][j] > maxP){
maxP = given_prob + viterbi[chr_idx-1][j];
maxPreIndex = j;
}
}
}
viterbi[chr_idx][i] = maxP;
backtrack[chr_idx][i] = maxPreIndex;
}
}
}
// backtracking viterbi path
int sentence_size = (int)input_sentences[input_idx].size();
int maxFinal = -1;
float maxFinalP = -1e4;
for(int st = 0; st < max_state; st++){
if (st >= (int)ZhuYin_Lookup.at(input_sentences[input_idx][sentence_size-1]).size()) break;
if (viterbi[sentence_size-1][st] > maxFinalP){
maxFinalP = viterbi[sentence_size-1][st];
maxFinal = st;
}
}
vector<string> best_sentences;
int back_idx = sentence_size-1;
int back_st = maxFinal;
while(back_idx >= 0){
string cur_term = ZhuYin_Lookup.at(input_sentences[input_idx][back_idx])[back_st];
best_sentences.push_back(cur_term);
if (back_idx > 0){
back_st = backtrack[back_idx][back_st];
back_idx -= 1;
}
else break;
}
for(int x = sentence_size -1; x >=0; x--){
f_out << best_sentences[x] << " ";
}
f_out << endl;
//if(input_idx >= 2) break;
//break;
}
}
int main(int argc, char** argv){
char* seg_input_file = argv[1];
char* observ_state_mapping_file = argv[2];
char* lm_file = argv[3];
char* out_file = argv[4];
read_seg_file(seg_input_file, out_file);
printf("Max Input Length - %d\n", max_input);
printf("Size of Input Text File : %lu\n", input_sentences.size());
parse_mapping(observ_state_mapping_file, out_file);
printf("Max State of ZhuYin - mapping - %d\n", max_state);
printf("Map size of ZhuYin Mapping File : %lu\n", ZhuYin_Lookup.size());
File _lm(lm_file, "r");
lm.read(_lm);
_lm.close();
viterbi(out_file);
/* example code only
VocabIndex vid = voc.getIndex(input_sentences[0][0].c_str());
printf("%d %d\n", input_sentences[0][0].c_str()[0], input_sentences[0][0].c_str()[1]);
cout << "example vid : " << vid << endl;
VocabIndex context[] = {Vocab_None};
printf("log Prob = %f\n", lm.wordProb(vid, context));
*/
return 0;
}
| [
"liaoweiskewer0703@gmail.com"
] | liaoweiskewer0703@gmail.com |
276aa3043f33e366d039746956cf5662f9c09884 | 1e54d65f6df28b604ba09ba4429eae88ea16480e | /Sender/main.cpp | ca4564b6deaf3fc03ac54d943e9124a3cb85f50a | [] | no_license | aerez/Files | 2ef51e2f4c01254fc5faae8830423909fe91bb95 | ae428370ce98084c7613611844d4f87df20cf4ab | refs/heads/master | 2020-07-07T03:56:43.848675 | 2019-08-19T14:45:10 | 2019-08-19T14:45:10 | 203,239,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,989 | cpp | #include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
#define LOOPBACK "127.0.0.1"
#define PORT "55555"
using namespace std;
void *get_in_addr(struct sockaddr *sa)
{
if(sa->sa_family ==AF_INET){
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
void gotoxy(int x,int y){//moves cursor to column x and row y
printf("%c[%d;%df",0x1B,y,x);
}
struct sockaddr_storage remoteaddr;//client address;
socklen_t addrlen;
string fname;
int SendFile(int sock){
cout<<fname<<endl;
send(sock,fname.c_str(),fname.size()+1,0);
//string path="/home/aerez/CLionProjects/FileProject/Sender/";
//path.append(fname);
FILE *fp= fopen(fname.c_str(),"rb");
if(fp==NULL)
{
printf("error opening file");
return 1;
}
while(1){
char buff[256]={0};
int nread= fread(buff,1,256,fp);
if(nread>0){
send(sock,buff,nread,0);
}
if(nread<256){
if(feof(fp)){
cout<<"end of file"<<endl;
cout<<"File transfer complete!"<<endl;
}
if(ferror(fp))
cout<<"Error reading"<<endl;
break;
}
}
}
int main() {
system("clear");
int sockfd=0;
struct addrinfo hints, *ai, *p;
int rv, yes = 1;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;//ipv4 or ipv6
hints.ai_socktype = SOCK_STREAM;// tcp socket
if ((rv = getaddrinfo(LOOPBACK,PORT, &hints, &ai)) != 0) {
fprintf(stderr, "select server: %s\n", gai_strerror(rv));
exit(1);
}
for (p = ai; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd < 0) {
continue;
}
//avoid "address already in use msg" error
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if (bind(sockfd, p->ai_addr, p->ai_addrlen) < 0) {
close(sockfd);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, " server: failed to bind\n");
exit(2);
}
freeaddrinfo(ai);
if(listen(sockfd,10)==-1){
perror("listen");
exit(3);
}
cout << "listener is READY!" << endl;
int newfd;
addrlen= sizeof(remoteaddr);
cout<<"waiting for connection"<<endl;
if((newfd=accept(sockfd,(struct sockaddr*)&remoteaddr,&addrlen))<0){
printf("accept error");
}
char remoteIP[INET6_ADDRSTRLEN];
cout<<"server: new connection from "<<
inet_ntop(remoteaddr.ss_family,get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP,INET6_ADDRSTRLEN)<<"on socket "<<sockfd<<endl;
cout<<"Enter file name to send: ";
getline(cin,fname);
SendFile(newfd);
return 0;
} | [
"alonerez4@gmail.com"
] | alonerez4@gmail.com |
c7352afe39f6a79f12249dcf8511f0c02d67c24c | 8b9f627b714a04c39aaaf417ba9c21ef329061b2 | /glib-core/os.cpp | 731d4ceae644d8a8f5eee35b1be2144e3b93fe5e | [] | no_license | lamvuvan/snap-dev-64 | 1ce5d4dffd81f065b7ed0b23bd5b1d06cd62d451 | 2965c542a078338ea4e2958f9917db150fcaff6c | refs/heads/master | 2020-06-05T07:33:35.953477 | 2019-06-21T09:44:42 | 2019-06-21T09:44:42 | 192,361,202 | 1 | 0 | null | 2019-06-21T09:44:43 | 2019-06-17T14:19:54 | C++ | UTF-8 | C++ | false | false | 25,203 | cpp | #ifdef GLib_WIN
/////////////////////////////////////////////////
// System-Processes
void TSysProc::Sleep(const uint& MSecs){
SleepEx(MSecs, false);
}
TStr TSysProc::GetExeFNm(){
DWORD MxFNmLen=1024;
LPTSTR FNmCStr=new char[MxFNmLen];
DWORD FNmLen=GetModuleFileName(NULL, FNmCStr, MxFNmLen);
TStr FNm;
if (FNmLen!=0){
FNm=FNmCStr;}
delete[] FNmCStr;
return FNm;
}
void TSysProc::SetLowPriority(){
SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
}
bool TSysProc::ExeProc(const TStr& ExeFNm, TStr& ParamStr){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb=sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
BOOL Ok=CreateProcess(
ExeFNm.CStr(), // module name
(LPSTR) ParamStr.CStr(), // patameters
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi); // Pointer to PROCESS_INFORMATION structure.
if (Ok){
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return true;
} else {
return false;
}
}
/////////////////////////////////////////////////
// Memory-Status
TStr TSysMemStat::GetLoadStr(){
static TStr MemUsageStr="Mem Load: ";
TChA ChA;
ChA+=MemUsageStr;
ChA+=TUInt64::GetStr(GetLoad());
ChA+="%";
return ChA;
}
TStr TSysMemStat::GetUsageStr(){
static TStr MemUsageStr="Mem Usage: ";
uint64 GlobalUsage=GetTotalPageFile()-GetAvailPageFile();
TChA ChA;
ChA+=MemUsageStr;
ChA+=TUInt64::GetStr(GlobalUsage/1024);
ChA+="K / ";
ChA+=TUInt64::GetStr(GetTotalPageFile()/1024);
ChA+="K";
return ChA;
}
TStr TSysMemStat::GetInfoStr(){
TChA ChA;
ChA+="Memory Load:";
ChA+=TUInt64::GetMegaStr(GetLoad()); ChA+="\r\n";
ChA+="Total Physical:";
ChA+=TUInt64::GetMegaStr(GetTotalPhys()); ChA+="\r\n";
ChA+="Available Physical:";
ChA+=TUInt64::GetMegaStr(GetAvailPhys()); ChA+="\r\n";
ChA+="Total Page File:";
ChA+=TUInt64::GetMegaStr(GetTotalPageFile()); ChA+="\r\n";
ChA+="Available Page File:";
ChA+=TUInt64::GetMegaStr(GetAvailPageFile()); ChA+="\r\n";
ChA+="Total Virtual:";
ChA+=TUInt64::GetMegaStr(GetTotalVirtual()); ChA+="\r\n";
ChA+="Available Virtual:";
ChA+=TUInt64::GetMegaStr(GetAvailVirtual()); ChA+="\r\n";
return ChA;
}
TStr TSysMemStat::GetStr(){
TChA ChA;
ChA+=TUInt64::GetStr(GetLoad()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalPhys()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailPhys()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalPageFile()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailPageFile()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalVirtual()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailVirtual());
return ChA;
}
/////////////////////////////////////////////////
// System-Console
TSysConsole::TSysConsole(){
Ok=(AllocConsole()!=0);
IAssert(Ok);
hStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
IAssert(hStdOut!=INVALID_HANDLE_VALUE);
}
TSysConsole::~TSysConsole(){
if (Ok){
IAssert(FreeConsole());}
}
void TSysConsole::Put(const TStr& Str){
DWORD ChsWritten;
WriteConsole(hStdOut, Str.CStr(), Str.Len(), &ChsWritten, NULL);
IAssert(ChsWritten==DWORD(Str.Len()));
}
/////////////////////////////////////////////////
// System-Console-Notifier
void TSysConsoleNotify::OnNotify(const TNotifyType& Type, const TStr& MsgStr){
if (Type==ntInfo){
SysConsole->PutLn(TStr::Fmt("%s", MsgStr.CStr()));
} else {
TStr TypeStr=TNotify::GetTypeStr(Type, false);
SysConsole->PutLn(TStr::Fmt("%s: %s", TypeStr.CStr(), MsgStr.CStr()));
}
}
void TSysConsoleNotify::OnStatus(const TStr& MsgStr){
SysConsole->Put(MsgStr.CStr());
// print '\n' if message not overlayed
if ((!MsgStr.Empty())&&(MsgStr.LastCh()!='\r')){
SysConsole->PutLn(""); }
}
/////////////////////////////////////////////////
// System-Messages
//void TSysMsg::Loop(){
// MSG Msg;
// while (GetMessage(&Msg, NULL, 0, 0 )){
// TranslateMessage(&Msg); DispatchMessage(&Msg);}
//}
//
//void TSysMsg::Quit(){PostQuitMessage(0);}
/////////////////////////////////////////////////
// System-Time
TTm TSysTm::GetCurUniTm(){
SYSTEMTIME SysTm;
GetSystemTime(&SysTm);
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
TTm TSysTm::GetCurLocTm(){
SYSTEMTIME SysTm;
GetLocalTime(&SysTm);
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
uint64 TSysTm::GetCurUniMSecs(){
SYSTEMTIME SysTm; FILETIME FileTm;
GetSystemTime(&SysTm);
IAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
uint64 TSysTm::GetCurLocMSecs(){
SYSTEMTIME SysTm; FILETIME FileTm;
GetLocalTime(&SysTm);
IAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
uint64 TSysTm::GetMSecsFromTm(const TTm& Tm){
SYSTEMTIME SysTm; FILETIME FileTm;
SysTm.wYear=WORD(Tm.GetYear());
SysTm.wMonth=WORD(Tm.GetMonth());
SysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
SysTm.wDay=WORD(Tm.GetDay());
SysTm.wHour=WORD(Tm.GetHour());
SysTm.wMinute=WORD(Tm.GetMin());
SysTm.wSecond=WORD(Tm.GetSec());
SysTm.wMilliseconds=WORD(Tm.GetMSec());
ESAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
TTm TSysTm::GetTmFromMSecs(const uint64& MSecs){
TUInt64 FileTmUnits(MSecs*uint64(10000));
SYSTEMTIME SysTm; FILETIME FileTm;
FileTm.dwHighDateTime=FileTmUnits.GetMsVal();
FileTm.dwLowDateTime=FileTmUnits.GetLsVal();
SAssert(FileTimeToSystemTime(&FileTm, &SysTm));
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
uint TSysTm::GetMSecsFromOsStart(){
return uint(GetTickCount());
}
TTm TSysTm::GetLocTmFromUniTm(const TTm& Tm){
// get time-zone information
TIME_ZONE_INFORMATION TzInf;
GetTimeZoneInformation(&TzInf);
// get system time
SYSTEMTIME UniSysTm;
UniSysTm.wYear=WORD(Tm.GetYear());
UniSysTm.wMonth=WORD(Tm.GetMonth());
UniSysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
UniSysTm.wDay=WORD(Tm.GetDay());
UniSysTm.wHour=WORD(Tm.GetHour());
UniSysTm.wMinute=WORD(Tm.GetMin());
UniSysTm.wSecond=WORD(Tm.GetSec());
UniSysTm.wMilliseconds=WORD(Tm.GetMSec());
// convert system-time
SYSTEMTIME LocSysTm;
SystemTimeToTzSpecificLocalTime(&TzInf, &UniSysTm, &LocSysTm);
// return local-time
return TTm(LocSysTm.wYear, LocSysTm.wMonth, LocSysTm.wDay, LocSysTm.wDayOfWeek,
LocSysTm.wHour, LocSysTm.wMinute, LocSysTm.wSecond, LocSysTm.wMilliseconds);
}
TTm TSysTm::GetUniTmFromLocTm(const TTm& Tm){
// get time-zone information
TIME_ZONE_INFORMATION TzInf;
GetTimeZoneInformation(&TzInf);
// get system time
SYSTEMTIME LocSysTm;
LocSysTm.wYear=WORD(Tm.GetYear());
LocSysTm.wMonth=WORD(Tm.GetMonth());
LocSysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
LocSysTm.wDay=WORD(Tm.GetDay());
LocSysTm.wHour=WORD(Tm.GetHour());
LocSysTm.wMinute=WORD(Tm.GetMin());
LocSysTm.wSecond=WORD(Tm.GetSec());
LocSysTm.wMilliseconds=WORD(Tm.GetMSec());
// convert system-time
SYSTEMTIME UniSysTm=LocSysTm;
Fail; // BCB5.0 doesn't find TzSpecificLocalTimeToSystemTime
//TzSpecificLocalTimeToSystemTime(&TzInf, &LocSysTm, &UniSysTm);
// return system-time
return TTm(UniSysTm.wYear, UniSysTm.wMonth, UniSysTm.wDay, UniSysTm.wDayOfWeek,
UniSysTm.wHour, UniSysTm.wMinute, UniSysTm.wSecond, UniSysTm.wMilliseconds);
}
uint64 TSysTm::GetProcessMSecs(){
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
IAssert(GetProcessTimes(GetCurrentProcess(),
&CreationTime, &ExitTime, &KernelTime, &UserTime));
TUInt64 KernelMSecs(uint(KernelTime.dwHighDateTime), uint(KernelTime.dwLowDateTime));
TUInt64 UserMSecs(uint(UserTime.dwHighDateTime), uint(UserTime.dwLowDateTime));
uint64 ProcessMSecs=KernelMSecs+UserMSecs;
return ProcessMSecs;
}
uint64 TSysTm::GetThreadMSecs(){
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
IAssert(GetProcessTimes(GetCurrentProcess(),
&CreationTime, &ExitTime, &KernelTime, &UserTime));
TUInt64 KernelMSecs(uint(KernelTime.dwHighDateTime), uint(KernelTime.dwLowDateTime));
TUInt64 UserMSecs(uint(UserTime.dwHighDateTime), uint(UserTime.dwLowDateTime));
uint64 ThreadMSecs=KernelMSecs+UserMSecs;
return ThreadMSecs;
}
uint64 TSysTm::GetPerfTimerFq(){
uint MsFq; uint LsFq;
LARGE_INTEGER LargeInt;
if (QueryPerformanceFrequency(&LargeInt)){
MsFq=LargeInt.u.HighPart;
LsFq=LargeInt.u.LowPart;
} else {
MsFq=0;
LsFq=1;
}
TUInt64 UInt64(MsFq, LsFq);
return UInt64.Val;
}
uint64 TSysTm::GetPerfTimerTicks(){
uint MsVal; uint LsVal;
LARGE_INTEGER LargeInt;
if (QueryPerformanceCounter(&LargeInt)){
MsVal=LargeInt.u.HighPart;
LsVal=LargeInt.u.LowPart;
} else {
MsVal=0;
LsVal=int(time(NULL));
}
TUInt64 UInt64(MsVal, LsVal);
return UInt64.Val;
}
/////////////////////////////////////////////////
// System-Strings
TStr TSysStr::GetCmLn(){
return TStr((char*)GetCommandLine());
}
TStr TSysStr::GetMsgStr(const DWORD& MsgCd){
// retrieve message string
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
MsgCd,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
// save string
TStr MsgStr((char*)lpMsgBuf);
// free the buffer.
LocalFree(lpMsgBuf);
return MsgStr;
}
char* TSysStr::GetLastMsgCStr(){
TStr MsgStr=GetLastMsgStr();
static char* MsgCStr=NULL;
if (MsgCStr==NULL){MsgCStr=new char[1000];}
strcpy(MsgCStr, MsgStr.CStr());
return MsgCStr;
}
/////////////////////////////////////////////////
// Registry-Key
PRegKey TRegKey::GetKey(const PRegKey& BaseKey, const TStr& SubKeyNm){
HKEY hKey;
DWORD RetCd=RegOpenKeyEx(
BaseKey->GetHandle(), SubKeyNm.CStr(), 0, KEY_ALL_ACCESS, &hKey);
bool Ok=RetCd==ERROR_SUCCESS;
return new TRegKey(Ok, hKey);
}
TStr TRegKey::GetVal(const PRegKey& Key, const TStr& SubKeyNm, const TStr& ValNm){
PRegKey RegKey=TRegKey::GetKey(Key, SubKeyNm);
if (RegKey->IsOk()){
TStrKdV ValNmStrKdV; RegKey->GetValV(ValNmStrKdV);
int ValN;
if (ValNmStrKdV.IsIn(TStrKd(ValNm), ValN)){
return ValNmStrKdV[ValN].Dat;
} else {
return "";
}
} else {
return "";
}
}
void TRegKey::GetKeyNmV(TStrV& KeyNmV) const {
KeyNmV.Clr();
if (!Ok){return;}
// get subkey count
DWORD SubKeys; // number of subkeys
DWORD MxSubKeyNmLen; // longest subkey size
DWORD RetCd=RegQueryInfoKey(
hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
&SubKeys, // number of subkeys
&MxSubKeyNmLen, // longest subkey size
NULL, // longest class string
NULL, // number of values for this key
NULL, // longest value name
NULL, // longest value data
NULL, // security descriptor
NULL); // last write time
if (RetCd!=ERROR_SUCCESS){return;}
// retrieve subkey-names
if (SubKeys>0){
KeyNmV.Gen(SubKeys, 0);
char* SubKeyNmCStr=new char[MxSubKeyNmLen+1];
DWORD SubKeyN=0;
forever{
DWORD SubKeyNmCStrLen=MxSubKeyNmLen+1;
DWORD RetCd=RegEnumKeyEx(
hKey, // handle of key to enumerate
SubKeyN, // index of subkey to enumerate
SubKeyNmCStr, // address of buffer for subkey name
&SubKeyNmCStrLen, // address for size of subkey buffer
NULL, // reserved
NULL, // address of buffer for class string
NULL, // address for size of class buffer
NULL); // address for time key last written to
if (RetCd==ERROR_SUCCESS){
TStr KeyNm(SubKeyNmCStr);
KeyNmV.Add(KeyNm);
} else {
break;
}
SubKeyN++;
}
delete[] SubKeyNmCStr;
}
}
void TRegKey::GetValV(TStrKdV& ValNmStrKdV) const {
ValNmStrKdV.Clr();
if (!Ok){return;}
// get subkey count
DWORD Vals; // number of values
DWORD MxValNmLen; // longest value name
DWORD MxValStrLen; // longest value data
DWORD RetCd=RegQueryInfoKey(
hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
NULL, // number of subkeys
NULL, // longest subkey size
NULL, // longest class string
&Vals, // number of values for this key
&MxValNmLen, // longest value name
&MxValStrLen, // longest value data
NULL, // security descriptor
NULL); // last write time
if (RetCd!=ERROR_SUCCESS){return;}
// retrieve subkey-names
if (Vals>0){
ValNmStrKdV.Gen(Vals, 0);
char* ValNmCStr=new char[MxValNmLen+1];
char* ValCStr=new char[MxValStrLen+1];
DWORD ValN=0;
forever{
DWORD ValNmCStrLen=MxValNmLen+1;
DWORD ValCStrLen=MxValStrLen+1;
DWORD ValType;
DWORD RetCd=RegEnumValue(
hKey, // handle of key to query
ValN, // index of value to query
ValNmCStr, // address of buffer for value string
&ValNmCStrLen, // address for size of value buffer
NULL, // reserved
&ValType, // address of buffer for type code
(unsigned char*) ValCStr, // address of buffer for value data
&ValCStrLen); // address for size of data buffer
if (RetCd==ERROR_SUCCESS){
if (ValType==REG_SZ){
TStr ValNm(ValNmCStr);
TStr ValStr(ValCStr);
ValNmStrKdV.Add(TStrKd(ValNm, ValStr));
}
} else {
break;
}
ValN++;
}
delete[] ValNmCStr;
delete[] ValCStr;
}
}
/////////////////////////////////////////////////
// Program StdIn and StdOut redirection using pipes
void TStdIOPipe::CreateProc(const TStr& Cmd) {
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdInput = ChildStdinRd;
siStartInfo.hStdOutput = ChildStdoutWr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
const BOOL FuncRetn = CreateProcess(NULL,
(LPSTR) Cmd.CStr(), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
EAssertR(FuncRetn!=0, TStr::Fmt("Can not execute '%s'", Cmd.CStr()).CStr());
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
TStdIOPipe::TStdIOPipe(const TStr& CmdToExe) : ChildStdinRd(NULL), ChildStdinWrDup(NULL),
ChildStdoutWr(NULL), ChildStdoutRdDup(NULL) {
HANDLE ChildStdinWr, ChildStdoutRd;
SECURITY_ATTRIBUTES saAttr;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
EAssert(CreatePipe(&ChildStdoutRd, &ChildStdoutWr, &saAttr, 0));
// Create noninheritable read handle and close the inheritable read handle.
EAssert(DuplicateHandle(GetCurrentProcess(), ChildStdoutRd,
GetCurrentProcess(), &ChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS));
CloseHandle(ChildStdoutRd);
// Create a pipe for the child process's STDIN.
EAssert(CreatePipe(&ChildStdinRd, &ChildStdinWr, &saAttr, 0));
// Duplicate the write handle to the pipe so it is not inherited.
EAssert(DuplicateHandle(GetCurrentProcess(), ChildStdinWr,
GetCurrentProcess(), &ChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS));
CloseHandle(ChildStdinWr);
// Now create the child process.
CreateProc(CmdToExe);
}
TStdIOPipe::~TStdIOPipe() {
if (ChildStdinRd != NULL) CloseHandle(ChildStdinRd);
if (ChildStdinWrDup != NULL) CloseHandle(ChildStdinWrDup);
if (ChildStdoutWr != NULL) CloseHandle(ChildStdoutWr);
if (ChildStdoutRdDup != NULL) CloseHandle(ChildStdoutRdDup);
}
int TStdIOPipe::Write(const char* Bf, const int& BfLen) {
DWORD Written;
EAssert(WriteFile(ChildStdinWrDup, Bf, BfLen, &Written, NULL));
return int(Written);
}
int TStdIOPipe::Read(char *Bf, const int& BfMxLen) {
DWORD Read;
EAssert(ReadFile(ChildStdoutRdDup, Bf, BfMxLen, &Read, NULL));
return int(Read);
}
#elif defined(GLib_UNIX)
/////////////////////////////////////////////////
// Compatibility functions
int GetModuleFileName(void *hModule, char *Bf, int MxBfL) {
int retlen = (int) readlink("/proc/self/exe", Bf, MxBfL);
if (retlen == -1) {
if (MxBfL > 0) Bf[0] = '\0';
return 0;
}
if (retlen == MxBfL) --retlen;
Bf[retlen] = '\0';
return retlen;
}
int GetCurrentDirectory(const int MxBfL, char *Bf) {
getcwd(Bf, MxBfL);
return (int) strlen(Bf);
}
int CreateDirectory(const char *FNm, void *useless) {
return mkdir(FNm, 0777)==0;
}
int RemoveDirectory(const char *FNm) {
return unlink(FNm)==0;
}
#define TICKS_PER_SECOND 10000000
#define EPOCH_DIFFERENCE 11644473600LL
/// Converts Unix epoch time to Windows FILETIME.
uint64 Epoch2Ft(time_t Epoch){
uint64 Ft;
Ft = Epoch + EPOCH_DIFFERENCE; // Adds seconds between epochs
Ft *= TICKS_PER_SECOND; // Converts from seconds to 100ns intervals
return Ft;
}
/// Converts Windows FILETIME to Unix epoch time.
time_t Ft2Epoch(uint64 Ft){
uint64 Epoch;
Epoch = Ft / TICKS_PER_SECOND; // Converts from 100ns intervals to seconds
Epoch -= EPOCH_DIFFERENCE; // Subtracts seconds between epochs
return (time_t) Epoch;
}
/////////////////////////////////////////////////
// System-Time
TTm TSysTm::GetCurUniTm(){
time_t t;
struct tm tms;
struct timeval tv;
time(&t);
int ErrCd = gettimeofday(&tv, NULL);
if (ErrCd != 0) {
Assert((ErrCd==0)&&(t!=-1));
}
gmtime_r(&t, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec/1000);
}
TTm TSysTm::GetCurLocTm(){
time_t t;
struct tm tms;
struct timeval tv;
time(&t);
int ErrCd = gettimeofday(&tv, NULL);
if (ErrCd != 0) {
Assert((ErrCd==0)&&(t!=-1));
}
localtime_r(&t, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec/1000);
}
uint64 TSysTm::GetCurUniMSecs(){
return TTm::GetMSecsFromTm(GetCurLocTm());
}
uint64 TSysTm::GetCurLocMSecs(){
return TTm::GetMSecsFromTm(GetCurUniTm());
}
uint64 TSysTm::GetMSecsFromTm(const TTm& Tm){
time_t t;
struct tm tms;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth();
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
t = timegm(&tms);
return Epoch2Ft(t)/10000 + (uint64)Tm.GetMSec();
}
TTm TSysTm::GetTmFromMSecs(const uint64& TmNum){
const int MSec = int(TmNum % 1000);
time_t Sec = Ft2Epoch(TmNum*10000);
struct tm tms;
gmtime_r(&Sec, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, MSec);
}
TTm TSysTm::GetLocTmFromUniTm(const TTm& Tm) {
struct tm tms, tmr;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth();
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
int MSec = Tm.GetMSec();
time_t Sec = timegm(&tms);
localtime_r(&Sec, &tmr);
return TTm(1900+tmr.tm_year, tmr.tm_mon, tmr.tm_mday, tmr.tm_wday,
tmr.tm_hour, tmr.tm_min, tmr.tm_sec, MSec);
}
TTm TSysTm::GetUniTmFromLocTm(const TTm& Tm) {
struct tm tms, tmr;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth();
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
tms.tm_isdst = -1; // ask the system to figure out DST
int MSec = Tm.GetMSec();
time_t Sec = mktime(&tms);
gmtime_r(&Sec, &tmr);
return TTm(1900+tmr.tm_year, tmr.tm_mon, tmr.tm_mday, tmr.tm_wday,
tmr.tm_hour, tmr.tm_min, tmr.tm_sec, MSec);
}
uint TSysTm::GetMSecsFromOsStart(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_MONOTONIC, &ts);
if (ErrCd != 0) {
Assert(ErrCd==0);
}
return (ts.tv_sec*1000) + (ts.tv_nsec/1000000);
#else
FILE *f;
uint sec, csec;
f = fopen("/proc/uptime", "r");
if (!f) return 0xffffffff; // !bn: assert
fscanf(f, "%u.%u", &sec, &csec);
fclose(f);
return (uint) (sec * 1000) + (csec * 10);
#endif
}
uint64 TSysTm::GetProcessMSecs() {
#if defined(_POSIX_CPUTIME) && (_POSIX_CPUTIME != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
if (ErrCd != 0) {
Assert(ErrCd==0);
}
return (ts.tv_sec*1000) + (ts.tv_nsec / 1000000);
#else
//#warning "CLOCK_PROCESS_CPUTIME not available; using getrusage"
struct rusage ru;
int ErrCd = getrusage(RUSAGE_SELF, &ru);
if (ErrCd != 0) {
Assert(ErrCd == 0);
}
return ((ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1000) +
((ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) * 1000);
#endif
}
uint64 TSysTm::GetThreadMSecs() {
#if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
if (ErrCd != 0) {
Assert(ErrCd==0);
}
return (ts.tv_sec*1000) + (ts.tv_nsec / 1000000);
#else
//#warning "CLOCK_THREAD_CPUTIME not available; using GetProcessMSecs()"
return GetProcessMSecs();
#endif
}
uint64 TSysTm::GetPerfTimerFq(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
return 1000000000;
#else
return 1000000;
#endif
}
uint64 TSysTm::GetPerfTimerTicks(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_MONOTONIC, &ts);
//Assert(ErrCd==0); //J: vcasih se prevede in ne dela
if (ErrCd != 0) {
return (uint64)ts.tv_sec*1000000000ll + (uint64)ts.tv_nsec; }
else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64)tv.tv_usec + ((uint64)tv.tv_sec)*1000000;
}
#else
//#warning "CLOCK_MONOTONIC not available; using gettimeofday()"
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64)tv.tv_usec + ((uint64)tv.tv_sec)*1000000;
#endif
}
/////////////////////////////////////////////////
// System-Processes
int TSysProc::Sleep(const uint& MSecs) {
int ret;
struct timespec tsp, trem;
tsp.tv_sec = MSecs / 1000;
tsp.tv_nsec = (MSecs % 1000) * 1000000;
while (true) {
ret = nanosleep(&tsp, &trem);
if ((ret != -1) || (errno != EINTR)) {
break;
}
tsp = trem;
}
return ret;
}
TStr TSysProc::GetExeFNm() {
char Bf[1024];
GetModuleFileName(NULL, Bf, 1023);
return TStr(Bf);
}
void TSysProc::SetLowPriority() {
nice(19);
}
bool TSysProc::ExeProc(const TStr& ExeFNm, TStr& ParamStr) {
TStrV SArgV;
ParamStr.SplitOnWs(SArgV);
int pid = fork();
if (pid == -1) return false;
if (pid > 0) return true;
char **argv;
argv = new char*[SArgV.Len()+2];
argv[0] = strdup(ExeFNm.CStr());
for (int i=0;i<SArgV.Len();i++) argv[i+1] = strdup(SArgV[i].CStr());
argv[SArgV.Len()+1] = NULL;
execvp(argv[0], argv);
//BF: moved role of TSysMsg to TLoop and TSockSys in net.h, hence removed the following inline
//TSysMsg::Quit();
kill(getpid(), SIGINT);
return false;
}
/////////////////////////////////////////////////
// System-Messages
//void TSysMsg::Loop() {
// //bn!!! zdej mamo pa problem. kaksne msgje? samo za sockete?
// //!!! tle je treba klicat AsyncSys iz net::sock.cpp
// //#define TOTALNAZMEDA
// //#ifdef TOTALNAZMEDA
// //class TAsyncSys;
// //extern TAsyncSys AsyncSys;
// //AsyncSys::AsyncLoop();
// //#endif
// FailR("Not intended for use under Linux!");
//}
//
//void TSysMsg::Quit() {
// kill(getpid(), SIGINT);
//}
/////////////////////////////////////////////////
// Program StdIn and StdOut redirection using pipes
// J: not yet ported to Linux
TStdIOPipe::TStdIOPipe(const TStr& CmdToExe) {
FailR("Not intended for use under Linux!");
}
TStdIOPipe::~TStdIOPipe() {
FailR("Not intended for use under Linux!");
}
int TStdIOPipe::Write(const char* Bf, const int& BfLen) {
FailR("Not intended for use under Linux!");
return -1;
}
int TStdIOPipe::Read(char *Bf, const int& BfMxLen) {
FailR("Not intended for use under Linux!");
return -1;
}
#endif
| [
"rok@cs.stanford.edu"
] | rok@cs.stanford.edu |
e023d71ea1db297edecd2991e76d0d3c01d48031 | 7306e3c05b80bdb223b46409db569cfd6e4cd3ac | /Exercises/Week1/E3_1.cpp | 2c2710a72610869d196a8d361cfe8e7d232d33f2 | [] | no_license | christianfleischer/FYS3150 | 6fbfc7884915a4bef2be5eb2e07cec5205c75adf | bfabbc952b7b1064a8be241592386f66105dc55c | refs/heads/master | 2021-01-20T07:45:55.424825 | 2015-09-11T17:51:43 | 2015-09-11T17:51:43 | 41,087,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95 | cpp | // Exercise 3.1
using namespace std;
#include <stdlib.h>
#include <math.h>
#include <iostream>
| [
"chrf@fys.uio.no"
] | chrf@fys.uio.no |
c0c91b13890f5de5f8bba4b4ed2fb4e92ffdf0b2 | ed857ee410b2f987b31ab1ab515414ad0db8d4ab | /server.cpp | 087c588a74b90ddba7039ca8bf933906283212fa | [] | no_license | Silmue/zmq | 374cceda22df84dca91f7f132e308b4e01f90303 | eb1ea73456fb84a8355b6487d1491f82be4c897b | refs/heads/master | 2020-04-30T22:39:30.522151 | 2019-03-22T07:40:26 | 2019-03-22T07:40:26 | 177,124,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | cpp | #include "zhelpers.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#define NDEBUG
#define backend_host "tcp://localhost:5679"
char* process(char* Dpic);
int main() {
void *context = zmq_ctx_new();
void *worker = zmq_socket(context, ZMQ_REQ);
char *identity = "WORKER1";
zmq_setsockopt (worker, ZMQ_IDENTITY, identity, strlen(identity));
zmq_connect(worker, backend_host);
s_send(worker, "READY");
printf("ready\n");
while(1){
char *identity = s_recv(worker);
char *empty = s_recv(worker);
assert(*empty == 0);
free(empty);
//char *Dpic = s_recv(worker);
char *Dpic;
int size = zmq_recv (worker, Dpic, 10000000, 0);
Dpic[size] = '\0';
char *Recog_Result = process(Dpic);
s_sendmore(worker, identity);
s_sendmore(worker, "");
//s_send(worker, Recog_Result);
zmq_send(worker, Recog_Result, size, 0);
free(Dpic);
free(identity);
free(Recog_Result);
printf("ready\n");
}
zmq_close(worker);
zmq_ctx_destroy(context);
}
char* process(char* Dpic){
return Dpic;
} | [
"byron@LAPTOP-2Q844RKF.localdomain"
] | byron@LAPTOP-2Q844RKF.localdomain |
d00273f8ad15a2335b848dec5d334539338fd7df | 2bfddaf9c0ceb7bf46931f80ce84a829672b0343 | /src/xtd.forms/src/xtd/forms/button_base.cpp | 41e809069f2fb0ffa2bffb633520e17e17a6833a | [
"MIT"
] | permissive | gammasoft71/xtd | c6790170d770e3f581b0f1b628c4a09fea913730 | ecd52f0519996b96025b196060280b602b41acac | refs/heads/master | 2023-08-19T09:48:09.581246 | 2023-08-16T20:52:11 | 2023-08-16T20:52:11 | 170,525,609 | 609 | 53 | MIT | 2023-05-06T03:49:33 | 2019-02-13T14:54:22 | C++ | UTF-8 | C++ | false | false | 12,363 | cpp | #include "../../../include/xtd/forms/application.h"
#include "../../../include/xtd/forms/button_base.h"
#include <xtd/argument_exception.h>
#define __XTD_FORMS_NATIVE_LIBRARY__
#include <xtd/forms/native/button_styles.h>
#undef __XTD_FORMS_NATIVE_LIBRARY__
using namespace xtd;
using namespace xtd::forms;
struct button_base::data {
bool auto_ellipsis = false;
xtd::forms::flat_button_appearance flat_appearance;
xtd::forms::flat_style flat_style = xtd::forms::flat_style::standard;
xtd::drawing::image image = xtd::drawing::image::empty;
xtd::forms::image_list image_list = xtd::forms::image_list::empty;
int32 image_index = -1;
content_alignment image_align = content_alignment::middle_center;
bool is_default = false;
content_alignment text_align = content_alignment::middle_center;
};
button_base::button_base() noexcept : data_(std::make_shared<data>()) {
if (application::use_system_controls()) data_->flat_style = xtd::forms::flat_style::system;
set_auto_size_mode(forms::auto_size_mode::grow_only);
set_style(control_styles::user_mouse | control_styles::user_paint, control_appearance() == forms::control_appearance::standard);
}
bool button_base::auto_ellipsis() const noexcept {
return data_->auto_ellipsis;
}
button_base& button_base::auto_ellipsis(bool auto_ellipsis) {
data_->auto_ellipsis = auto_ellipsis;
return *this;
}
bool button_base::auto_size() const noexcept {
return control::auto_size();
}
control& button_base::auto_size(bool auto_size) {
control::auto_size(auto_size);
if (get_state(state::auto_size))
data_->auto_ellipsis = false;
return *this;
}
control& button_base::control_appearance(forms::control_appearance value) {
control::control_appearance(value);
if (value == forms::control_appearance::system && data_->flat_style != xtd::forms::flat_style::system)
flat_style(xtd::forms::flat_style::system);
else if (value == forms::control_appearance::standard && data_->flat_style == xtd::forms::flat_style::system)
flat_style(xtd::forms::flat_style::standard);
return *this;
}
const xtd::forms::flat_button_appearance& button_base::flat_appearance() const noexcept {
return data_->flat_appearance;
}
button_base& button_base::flat_appearance(const xtd::forms::flat_button_appearance& value) {
if (data_->flat_appearance != value) {
data_->flat_appearance = value;
recreate_handle();
}
return *this;
}
xtd::forms::flat_style button_base::flat_style() const noexcept {
return data_->flat_style;
}
button_base& button_base::flat_style(xtd::forms::flat_style value) {
if (data_->flat_style != value) {
data_->flat_style = value;
control_appearance(data_->flat_style == xtd::forms::flat_style::system ? forms::control_appearance::system : forms::control_appearance::standard);
recreate_handle();
}
return *this;
}
const drawing::image& button_base::image() const noexcept {
return data_->image;
}
button_base& button_base::image(const drawing::image& value) {
if (data_->image != value) {
data_->image = value;
data_->image_list = forms::image_list();
data_->image_index = -1;
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
on_image_changed(xtd::event_args::empty);
}
return *this;
}
content_alignment button_base::image_align() const noexcept {
return data_->image_align;
}
button_base& button_base::image_align(content_alignment value) {
if (data_->image_align != value) {
data_->image_align = value;
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
}
return *this;
}
int32 button_base::image_index() const noexcept {
return data_->image_index;
}
button_base& button_base::image_index(int32 value) {
if (data_->image_index != value) {
if (value < -1 || static_cast<size_t>(value) >= data_->image_list.images().size()) throw argument_out_of_range_exception(csf_);
data_->image_index = value;
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
if (value != -1) data_->image = xtd::drawing::image::empty;
}
return *this;
}
const forms::image_list& button_base::image_list() const noexcept {
return data_->image_list;
}
forms::image_list& button_base::image_list() noexcept {
return data_->image_list;
}
button_base& button_base::image_list(const forms::image_list& value) {
if (data_->image_list != value) {
data_->image_list = value;
data_->image = drawing::image::empty;
post_recreate_handle();
}
return *this;
}
bool button_base::is_default() const noexcept {
return data_->is_default;
}
button_base& button_base::is_default(bool value) {
data_->is_default = value;
return *this;
}
content_alignment button_base::text_align() const noexcept {
return data_->text_align;
}
button_base& button_base::text_align(content_alignment text_align) {
if (data_->text_align != text_align) {
data_->text_align = text_align;
if (data_->flat_style == xtd::forms::flat_style::system) post_recreate_handle();
else invalidate();
}
return *this;
}
forms::create_params button_base::create_params() const noexcept {
forms::create_params create_params = control::create_params();
if (data_->flat_style != xtd::forms::flat_style::system) create_params.style(create_params.style() | BS_OWNERDRAW);
switch (data_->text_align) {
case content_alignment::top_left: create_params.style(create_params.style() | BS_TOP | BS_LEFT); break;
case content_alignment::top_center: create_params.style(create_params.style() | BS_TOP | BS_CENTER); break;
case content_alignment::top_right: create_params.style(create_params.style() | BS_TOP | BS_RIGHT); break;
case content_alignment::middle_left: create_params.style(create_params.style() | BS_VCENTER | BS_LEFT); break;
case content_alignment::middle_center: create_params.style(create_params.style() | BS_VCENTER | BS_CENTER); break;
case content_alignment::middle_right: create_params.style(create_params.style() | BS_VCENTER | BS_RIGHT); break;
case content_alignment::bottom_left: create_params.style(create_params.style() | BS_BOTTOM | BS_LEFT); break;
case content_alignment::bottom_center: create_params.style(create_params.style() | BS_BOTTOM | BS_CENTER); break;
case content_alignment::bottom_right: create_params.style(create_params.style() | BS_BOTTOM | BS_RIGHT); break;
default: break;
}
return create_params;
}
drawing::size button_base::measure_control() const noexcept {
return control::measure_text() + drawing::size(13, 0);
}
void button_base::on_back_color_changed(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_back_color_changed(e);
}
void button_base::on_enabled_changed(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_enabled_changed(e);
}
void button_base::on_font_changed(const xtd::event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_font_changed(e);
}
void button_base::on_fore_color_changed(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_fore_color_changed(e);
}
void button_base::on_image_changed(const xtd::event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
if (can_raise_events()) image_changed(*this, e);
}
void button_base::on_mouse_down(const mouse_event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_mouse_down(e);
}
void button_base::on_mouse_enter(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_mouse_enter(e);
}
void button_base::on_mouse_leave(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_mouse_leave(e);
}
void button_base::on_mouse_up(const mouse_event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_mouse_up(e);
}
void button_base::on_parent_back_color_changed(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_parent_back_color_changed(e);
}
void button_base::on_parent_fore_color_changed(const event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_parent_fore_color_changed(e);
}
void button_base::on_resize(const xtd::event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_resize(e);
}
void button_base::on_text_changed(const xtd::event_args& e) {
if (data_->flat_style != xtd::forms::flat_style::system) invalidate();
control::on_text_changed(e);
}
xtd::drawing::rectangle button_base::compute_image_bounds() {return compute_image_bounds({0, 0, width(), height()});}
xtd::drawing::rectangle button_base::compute_image_bounds(const xtd::drawing::rectangle& rectangle) {
xtd::drawing::rectangle image_bounds = {(width() - data_->image.width()) / 2, (height() - data_->image.height()) / 2, data_->image.width(), data_->image.height()};
auto image_margin = 4;
switch (data_->image_align) {
case content_alignment::top_left: image_bounds = {rectangle.x() + image_margin, rectangle.y() + image_margin, data_->image.width(), data_->image.height()}; break;
case content_alignment::top_center: image_bounds = {(rectangle.width() - data_->image.width()) / 2, rectangle.y() + image_margin, data_->image.width(), data_->image.height()}; break;
case content_alignment::top_right: image_bounds = {rectangle.width() - data_->image.width() - image_margin, rectangle.y() + image_margin, data_->image.width(), data_->image.height()}; break;
case content_alignment::middle_left: image_bounds = {rectangle.x() + image_margin, (rectangle.height() - data_->image.height()) / 2, data_->image.width(), data_->image.height()}; break;
case content_alignment::middle_center: image_bounds = {(rectangle.width() - data_->image.width()) / 2, (rectangle.height() - data_->image.height()) / 2, data_->image.width(), data_->image.height()}; break;
case content_alignment::middle_right: image_bounds = {rectangle.width() - data_->image.width() - image_margin, (rectangle.height() - data_->image.height()) / 2, data_->image.width(), data_->image.height()}; break;
case content_alignment::bottom_left: image_bounds = {rectangle.x() + image_margin, rectangle.height() - data_->image.height() - image_margin, data_->image.width(), data_->image.height()}; break;
case content_alignment::bottom_center: image_bounds = {(rectangle.width() - data_->image.width()) / 2, rectangle.height() - data_->image.height() - image_margin, data_->image.width(), data_->image.height()}; break;
case content_alignment::bottom_right: image_bounds = {rectangle.width() - data_->image.width() - image_margin, rectangle.height() - data_->image.height() - image_margin, data_->image.width(), data_->image.height()}; break;
default: break;
}
return image_bounds;
}
text_format_flags button_base::to_text_format_flags(content_alignment text_align) {
text_format_flags flags = text_format_flags::default_format;
switch (text_align) {
case content_alignment::top_left: flags |= text_format_flags::top | text_format_flags::left; break;
case content_alignment::top_center: flags |= text_format_flags::top | text_format_flags::horizontal_center; break;
case content_alignment::top_right: flags |= text_format_flags::top | text_format_flags::right; break;
case content_alignment::middle_left: flags |= text_format_flags::vertical_center | text_format_flags::left; break;
case content_alignment::middle_center: flags |= text_format_flags::vertical_center | text_format_flags::horizontal_center; break;
case content_alignment::middle_right: flags |= text_format_flags::vertical_center | text_format_flags::right; break;
case content_alignment::bottom_left: flags |= text_format_flags::bottom | text_format_flags::left; break;
case content_alignment::bottom_center: flags |= text_format_flags::bottom | text_format_flags::horizontal_center; break;
case content_alignment::bottom_right: flags |= text_format_flags::bottom | text_format_flags::right; break;
default: break;
}
return flags;
}
| [
"gammasoft71@gmail.com"
] | gammasoft71@gmail.com |
ee6648f72b75f3e3337606604c558de9d66ca6d8 | 7b65ac82d8064179481da4a3710509314e1fc109 | /Board.h | a4d86c3d1b931c467f90b8d0d365aaed62e50322 | [] | no_license | Arpher6/Tic-tac-toe | b0c494a6efe8687f6f3f9231fb301ba38f05a4a6 | d2f46d9f99099a6e9758a8951dabda39ffa57ef6 | refs/heads/main | 2023-07-30T19:36:33.122793 | 2021-09-14T06:46:32 | 2021-09-14T06:46:32 | 403,311,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | h | class board {
private:
char aBoard[3][3];
public:
board();
bool isFull();
bool isEmpty(int x, int y);
char getValueatIndex(int x, int y);
void setValueatIndex(int x, int y, char value);
char checkSimiliarValueVertically();
char checkSimiliarvalueHorizontally();
}; | [
"noreply@github.com"
] | noreply@github.com |
1c1067151bd1587ab168be6c91184d5908d0114f | dd1393cef959982b09bbdbc08180f963f7ecaec6 | /PrimeEngine/PrimeEngine-Core/Graphics/Lights/PointLight.h | d036d582dedb16f620e9a8f006b6e9d81ff05e31 | [] | no_license | TomasMonkevic/PrimeEngine | 5926d34c04daf32df90aae789cada8fcc3f4df0f | bd143c14151b84f2e2e39f21b93f24189b83909e | refs/heads/master | 2022-09-25T07:38:36.647152 | 2020-02-24T10:20:00 | 2020-02-24T10:20:00 | 198,994,960 | 3 | 0 | null | 2020-02-21T20:51:05 | 2019-07-26T10:08:10 | C | UTF-8 | C++ | false | false | 320 | h | #pragma once
#include "Light.h"
namespace PrimeEngine { namespace Graphics { namespace Lights {
class PRIMEENGINEAPI PointLight : public Light
{
private:
float _range;
public:
PointLight(const Color& color, float intensity, float range);
void Enable(Shader& shader, unsigned i) const override;
};
} } }
| [
"tomas.monkevic97@gmail.com"
] | tomas.monkevic97@gmail.com |
32ed716ebb236c43e157dcfd4299dde903bdfda7 | e05281b9b5fc7ba86709c21745eefad17a3228c6 | /HDU3549.cpp | 960b8f3d362b982cee2c07b71a16a3297a962a2d | [] | no_license | ningning772669569/algorithm | a87871d6982312556d5c657320b644d7d9242dd7 | 346dce6c9cdd2481c12d8a7b26e23672a7cb7e76 | refs/heads/master | 2021-01-19T00:34:04.909656 | 2017-04-13T13:22:33 | 2017-04-13T13:22:33 | 87,186,141 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,012 | cpp | #include "cstdio"
#include "cstring"
#include "iostream"
#include "algorithm"
#include "queue"
#include "vector"
#define maxn 100
#define INF 0x3f3f3f3f
using namespace std;
int N,M;
struct edge{
int from,to,cap,flow;
edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct edmondkarp{
int n,m;
vector<edge> edges;
vector<int> G[maxn];
int a[maxn];
int p[maxn];
void init(int n){
for(int i=0;i<=n;i++)
G[i].clear();
edges.clear();
}
void addedge(int from,int to,int cap)
{
edges.push_back(edge(from,to,cap,0));
edges.push_back(edge(to,from,0,0));
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
int maxflow(int s,int t)
{
int flow=0;
while(1){
memset(a,0,sizeof(a));
queue<int> Q;
Q.push(s);
a[s]=INF;
while(!Q.empty()){
int x=Q.front(); Q.pop();
for(int i=0;i<G[x].size();i++){
edge &e=edges[G[x][i]];
if(!a[e.to] && e.cap>e.flow){
p[e.to]=G[x][i];
a[e.to]=min(a[x],e.cap-e.flow);
Q.push(e.to);
}
}
if(a[t]) break;
}
if(!a[t]) break;
for(int u=t;u!=s;u=edges[p[u]].from){
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
}
flow+=a[t];
}
return flow;
}
};
int g[30][30];
int main ()
{
int T;
edmondkarp e;
scanf("%d",&T);
for(int t=1;t<=T;t++){
memset(g,0,sizeof(g));
scanf("%d%d",&N,&M);
e.init(N);
for(int i=1;i<=M;i++){
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
e.addedge(u,v,c);
}
int re=e.maxflow(1,N);
printf("Case %d: %d\n",t,re);
}
return 0;
}
| [
"ningning@localhost.localdomain"
] | ningning@localhost.localdomain |
204b3e1442534fb9a69e20f1c0fca2ca4050ed7c | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-lookoutmetrics/include/aws/lookoutmetrics/model/CsvFormatDescriptor.h | aa43dfe11108c8ae9a5d1757d91d672b431349d8 | [
"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 | 9,754 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lookoutmetrics/LookoutMetrics_EXPORTS.h>
#include <aws/lookoutmetrics/model/CSVFileCompression.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace LookoutMetrics
{
namespace Model
{
/**
* <p>Contains information about how a source CSV data file should be
* analyzed.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/lookoutmetrics-2017-07-25/CsvFormatDescriptor">AWS
* API Reference</a></p>
*/
class AWS_LOOKOUTMETRICS_API CsvFormatDescriptor
{
public:
CsvFormatDescriptor();
CsvFormatDescriptor(Aws::Utils::Json::JsonView jsonValue);
CsvFormatDescriptor& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline const CSVFileCompression& GetFileCompression() const{ return m_fileCompression; }
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline bool FileCompressionHasBeenSet() const { return m_fileCompressionHasBeenSet; }
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline void SetFileCompression(const CSVFileCompression& value) { m_fileCompressionHasBeenSet = true; m_fileCompression = value; }
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline void SetFileCompression(CSVFileCompression&& value) { m_fileCompressionHasBeenSet = true; m_fileCompression = std::move(value); }
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline CsvFormatDescriptor& WithFileCompression(const CSVFileCompression& value) { SetFileCompression(value); return *this;}
/**
* <p>The level of compression of the source CSV file.</p>
*/
inline CsvFormatDescriptor& WithFileCompression(CSVFileCompression&& value) { SetFileCompression(std::move(value)); return *this;}
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline const Aws::String& GetCharset() const{ return m_charset; }
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline bool CharsetHasBeenSet() const { return m_charsetHasBeenSet; }
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline void SetCharset(const Aws::String& value) { m_charsetHasBeenSet = true; m_charset = value; }
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline void SetCharset(Aws::String&& value) { m_charsetHasBeenSet = true; m_charset = std::move(value); }
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline void SetCharset(const char* value) { m_charsetHasBeenSet = true; m_charset.assign(value); }
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline CsvFormatDescriptor& WithCharset(const Aws::String& value) { SetCharset(value); return *this;}
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline CsvFormatDescriptor& WithCharset(Aws::String&& value) { SetCharset(std::move(value)); return *this;}
/**
* <p>The character set in which the source CSV file is written.</p>
*/
inline CsvFormatDescriptor& WithCharset(const char* value) { SetCharset(value); return *this;}
/**
* <p>Whether or not the source CSV file contains a header.</p>
*/
inline bool GetContainsHeader() const{ return m_containsHeader; }
/**
* <p>Whether or not the source CSV file contains a header.</p>
*/
inline bool ContainsHeaderHasBeenSet() const { return m_containsHeaderHasBeenSet; }
/**
* <p>Whether or not the source CSV file contains a header.</p>
*/
inline void SetContainsHeader(bool value) { m_containsHeaderHasBeenSet = true; m_containsHeader = value; }
/**
* <p>Whether or not the source CSV file contains a header.</p>
*/
inline CsvFormatDescriptor& WithContainsHeader(bool value) { SetContainsHeader(value); return *this;}
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline const Aws::String& GetDelimiter() const{ return m_delimiter; }
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline bool DelimiterHasBeenSet() const { return m_delimiterHasBeenSet; }
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline void SetDelimiter(const Aws::String& value) { m_delimiterHasBeenSet = true; m_delimiter = value; }
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline void SetDelimiter(Aws::String&& value) { m_delimiterHasBeenSet = true; m_delimiter = std::move(value); }
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline void SetDelimiter(const char* value) { m_delimiterHasBeenSet = true; m_delimiter.assign(value); }
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline CsvFormatDescriptor& WithDelimiter(const Aws::String& value) { SetDelimiter(value); return *this;}
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline CsvFormatDescriptor& WithDelimiter(Aws::String&& value) { SetDelimiter(std::move(value)); return *this;}
/**
* <p>The character used to delimit the source CSV file.</p>
*/
inline CsvFormatDescriptor& WithDelimiter(const char* value) { SetDelimiter(value); return *this;}
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline const Aws::Vector<Aws::String>& GetHeaderList() const{ return m_headerList; }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline bool HeaderListHasBeenSet() const { return m_headerListHasBeenSet; }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline void SetHeaderList(const Aws::Vector<Aws::String>& value) { m_headerListHasBeenSet = true; m_headerList = value; }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline void SetHeaderList(Aws::Vector<Aws::String>&& value) { m_headerListHasBeenSet = true; m_headerList = std::move(value); }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline CsvFormatDescriptor& WithHeaderList(const Aws::Vector<Aws::String>& value) { SetHeaderList(value); return *this;}
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline CsvFormatDescriptor& WithHeaderList(Aws::Vector<Aws::String>&& value) { SetHeaderList(std::move(value)); return *this;}
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline CsvFormatDescriptor& AddHeaderList(const Aws::String& value) { m_headerListHasBeenSet = true; m_headerList.push_back(value); return *this; }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline CsvFormatDescriptor& AddHeaderList(Aws::String&& value) { m_headerListHasBeenSet = true; m_headerList.push_back(std::move(value)); return *this; }
/**
* <p>A list of the source CSV file's headers, if any.</p>
*/
inline CsvFormatDescriptor& AddHeaderList(const char* value) { m_headerListHasBeenSet = true; m_headerList.push_back(value); return *this; }
/**
* <p>The character used as a quote character.</p>
*/
inline const Aws::String& GetQuoteSymbol() const{ return m_quoteSymbol; }
/**
* <p>The character used as a quote character.</p>
*/
inline bool QuoteSymbolHasBeenSet() const { return m_quoteSymbolHasBeenSet; }
/**
* <p>The character used as a quote character.</p>
*/
inline void SetQuoteSymbol(const Aws::String& value) { m_quoteSymbolHasBeenSet = true; m_quoteSymbol = value; }
/**
* <p>The character used as a quote character.</p>
*/
inline void SetQuoteSymbol(Aws::String&& value) { m_quoteSymbolHasBeenSet = true; m_quoteSymbol = std::move(value); }
/**
* <p>The character used as a quote character.</p>
*/
inline void SetQuoteSymbol(const char* value) { m_quoteSymbolHasBeenSet = true; m_quoteSymbol.assign(value); }
/**
* <p>The character used as a quote character.</p>
*/
inline CsvFormatDescriptor& WithQuoteSymbol(const Aws::String& value) { SetQuoteSymbol(value); return *this;}
/**
* <p>The character used as a quote character.</p>
*/
inline CsvFormatDescriptor& WithQuoteSymbol(Aws::String&& value) { SetQuoteSymbol(std::move(value)); return *this;}
/**
* <p>The character used as a quote character.</p>
*/
inline CsvFormatDescriptor& WithQuoteSymbol(const char* value) { SetQuoteSymbol(value); return *this;}
private:
CSVFileCompression m_fileCompression;
bool m_fileCompressionHasBeenSet;
Aws::String m_charset;
bool m_charsetHasBeenSet;
bool m_containsHeader;
bool m_containsHeaderHasBeenSet;
Aws::String m_delimiter;
bool m_delimiterHasBeenSet;
Aws::Vector<Aws::String> m_headerList;
bool m_headerListHasBeenSet;
Aws::String m_quoteSymbol;
bool m_quoteSymbolHasBeenSet;
};
} // namespace Model
} // namespace LookoutMetrics
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
3445c88ea16be34893decbf29e5e81f1234f5cc6 | b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1 | /C++ code/Uva Online Judge/Q1489(4).cpp | d0500f65a24c9ab0d8204d9067a6bf80d9aea28f | [] | no_license | fsps60312/old-C-code | 5d0ffa0796dde5ab04c839e1dc786267b67de902 | b4be562c873afe9eacb45ab14f61c15b7115fc07 | refs/heads/master | 2022-11-30T10:55:25.587197 | 2017-06-03T16:23:03 | 2017-06-03T16:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cpp | #include<cstdio>
#define LL long long
const LL MOD=1000000003LL;
int N,K,V[51];
void getmax(int &a,int b){if(b>a)a=b;}
LL DP[51][51];
int main()
{
// freopen("in.txt","r",stdin);
while(scanf("%d%d",&N,&K)==2&&(N||K))
{
for(int i=1;i<=N;i++)scanf("%d",V+i);
LL ans=0LL;
bool reach0=false;
for(int digit=30,d=1<<30;digit>=0;digit--,d>>=1)
{
for(int i=0;i<=N;i++)for(int j=0;j<=N;j++)DP[i][j]=0LL;
DP[0][0]=1LL;
int cnt=0;
for(int i=1;i<=N;i++)
{
if(d&V[i])
{
cnt++;
for(int j=0;j<=cnt;j++)//use 1
{
DP[i][j]+=DP[i-1][j]*(V[i]-d+1);
DP[i][j]%=MOD;
}
DP[i][1]+=DP[i-1][0];
DP[i][1]%=MOD;
for(int j=2;j<=cnt;j++)//use 0
{
DP[i][j]+=DP[i-1][j-1]*d;
DP[i][j]%=MOD;
}
V[i]-=d;
}
else
{
for(int j=1;j<=cnt;j++)
{
DP[i][j]=DP[i-1][j-1]*(V[i]+1);
DP[i][j]%=MOD;
}
}
}
bool differ=(cnt&1)^((K&d)>>digit);
for(int i=differ?1:2;i<=cnt;i+=2)
{
ans+=DP[N][i];
ans%=MOD;
}
if(differ)break;
if(digit==0)reach0=true;
}
if(reach0)ans++;//no need to adjust
printf("%lld\n",ans);
}
return 0;
}
| [
"fsps60312@yahoo.com.tw"
] | fsps60312@yahoo.com.tw |
7b03889b3b067af9007a2817b95ef116a14c9419 | fbe228242f28ebf25c6335ed61730a099fe10f8e | /gameobject.h | 306fdbef362ede78ad5cf723a5ec9f6d31a3429d | [] | no_license | BeNeNuTs/tp7 | 3fd082d5907ec6abef238e86d1cc42059efaf858 | a9e1fbcb4e8c72112aa1a1e6db086a57ca38217b | refs/heads/master | 2021-01-21T23:54:10.787612 | 2015-11-20T14:45:26 | 2015-11-20T14:45:26 | 46,128,350 | 0 | 0 | null | 2015-11-13T15:01:30 | 2015-11-13T15:01:30 | null | UTF-8 | C++ | false | false | 997 | h | #ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <QVector3D>
#include <QString>
#include <QFile>
enum Format { PLY, STL, OBJ };
class GameObject
{
public:
GameObject();
GameObject(QVector3D pos, QVector3D rot, QVector3D _scale);
GameObject(QVector3D pos, QVector3D rot, QVector3D _scale, QString _localPath);
GameObject(QVector3D pos, QVector3D rot, QVector3D _scale, QString _localPath, int L);
void setLOD(int l, QString name);
void open(QString localPath);
void display();
private:
void openPLY(QString localPath);
void openSTL(QString localPath);
void openOBJ(QString localPath);
void displayPLY();
void displaySTL();
void displayOBJ();
public:
QVector3D position;
QVector3D scale;
QVector3D rotation;
QString localPath;
Format format;
QVector3D* vertex;
int nb_vertex;
QVector3D* normals;
QVector3D* index;
int nb_ind;
int LOD;
signals:
public slots:
};
#endif // GAMEOBJECT_H
| [
"david13.tcm@hotmail.fr"
] | david13.tcm@hotmail.fr |
ee5bd503a1ebd5d2cc339c8adec9e8cef71e61e3 | c7c4ef3ac21751270437c9c354d1e1fb7abbe183 | /Episodio.h | c849aed54ce52aecc7f9beed4f3411812127de1e | [] | no_license | angelicaalemanc/ProyectoIntegradorTC1030_E3 | 07dc2dd6387e97c07068a5baec34d2c6eeb9d54e | a801aaca7ac436b172402a2ad8d275608f5a4087 | refs/heads/main | 2023-05-28T17:24:07.004804 | 2021-06-12T01:33:35 | 2021-06-12T01:33:35 | 375,139,258 | 0 | 0 | null | 2021-06-12T01:02:57 | 2021-06-08T20:39:12 | C++ | UTF-8 | C++ | false | false | 390 | h | #ifndef EPISODIO_H
#define EPISODIO_H
#include <iostream>
#include <string>
using namespace std;
class Episodio{
private:
// Atributos de la clase Video
string tituloEpisodio;
public:
// Constructores de la clase
Episodio();
Episodio(string);
// Método set de la clase
void setTituloEpisodio(string);
// Método get de a clase
string getTituloEpisodio();
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
55393b182bdef8f48954b9caaf1b7cc9a74db6ff | d1f6d1dd18d72b9177ef8a9bbcb2e441a06ab902 | /Basic Level/1069.cpp | 7c68cb78b358397f83faec31b28fc02b7ff3df10 | [] | no_license | oldzhg/PAT | 7a99b4cb66b778ff7539997b1cb1559b8a6d84fc | 92358ca10aa25f7354b85a6319575b226756c885 | refs/heads/master | 2020-11-25T17:28:58.101565 | 2020-02-25T07:16:19 | 2020-02-25T07:16:19 | 228,773,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | //
// Created by oldzhg on 2020-01-31.
//
#include <iostream>
#include <map>
using namespace std;
int main() {
int M, N, S;
string str;
cin >> M >> N >> S;
map<string, int> person; //存储当前用户有没有已经中奖过
bool flag = false;
for (int i = 1; i <= M; ++i) {
cin >> str;
if (person[str] == 1) S += 1;
if (i == S && person[str] == 0) {
person[str] = 1;
cout << str << endl;
flag = true;
S = S + N;
}
}
if (!flag) cout << "Keep going...";
return 0;
}
| [
"zcy000321@gmail.com"
] | zcy000321@gmail.com |
cc62c447bb1e6c1f3850eca9afb86e5e6ce62d60 | 23376108e575e2efb940238f00a2da17b1dc1919 | /include/API/Wallet/Owner/OwnerServer.h | 149172b7a30a95098cb541ed647fc1f546aaff45 | [
"MIT"
] | permissive | fakecoinbase/GrinPlusPlusslashGrinPlusPlus | b05ed68de4aa633d43b9e97939b3dcb37732b7b2 | 34310ff08627769e1a538f828b7e56eeec46bb58 | refs/heads/master | 2022-11-20T20:09:43.836494 | 2020-07-26T01:12:30 | 2020-07-26T01:12:30 | 282,561,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,693 | h | #pragma once
#include <Wallet/WalletManager.h>
#include <Net/Servers/RPC/RPCServer.h>
#include <Net/Tor/TorProcess.h>
#include <API/Wallet/Owner/Handlers/CreateWalletHandler.h>
#include <API/Wallet/Owner/Handlers/RestoreWalletHandler.h>
#include <API/Wallet/Owner/Handlers/LoginHandler.h>
#include <API/Wallet/Owner/Handlers/LogoutHandler.h>
#include <API/Wallet/Owner/Handlers/SendHandler.h>
#include <API/Wallet/Owner/Handlers/ReceiveHandler.h>
#include <API/Wallet/Owner/Handlers/FinalizeHandler.h>
#include <API/Wallet/Owner/Handlers/RetryTorHandler.h>
#include <API/Wallet/Owner/Handlers/DeleteWalletHandler.h>
#include <API/Wallet/Owner/Handlers/GetWalletSeedHandler.h>
#include <API/Wallet/Owner/Handlers/CancelTxHandler.h>
#include <API/Wallet/Owner/Handlers/GetBalanceHandler.h>
#include <API/Wallet/Owner/Handlers/ListTxsHandler.h>
#include <API/Wallet/Owner/Handlers/RepostTxHandler.h>
#include <API/Wallet/Owner/Handlers/EstimateFeeHandler.h>
class OwnerServer
{
public:
using UPtr = std::unique_ptr<OwnerServer>;
OwnerServer(const RPCServerPtr& pServer) : m_pServer(pServer) { }
~OwnerServer() { LOG_INFO("Shutting down owner API"); }
// TODO: Add e2e encryption
static OwnerServer::UPtr Create(const TorProcess::Ptr& pTorProcess, const IWalletManagerPtr& pWalletManager)
{
RPCServerPtr pServer = RPCServer::Create(
EServerType::LOCAL,
std::make_optional<uint16_t>((uint16_t)3421), // TODO: Read port from config (Use same port as v1 owner)
"/v2",
LoggerAPI::LogFile::WALLET
);
/*
Request:
{
"jsonrpc": "2.0",
"method": "create_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!",
"num_seed_words": 24
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("create_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new CreateWalletHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "restore_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!",
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("restore_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new RestoreWalletHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "login",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("login", std::shared_ptr<RPCMethod>((RPCMethod*)new LoginHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "logout",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk="
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {}
}
*/
pServer->AddMethod("logout", std::shared_ptr<RPCMethod>((RPCMethod*)new LogoutHandler(pWalletManager)));
pServer->AddMethod("send", std::shared_ptr<RPCMethod>((RPCMethod*)new SendHandler(pTorProcess, pWalletManager)));
pServer->AddMethod("receive", std::shared_ptr<RPCMethod>((RPCMethod*)new ReceiveHandler(pWalletManager)));
pServer->AddMethod("finalize", std::shared_ptr<RPCMethod>((RPCMethod*)new FinalizeHandler(pTorProcess, pWalletManager)));
pServer->AddMethod("retry_tor", std::shared_ptr<RPCMethod>((RPCMethod*)new RetryTorHandler(pTorProcess, pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "delete_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("delete_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new DeleteWalletHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "get_wallet_seed",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear"
}
}
*/
pServer->AddMethod("get_wallet_seed", std::shared_ptr<RPCMethod>((RPCMethod*)new GetWalletSeedHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "cancel_tx",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"tx_id": 123
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("cancel_tx", std::shared_ptr<RPCMethod>((RPCMethod*)new CancelTxHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "get_balance",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk="
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"total": 20482100000,
"unconfirmed": 6282100000,
"immature": 10200000000,
"locked": 5700000000,
"spendable": 4000000000
}
}
*/
pServer->AddMethod("get_balance", std::shared_ptr<RPCMethod>((RPCMethod*)new GetBalanceHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "list_txs",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"start_range_ms": 1567361400000,
"end_range_ms": 1575227400000,
"statuses": ["COINBASE","SENT","RECEIVED","SENT_CANCELED","RECEIVED_CANCELED","SENDING_NOT_FINALIZED","RECEIVING_IN_PROGRESS", "SENDING_FINALIZED"]
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"txs": []
}
}
*/
pServer->AddMethod("list_txs", std::shared_ptr<RPCMethod>((RPCMethod*)new ListTxsHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "repost_tx",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"tx_id": 123,
"method": "STEM"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("repost_tx", std::shared_ptr<RPCMethod>((RPCMethod*)new RepostTxHandler(pTorProcess, pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "estimate_fee",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"amount": 12345678,
"fee_base": "1000000",
"change_outputs": 1,
"selection_strategy": {
"strategy": "SMALLEST"
}
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"fee": "7000000",
"inputs": [
{
"keychain_path": "m/1/0/1000",
"commitment": "0808657d5346f4061e5484b6f57ed036ce2cb4430599cec5dcb999d07755772010",
"amount": 30000000,
"status": "Spendable"
}
]
}
}
*/
pServer->AddMethod("estimate_fee", std::shared_ptr<RPCMethod>((RPCMethod*)new EstimateFeeHandler(pWalletManager)));
// TODO: Add the following APIs:
// authenticate - Simply validates the password - useful for confirming password before sending funds
// tx_info - Detailed info about a specific transaction (status, kernels, inputs, outputs, payment proofs, labels, etc)
// update_labels - Add or remove labels - useful for coin control
// verify_payment_proof - Takes in an existing payment proof and validates it
return std::make_unique<OwnerServer>(pServer);
}
private:
RPCServerPtr m_pServer;
}; | [
"davidburkett38@gmail.com"
] | davidburkett38@gmail.com |
4a135a648ccb3a07e42d05b88a2c0ba6a10c501b | a76e25b6c2941fa82e1917138d7c328eeb5f1500 | /Machine Novelist Project/CSVReader.h | 2e2c1071b407060399851e0ede35deb5fae4fb4f | [
"Apache-2.0"
] | permissive | ajitkoduri/Code-for-Blog-Posts | 0985e85244c213a4064bd22fac013fbed0751f00 | 4892ae8a4244e970a3932decaebeca3d5da6a577 | refs/heads/master | 2021-09-06T09:46:20.395318 | 2018-02-05T05:29:23 | 2018-02-05T05:29:23 | 114,692,130 | 3 | 0 | Apache-2.0 | 2018-01-23T06:27:06 | 2017-12-18T22:03:15 | Python | UTF-8 | C++ | false | false | 3,283 | h | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
//structure to read a csv file
struct csvreader
{
vector <vector <string> > data; //data entry
vector <string> heading; //heading for data
void read(const string& filename, bool header = true) //automaticall assume heading is there
{
heading.clear(); //empty initial header
data.clear(); //empty the initial data
vector <string> line_data; //data per line entry
string line; //unparsed row
string cell; //data inside each cell
ifstream file; //file to extract data from
file.open(filename);
if (file.is_open())
{
int l_index = 0; //line index
while (getline(file, line))
{
line_data.clear(); //empty the data found in the line
//after each iteration
line = line + ","; //in the case that the last cell in the line
//is empty, I append a comma to the line.
istringstream iss(line); //string stream for line data
if (header == true && l_index == 0) //gathering heading data if there
{
int cell_num = 0;
while (getline(iss, cell, ','))
{
if (cell.empty()) //if the cell is empty,
heading.push_back(to_string(cell_num)); //append a space as a header.
else
{
int cell_index = 0;
while (cell[cell_index] == ' ') //trim leading whitespace
{
cell_index++;
cell = cell.substr(cell_index, cell.length());
}
cell_index = cell.size()-1;
while (cell[cell_index] == ' ') //trim ending whitespace
{
cell = cell.substr(0, cell_index);
cell_index--;
}
heading.push_back(cell); //append the cell name
}
cell_num++; //increase cell number with each iteration
}
data.resize(heading.size()); //number of columns is same
//as number of columns of header
}
else
{
while (getline(iss, cell, ',')) //parsing data from each row
{
if (cell.empty()) //check if the cell data is empty
line_data.push_back("NA"); //if it is, consider it NULL
else
{
int cell_index = 0; //trim leading whitespace
while (cell[cell_index] == ' ')
{
cell_index++;
cell = cell.substr(cell_index, cell.length());
}
cell_index = cell.size() - 1;
while (cell[cell_index] == ' ') //trim ending whitespace
{
cell = cell.substr(0, cell_index);
cell_index--;
}
line_data.push_back(cell); //if it is not, append the cell
}
}
if (l_index == 0 && header == false) //resize columns appropriately
data.resize(line_data.size()); //from first row
for (int column = 0; column < data.size(); column++)
{
if (line_data[column] != "NA") //if the cell was empty
data[column].push_back(line_data[column]); //append line data to
//rest of data
}
}
l_index++; //moving to the next line
}
file.close();
}
}
}; | [
"noreply@github.com"
] | noreply@github.com |
0c04dc6ced345643ee631886c79711c493288382 | 925f9ff0398485ca905b775d994c537cd0f89446 | /Programming Codes in Cpp/subarraysofanArray.cpp | bfbeb022972015f55a98e6db4800186c2fbc477e | [] | no_license | ChandanKuilya/Cpp-Algorithmic-Programming-Codes | 2a0250a586b0fbb6edbdf5549aab6847c80d05e1 | f8bcf5683d890bf8b34a1d68601d926b82f08e29 | refs/heads/main | 2023-09-04T01:05:45.913102 | 2021-11-12T14:31:51 | 2021-11-12T14:31:51 | 427,384,824 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | #include<bits/stdc++.h>
using namespace std;
void subarrays(int a[],int n){
int cnt=0;
for (int i=0;i<n;i++){
for (int j=i;j<n;j++){
for (int k=i;k<=j;k++){
cout<<a[k]<<" ";
}
cnt++;
cout<<endl;
cout<<"Number of subarrays til now: "<<cnt<<endl;
}
}
}
int main(){
int n;
cin>>n;
int a[n];
for (int i=0;i<n;i++){
cin>>a[i];
}
subarrays(a,n);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
bd2ace985a6f98e575000c08ed5f1fc08196f86b | 6530d7521fb339ff20269d90992dc0aa0e4a7080 | /src/server/game/Spells/Auras/SpellAuraEffects.cpp | e73f99d5dd819efbd99de1f31bd09b5a7474e650 | [] | no_license | Maczuga/WoW-Open-World-Sandbox | d233326620888db3e1a880f4524130880cb7d143 | 1496c94003fb7d03b9c0194d7319befb06987138 | refs/heads/master | 2020-03-22T18:10:38.403158 | 2018-07-13T07:24:21 | 2018-07-13T07:24:21 | 140,442,256 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281,108 | cpp | /*
* Copyright (C)
* Copyright (C)
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "WorldPacket.h"
#include "Opcodes.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Unit.h"
#include "ObjectAccessor.h"
#include "Util.h"
#include "Spell.h"
#include "SpellAuraEffects.h"
#include "Formulas.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "ScriptMgr.h"
#include "Vehicle.h"
#include "Pet.h"
#include "ReputationMgr.h"
class Aura;
//
// EFFECT HANDLER NOTES
//
// in aura handler there should be check for modes:
// AURA_EFFECT_HANDLE_REAL set
// AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK set
// AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK set - aura is recalculated or is just applied/removed - need to redo all things related to m_amount
// AURA_EFFECT_HANDLE_CHANGE_AMOUNT_SEND_FOR_CLIENT_MASK - logical or of above conditions
// AURA_EFFECT_HANDLE_STAT - set when stats are reapplied
// such checks will speedup trinity change amount/send for client operations
// because for change amount operation packets will not be send
// aura effect handlers shouldn't contain any AuraEffect or Aura object modifications
pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]=
{
&AuraEffect::HandleNULL, // 0 SPELL_AURA_NONE
&AuraEffect::HandleBindSight, // 1 SPELL_AURA_BIND_SIGHT
&AuraEffect::HandleModPossess, // 2 SPELL_AURA_MOD_POSSESS
&AuraEffect::HandleNoImmediateEffect, // 3 SPELL_AURA_PERIODIC_DAMAGE implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleAuraDummy, // 4 SPELL_AURA_DUMMY
&AuraEffect::HandleModConfuse, // 5 SPELL_AURA_MOD_CONFUSE
&AuraEffect::HandleModCharm, // 6 SPELL_AURA_MOD_CHARM
&AuraEffect::HandleModFear, // 7 SPELL_AURA_MOD_FEAR
&AuraEffect::HandleNoImmediateEffect, // 8 SPELL_AURA_PERIODIC_HEAL implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleModAttackSpeed, // 9 SPELL_AURA_MOD_ATTACKSPEED
&AuraEffect::HandleModThreat, // 10 SPELL_AURA_MOD_THREAT
&AuraEffect::HandleModTaunt, // 11 SPELL_AURA_MOD_TAUNT
&AuraEffect::HandleAuraModStun, // 12 SPELL_AURA_MOD_STUN
&AuraEffect::HandleModDamageDone, // 13 SPELL_AURA_MOD_DAMAGE_DONE
&AuraEffect::HandleNoImmediateEffect, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonus and Unit::SpellDamageBonus
&AuraEffect::HandleNoImmediateEffect, // 15 SPELL_AURA_DAMAGE_SHIELD implemented in Unit::DoAttackDamage
&AuraEffect::HandleModStealth, // 16 SPELL_AURA_MOD_STEALTH
&AuraEffect::HandleModStealthDetect, // 17 SPELL_AURA_MOD_DETECT
&AuraEffect::HandleModInvisibility, // 18 SPELL_AURA_MOD_INVISIBILITY
&AuraEffect::HandleModInvisibilityDetect, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION
&AuraEffect::HandleNoImmediateEffect, // 20 SPELL_AURA_OBS_MOD_HEALTH implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, // 21 SPELL_AURA_OBS_MOD_POWER implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleAuraModResistance, // 22 SPELL_AURA_MOD_RESISTANCE
&AuraEffect::HandleNoImmediateEffect, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, // 24 SPELL_AURA_PERIODIC_ENERGIZE implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleAuraModPacify, // 25 SPELL_AURA_MOD_PACIFY
&AuraEffect::HandleAuraModRoot, // 26 SPELL_AURA_MOD_ROOT
&AuraEffect::HandleAuraModSilence, // 27 SPELL_AURA_MOD_SILENCE
&AuraEffect::HandleNoImmediateEffect, // 28 SPELL_AURA_REFLECT_SPELLS implement in Unit::SpellHitResult
&AuraEffect::HandleAuraModStat, // 29 SPELL_AURA_MOD_STAT
&AuraEffect::HandleAuraModSkill, // 30 SPELL_AURA_MOD_SKILL
&AuraEffect::HandleAuraModIncreaseSpeed, // 31 SPELL_AURA_MOD_INCREASE_SPEED
&AuraEffect::HandleAuraModIncreaseMountedSpeed, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED
&AuraEffect::HandleAuraModDecreaseSpeed, // 33 SPELL_AURA_MOD_DECREASE_SPEED
&AuraEffect::HandleAuraModIncreaseHealth, // 34 SPELL_AURA_MOD_INCREASE_HEALTH
&AuraEffect::HandleAuraModIncreaseEnergy, // 35 SPELL_AURA_MOD_INCREASE_ENERGY
&AuraEffect::HandleAuraModShapeshift, // 36 SPELL_AURA_MOD_SHAPESHIFT
&AuraEffect::HandleAuraModEffectImmunity, // 37 SPELL_AURA_EFFECT_IMMUNITY
&AuraEffect::HandleAuraModStateImmunity, // 38 SPELL_AURA_STATE_IMMUNITY
&AuraEffect::HandleAuraModSchoolImmunity, // 39 SPELL_AURA_SCHOOL_IMMUNITY
&AuraEffect::HandleAuraModDmgImmunity, // 40 SPELL_AURA_DAMAGE_IMMUNITY
&AuraEffect::HandleAuraModDispelImmunity, // 41 SPELL_AURA_DISPEL_IMMUNITY
&AuraEffect::HandleNoImmediateEffect, // 42 SPELL_AURA_PROC_TRIGGER_SPELL implemented in Unit::ProcDamageAndSpellFor and Unit::HandleProcTriggerSpell
&AuraEffect::HandleNoImmediateEffect, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE implemented in Unit::ProcDamageAndSpellFor
&AuraEffect::HandleAuraTrackCreatures, // 44 SPELL_AURA_TRACK_CREATURES
&AuraEffect::HandleAuraTrackResources, // 45 SPELL_AURA_TRACK_RESOURCES
&AuraEffect::HandleNULL, // 46 SPELL_AURA_46 (used in test spells 54054 and 54058, and spell 48050) (3.0.8a)
&AuraEffect::HandleAuraModParryPercent, // 47 SPELL_AURA_MOD_PARRY_PERCENT
&AuraEffect::HandleNULL, // 48 SPELL_AURA_48 spell Napalm (area damage spell with additional delayed damage effect)
&AuraEffect::HandleAuraModDodgePercent, // 49 SPELL_AURA_MOD_DODGE_PERCENT
&AuraEffect::HandleNoImmediateEffect, // 50 SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT implemented in Unit::SpellCriticalHealingBonus
&AuraEffect::HandleAuraModBlockPercent, // 51 SPELL_AURA_MOD_BLOCK_PERCENT
&AuraEffect::HandleAuraModWeaponCritPercent, // 52 SPELL_AURA_MOD_WEAPON_CRIT_PERCENT
&AuraEffect::HandleNoImmediateEffect, // 53 SPELL_AURA_PERIODIC_LEECH implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleModHitChance, // 54 SPELL_AURA_MOD_HIT_CHANCE
&AuraEffect::HandleModSpellHitChance, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE
&AuraEffect::HandleAuraTransform, // 56 SPELL_AURA_TRANSFORM
&AuraEffect::HandleModSpellCritChance, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE
&AuraEffect::HandleAuraModIncreaseSwimSpeed, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED
&AuraEffect::HandleNoImmediateEffect, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE implemented in Unit::MeleeDamageBonus and Unit::SpellDamageBonus
&AuraEffect::HandleAuraModPacifyAndSilence, // 60 SPELL_AURA_MOD_PACIFY_SILENCE
&AuraEffect::HandleAuraModScale, // 61 SPELL_AURA_MOD_SCALE
&AuraEffect::HandleNoImmediateEffect, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNULL, // 63 unused (3.2.0) old SPELL_AURA_PERIODIC_MANA_FUNNEL
&AuraEffect::HandleNoImmediateEffect, // 64 SPELL_AURA_PERIODIC_MANA_LEECH implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleModCastingSpeed, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK
&AuraEffect::HandleFeignDeath, // 66 SPELL_AURA_FEIGN_DEATH
&AuraEffect::HandleAuraModDisarm, // 67 SPELL_AURA_MOD_DISARM
&AuraEffect::HandleAuraModStalked, // 68 SPELL_AURA_MOD_STALKED
&AuraEffect::HandleNoImmediateEffect, // 69 SPELL_AURA_SCHOOL_ABSORB implemented in Unit::CalcAbsorbResist
&AuraEffect::HandleUnused, // 70 SPELL_AURA_EXTRA_ATTACKS clientside
&AuraEffect::HandleModSpellCritChanceShool, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL
&AuraEffect::HandleModPowerCostPCT, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT
&AuraEffect::HandleModPowerCost, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL
&AuraEffect::HandleNoImmediateEffect, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL implemented in Unit::SpellHitResult
&AuraEffect::HandleNoImmediateEffect, // 75 SPELL_AURA_MOD_LANGUAGE
&AuraEffect::HandleNoImmediateEffect, // 76 SPELL_AURA_FAR_SIGHT
&AuraEffect::HandleModMechanicImmunity, // 77 SPELL_AURA_MECHANIC_IMMUNITY
&AuraEffect::HandleAuraMounted, // 78 SPELL_AURA_MOUNTED
&AuraEffect::HandleModDamagePercentDone, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
&AuraEffect::HandleModPercentStat, // 80 SPELL_AURA_MOD_PERCENT_STAT
&AuraEffect::HandleNoImmediateEffect, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT implemented in Unit::CalcAbsorbResist
&AuraEffect::HandleWaterBreathing, // 82 SPELL_AURA_WATER_BREATHING
&AuraEffect::HandleModBaseResistance, // 83 SPELL_AURA_MOD_BASE_RESISTANCE
&AuraEffect::HandleNoImmediateEffect, // 84 SPELL_AURA_MOD_REGEN implemented in Player::RegenerateHealth
&AuraEffect::HandleModPowerRegen, // 85 SPELL_AURA_MOD_POWER_REGEN implemented in Player::Regenerate
&AuraEffect::HandleChannelDeathItem, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM
&AuraEffect::HandleNoImmediateEffect, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN implemented in Unit::MeleeDamageBonus and Unit::SpellDamageBonus
&AuraEffect::HandleNoImmediateEffect, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT implemented in Player::RegenerateHealth
&AuraEffect::HandleNoImmediateEffect, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT
&AuraEffect::HandleNULL, // 90 unused (3.0.8a) old SPELL_AURA_MOD_RESIST_CHANCE
&AuraEffect::HandleNoImmediateEffect, // 91 SPELL_AURA_MOD_DETECT_RANGE implemented in Creature::GetAggroRange
&AuraEffect::HandlePreventFleeing, // 92 SPELL_AURA_PREVENTS_FLEEING
&AuraEffect::HandleModUnattackable, // 93 SPELL_AURA_MOD_UNATTACKABLE
&AuraEffect::HandleNoImmediateEffect, // 94 SPELL_AURA_INTERRUPT_REGEN implemented in Player::Regenerate
&AuraEffect::HandleAuraGhost, // 95 SPELL_AURA_GHOST
&AuraEffect::HandleNoImmediateEffect, // 96 SPELL_AURA_SPELL_MAGNET implemented in Unit::SelectMagnetTarget
&AuraEffect::HandleNoImmediateEffect, // 97 SPELL_AURA_MANA_SHIELD implemented in Unit::CalcAbsorbResist
&AuraEffect::HandleAuraModSkill, // 98 SPELL_AURA_MOD_SKILL_TALENT
&AuraEffect::HandleAuraModAttackPower, // 99 SPELL_AURA_MOD_ATTACK_POWER
&AuraEffect::HandleUnused, //100 SPELL_AURA_AURAS_VISIBLE obsolete? all player can see all auras now, but still have spells including GM-spell
&AuraEffect::HandleModResistancePercent, //101 SPELL_AURA_MOD_RESISTANCE_PCT
&AuraEffect::HandleNoImmediateEffect, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleAuraModTotalThreat, //103 SPELL_AURA_MOD_TOTAL_THREAT
&AuraEffect::HandleAuraWaterWalk, //104 SPELL_AURA_WATER_WALK
&AuraEffect::HandleAuraFeatherFall, //105 SPELL_AURA_FEATHER_FALL
&AuraEffect::HandleAuraHover, //106 SPELL_AURA_HOVER
&AuraEffect::HandleNoImmediateEffect, //107 SPELL_AURA_ADD_FLAT_MODIFIER implemented in AuraEffect::CalculateSpellMod()
&AuraEffect::HandleNoImmediateEffect, //108 SPELL_AURA_ADD_PCT_MODIFIER implemented in AuraEffect::CalculateSpellMod()
&AuraEffect::HandleNoImmediateEffect, //109 SPELL_AURA_ADD_TARGET_TRIGGER
&AuraEffect::HandleModPowerRegenPCT, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT implemented in Player::Regenerate, Creature::Regenerate
&AuraEffect::HandleNoImmediateEffect, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER implemented in Unit::SelectMagnetTarget
&AuraEffect::HandleNoImmediateEffect, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS
&AuraEffect::HandleNoImmediateEffect, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleNoImmediateEffect, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleNoImmediateEffect, //115 SPELL_AURA_MOD_HEALING implemented in Unit::SpellBaseHealingBonusForVictim
&AuraEffect::HandleNoImmediateEffect, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT
&AuraEffect::HandleNoImmediateEffect, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE implemented in Unit::MagicSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //118 SPELL_AURA_MOD_HEALING_PCT implemented in Unit::SpellHealingBonus
&AuraEffect::HandleNULL, //119 unused (3.2.0) old SPELL_AURA_SHARE_PET_TRACKING
&AuraEffect::HandleAuraUntrackable, //120 SPELL_AURA_UNTRACKABLE
&AuraEffect::HandleAuraEmpathy, //121 SPELL_AURA_EMPATHY
&AuraEffect::HandleModOffhandDamagePercent, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT
&AuraEffect::HandleModTargetResistance, //123 SPELL_AURA_MOD_TARGET_RESISTANCE
&AuraEffect::HandleAuraModRangedAttackPower, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER
&AuraEffect::HandleNoImmediateEffect, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleNoImmediateEffect, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleNoImmediateEffect, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleModPossessPet, //128 SPELL_AURA_MOD_POSSESS_PET
&AuraEffect::HandleAuraModIncreaseSpeed, //129 SPELL_AURA_MOD_SPEED_ALWAYS
&AuraEffect::HandleAuraModIncreaseMountedSpeed, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS
&AuraEffect::HandleNoImmediateEffect, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleAuraModIncreaseEnergyPercent, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT
&AuraEffect::HandleAuraModIncreaseHealthPercent, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT
&AuraEffect::HandleAuraModRegenInterrupt, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT
&AuraEffect::HandleModHealingDone, //135 SPELL_AURA_MOD_HEALING_DONE
&AuraEffect::HandleNoImmediateEffect, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT implemented in Unit::SpellHealingBonus
&AuraEffect::HandleModTotalPercentStat, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE
&AuraEffect::HandleModMeleeSpeedPct, //138 SPELL_AURA_MOD_MELEE_HASTE
&AuraEffect::HandleForceReaction, //139 SPELL_AURA_FORCE_REACTION
&AuraEffect::HandleAuraModRangedHaste, //140 SPELL_AURA_MOD_RANGED_HASTE
&AuraEffect::HandleRangedAmmoHaste, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE
&AuraEffect::HandleAuraModBaseResistancePCT, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT
&AuraEffect::HandleAuraModResistanceExclusive, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE
&AuraEffect::HandleNoImmediateEffect, //144 SPELL_AURA_SAFE_FALL implemented in WorldSession::HandleMovementOpcodes
&AuraEffect::HandleAuraModPetTalentsPoints, //145 SPELL_AURA_MOD_PET_TALENT_POINTS
&AuraEffect::HandleNoImmediateEffect, //146 SPELL_AURA_ALLOW_TAME_PET_TYPE
&AuraEffect::HandleModStateImmunityMask, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK
&AuraEffect::HandleAuraRetainComboPoints, //148 SPELL_AURA_RETAIN_COMBO_POINTS
&AuraEffect::HandleNoImmediateEffect, //149 SPELL_AURA_REDUCE_PUSHBACK
&AuraEffect::HandleShieldBlockValue, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT
&AuraEffect::HandleAuraTrackStealthed, //151 SPELL_AURA_TRACK_STEALTHED
&AuraEffect::HandleNoImmediateEffect, //152 SPELL_AURA_MOD_DETECTED_RANGE implemented in Creature::GetAggroRange
&AuraEffect::HandleNoImmediateEffect, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT
&AuraEffect::HandleModStealthLevel, //154 SPELL_AURA_MOD_STEALTH_LEVEL
&AuraEffect::HandleNoImmediateEffect, //155 SPELL_AURA_MOD_WATER_BREATHING
&AuraEffect::HandleNoImmediateEffect, //156 SPELL_AURA_MOD_REPUTATION_GAIN
&AuraEffect::HandleNULL, //157 SPELL_AURA_PET_DAMAGE_MULTI
&AuraEffect::HandleShieldBlockValue, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE
&AuraEffect::HandleNoImmediateEffect, //159 SPELL_AURA_NO_PVP_CREDIT only for Honorless Target spell
&AuraEffect::HandleNoImmediateEffect, //160 SPELL_AURA_MOD_AOE_AVOIDANCE implemented in Unit::MagicSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
&AuraEffect::HandleNoImmediateEffect, //162 SPELL_AURA_POWER_BURN implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
&AuraEffect::HandleUnused, //164 unused (3.2.0), only one test spell
&AuraEffect::HandleNoImmediateEffect, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonus
&AuraEffect::HandleAuraModAttackPowerPercent, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT
&AuraEffect::HandleAuraModRangedAttackPowerPercent, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT
&AuraEffect::HandleNoImmediateEffect, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS implemented in Unit::SpellDamageBonus, Unit::MeleeDamageBonus
&AuraEffect::HandleNoImmediateEffect, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS implemented in Unit::DealDamageBySchool, Unit::DoAttackDamage, Unit::SpellCriticalBonus
&AuraEffect::HandleNULL, //170 SPELL_AURA_DETECT_AMORE various spells that change visual of units for aura target (clientside?)
&AuraEffect::HandleAuraModIncreaseSpeed, //171 SPELL_AURA_MOD_SPEED_NOT_STACK
&AuraEffect::HandleAuraModIncreaseMountedSpeed, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK
&AuraEffect::HandleNULL, //173 unused (3.2.0) no spells, old SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell
&AuraEffect::HandleModSpellDamagePercentFromStat, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT implemented in Unit::SpellBaseDamageBonus
&AuraEffect::HandleModSpellHealingPercentFromStat, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT implemented in Unit::SpellBaseHealingBonus
&AuraEffect::HandleSpiritOfRedemption, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end
&AuraEffect::HandleCharmConvert, //177 SPELL_AURA_AOE_CHARM
&AuraEffect::HandleNoImmediateEffect, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE implemented in Unit::MagicSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE implemented in Unit::SpellCriticalBonus
&AuraEffect::HandleNoImmediateEffect, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS implemented in Unit::SpellDamageBonus
&AuraEffect::HandleNULL, //181 unused (3.2.0) old SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS
&AuraEffect::HandleAuraModResistenceOfStatPercent, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT
&AuraEffect::HandleNULL, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746 - miscvalue - spell school
&AuraEffect::HandleNoImmediateEffect, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&AuraEffect::HandleNoImmediateEffect, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&AuraEffect::HandleNoImmediateEffect, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE implemented in Unit::MagicSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE implemented in ObjectAccessor::GetUnitCriticalChance
&AuraEffect::HandleNoImmediateEffect, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE implemented in ObjectAccessor::GetUnitCriticalChance
&AuraEffect::HandleModRating, //189 SPELL_AURA_MOD_RATING
&AuraEffect::HandleNoImmediateEffect, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN implemented in Player::CalculateReputationGain
&AuraEffect::HandleAuraModUseNormalSpeed, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED
&AuraEffect::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_MOD_MELEE_RANGED_HASTE
&AuraEffect::HandleModCombatSpeedPct, //193 SPELL_AURA_MELEE_SLOW (in fact combat (any type attack) speed pct)
&AuraEffect::HandleNoImmediateEffect, //194 SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL implemented in Unit::CalcAbsorbResist
&AuraEffect::HandleNoImmediateEffect, //195 SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL implemented in Unit::CalcAbsorbResist
&AuraEffect::HandleNoImmediateEffect, //196 SPELL_AURA_MOD_COOLDOWN - flat mod of spell cooldowns
&AuraEffect::HandleNoImmediateEffect, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE implemented in Unit::SpellCriticalBonus ObjectAccessor::GetUnitCriticalChance
&AuraEffect::HandleNULL, //198 unused (3.2.0) old SPELL_AURA_MOD_ALL_WEAPON_SKILLS
&AuraEffect::HandleNoImmediateEffect, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT implemented in Unit::MagicSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //200 SPELL_AURA_MOD_XP_PCT implemented in Player::RewardPlayerAndGroupAtKill
&AuraEffect::HandleAuraAllowFlight, //201 SPELL_AURA_FLY this aura enable flight mode...
&AuraEffect::HandleNoImmediateEffect, //202 SPELL_AURA_CANNOT_BE_DODGED implemented in Unit::RollPhysicalOutcomeAgainst
&AuraEffect::HandleNoImmediateEffect, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::CalculateSpellDamage
&AuraEffect::HandleNoImmediateEffect, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::CalculateSpellDamage
&AuraEffect::HandleNULL, //205 SPELL_AURA_MOD_SCHOOL_CRIT_DMG_TAKEN
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //206 SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //207 SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //208 SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //209 SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //210 SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS
&AuraEffect::HandleAuraModIncreaseFlightSpeed, //211 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK
&AuraEffect::HandleAuraModRangedAttackPowerOfStatPercent, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT
&AuraEffect::HandleNoImmediateEffect, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage
&AuraEffect::HandleNULL, //214 Tamed Pet Passive
&AuraEffect::HandleArenaPreparation, //215 SPELL_AURA_ARENA_PREPARATION
&AuraEffect::HandleModCastingSpeed, //216 SPELL_AURA_HASTE_SPELLS
&AuraEffect::HandleNULL, //217 69106 - killing spree helper - unknown use
&AuraEffect::HandleAuraModRangedHaste, //218 SPELL_AURA_HASTE_RANGED
&AuraEffect::HandleModManaRegen, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT
&AuraEffect::HandleModRatingFromStat, //220 SPELL_AURA_MOD_RATING_FROM_STAT
&AuraEffect::HandleNoImmediateEffect, //221 SPELL_AURA_IGNORED
&AuraEffect::HandleUnused, //222 unused (3.2.0) only for spell 44586 that not used in real spell cast
&AuraEffect::HandleNoImmediateEffect, //223 SPELL_AURA_RAID_PROC_FROM_CHARGE
&AuraEffect::HandleUnused, //224 unused (3.0.8a)
&AuraEffect::HandleNoImmediateEffect, //225 SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE
&AuraEffect::HandleNoImmediateEffect, //226 SPELL_AURA_PERIODIC_DUMMY implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, //228 SPELL_AURA_DETECT_STEALTH stealth detection
&AuraEffect::HandleNoImmediateEffect, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE
&AuraEffect::HandleAuraModIncreaseHealth, //230 SPELL_AURA_MOD_INCREASE_HEALTH_2
&AuraEffect::HandleNoImmediateEffect, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE
&AuraEffect::HandleNoImmediateEffect, //232 SPELL_AURA_MECHANIC_DURATION_MOD implement in Unit::CalculateSpellDuration
&AuraEffect::HandleUnused, //233 set model id to the one of the creature with id GetMiscValue() - clientside
&AuraEffect::HandleNoImmediateEffect, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK implement in Unit::CalculateSpellDuration
&AuraEffect::HandleNoImmediateEffect, //235 SPELL_AURA_MOD_DISPEL_RESIST implement in Unit::MagicSpellHitResult
&AuraEffect::HandleAuraControlVehicle, //236 SPELL_AURA_CONTROL_VEHICLE
&AuraEffect::HandleModSpellDamagePercentFromAttackPower, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER implemented in Unit::SpellBaseDamageBonus
&AuraEffect::HandleModSpellHealingPercentFromAttackPower, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER implemented in Unit::SpellBaseHealingBonus
&AuraEffect::HandleAuraModScale, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61
&AuraEffect::HandleAuraModExpertise, //240 SPELL_AURA_MOD_EXPERTISE
&AuraEffect::HandleForceMoveForward, //241 SPELL_AURA_FORCE_MOVE_FORWARD Forces the caster to move forward
&AuraEffect::HandleNULL, //242 SPELL_AURA_MOD_SPELL_DAMAGE_FROM_HEALING - 2 test spells: 44183 and 44182
&AuraEffect::HandleAuraModFaction, //243 SPELL_AURA_MOD_FACTION
&AuraEffect::HandleComprehendLanguage, //244 SPELL_AURA_COMPREHEND_LANGUAGE
&AuraEffect::HandleNoImmediateEffect, //245 SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL
&AuraEffect::HandleNoImmediateEffect, //246 SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK implemented in Spell::EffectApplyAura
&AuraEffect::HandleAuraCloneCaster, //247 SPELL_AURA_CLONE_CASTER
&AuraEffect::HandleNoImmediateEffect, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&AuraEffect::HandleAuraConvertRune, //249 SPELL_AURA_CONVERT_RUNE
&AuraEffect::HandleAuraModIncreaseHealth, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2
&AuraEffect::HandleNoImmediateEffect, //251 SPELL_AURA_MOD_ENEMY_DODGE
&AuraEffect::HandleModCombatSpeedPct, //252 SPELL_AURA_252 Is there any difference between this and SPELL_AURA_MELEE_SLOW ? maybe not stacking mod?
&AuraEffect::HandleNoImmediateEffect, //253 SPELL_AURA_MOD_BLOCK_CRIT_CHANCE implemented in Unit::isBlockCritical
&AuraEffect::HandleAuraModDisarm, //254 SPELL_AURA_MOD_DISARM_OFFHAND
&AuraEffect::HandleNoImmediateEffect, //255 SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT implemented in Unit::SpellDamageBonus
&AuraEffect::HandleNoReagentUseAura, //256 SPELL_AURA_NO_REAGENT_USE Use SpellClassMask for spell select
&AuraEffect::HandleNULL, //257 SPELL_AURA_MOD_TARGET_RESIST_BY_SPELL_CLASS Use SpellClassMask for spell select
&AuraEffect::HandleNULL, //258 SPELL_AURA_MOD_SPELL_VISUAL
&AuraEffect::HandleNoImmediateEffect, //259 SPELL_AURA_MOD_HOT_PCT implemented in Unit::SpellHealingBonus
&AuraEffect::HandleNoImmediateEffect, //260 SPELL_AURA_SCREEN_EFFECT (miscvalue = id in ScreenEffect.dbc) not required any code
&AuraEffect::HandlePhase, //261 SPELL_AURA_PHASE
&AuraEffect::HandleNoImmediateEffect, //262 SPELL_AURA_ABILITY_IGNORE_AURASTATE implemented in spell::cancast
&AuraEffect::HandleAuraAllowOnlyAbility, //263 SPELL_AURA_ALLOW_ONLY_ABILITY player can use only abilities set in SpellClassMask
&AuraEffect::HandleUnused, //264 unused (3.2.0)
&AuraEffect::HandleUnused, //265 unused (3.2.0)
&AuraEffect::HandleUnused, //266 unused (3.2.0)
&AuraEffect::HandleNoImmediateEffect, //267 SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL implemented in Unit::IsImmunedToSpellEffect
&AuraEffect::HandleAuraModAttackPowerOfStatPercent, //268 SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT
&AuraEffect::HandleNoImmediateEffect, //269 SPELL_AURA_MOD_IGNORE_TARGET_RESIST implemented in Unit::CalcAbsorbResist and CalcArmorReducedDamage
&AuraEffect::HandleNoImmediateEffect, //270 SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST implemented in Unit::CalcAbsorbResist and CalcArmorReducedDamage
&AuraEffect::HandleNoImmediateEffect, //271 SPELL_AURA_MOD_DAMAGE_FROM_CASTER implemented in Unit::SpellDamageBonus
&AuraEffect::HandleNoImmediateEffect, //272 SPELL_AURA_IGNORE_MELEE_RESET
&AuraEffect::HandleUnused, //273 clientside
&AuraEffect::HandleNoImmediateEffect, //274 SPELL_AURA_CONSUME_NO_AMMO implemented in spell::CalculateDamageDoneForAllTargets
&AuraEffect::HandleNoImmediateEffect, //275 SPELL_AURA_MOD_IGNORE_SHAPESHIFT Use SpellClassMask for spell select
&AuraEffect::HandleNULL, //276 mod damage % mechanic?
&AuraEffect::HandleNoImmediateEffect, //277 SPELL_AURA_MOD_ABILITY_AFFECTED_TARGETS implemented in spell::settargetmap
&AuraEffect::HandleAuraModDisarm, //278 SPELL_AURA_MOD_DISARM_RANGED disarm ranged weapon
&AuraEffect::HandleNoImmediateEffect, //279 SPELL_AURA_INITIALIZE_IMAGES
&AuraEffect::HandleNoImmediateEffect, //280 SPELL_AURA_MOD_TARGET_ARMOR_PCT
&AuraEffect::HandleNoImmediateEffect, //281 SPELL_AURA_MOD_HONOR_GAIN_PCT implemented in Player::RewardHonor
&AuraEffect::HandleAuraIncreaseBaseHealthPercent, //282 SPELL_AURA_INCREASE_BASE_HEALTH_PERCENT
&AuraEffect::HandleNoImmediateEffect, //283 SPELL_AURA_MOD_HEALING_RECEIVED implemented in Unit::SpellHealingBonus
&AuraEffect::HandleAuraLinked, //284 SPELL_AURA_LINKED
&AuraEffect::HandleAuraModAttackPowerOfArmor, //285 SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR implemented in Player::UpdateAttackPowerAndDamage
&AuraEffect::HandleNoImmediateEffect, //286 SPELL_AURA_ABILITY_PERIODIC_CRIT implemented in AuraEffect::PeriodicTick
&AuraEffect::HandleNoImmediateEffect, //287 SPELL_AURA_DEFLECT_SPELLS implemented in Unit::MagicSpellHitResult and Unit::MeleeSpellHitResult
&AuraEffect::HandleNoImmediateEffect, //288 SPELL_AURA_IGNORE_HIT_DIRECTION implemented in Unit::MagicSpellHitResult and Unit::MeleeSpellHitResult Unit::RollMeleeOutcomeAgainst
&AuraEffect::HandleNULL, //289 unused (3.2.0)
&AuraEffect::HandleAuraModCritPct, //290 SPELL_AURA_MOD_CRIT_PCT
&AuraEffect::HandleNoImmediateEffect, //291 SPELL_AURA_MOD_XP_QUEST_PCT implemented in Player::RewardQuest
&AuraEffect::HandleNULL, //292 SPELL_AURA_OPEN_STABLE
&AuraEffect::HandleAuraOverrideSpells, //293 auras which probably add set of abilities to their target based on it's miscvalue
&AuraEffect::HandleModManaRegen, //294 SPELL_AURA_PREVENT_REGENERATE_POWER implemented in Player::Regenerate(Powers power), HandleModManaRegen to refresh regeneration clientside
&AuraEffect::HandleNULL, //295 0 spells in 3.3.5
&AuraEffect::HandleAuraSetVehicle, //296 SPELL_AURA_SET_VEHICLE_ID sets vehicle on target
&AuraEffect::HandleNULL, //297 Spirit Burst spells
&AuraEffect::HandleNULL, //298 70569 - Strangulating, maybe prevents talk or cast
&AuraEffect::HandleNULL, //299 unused
&AuraEffect::HandleNoImmediateEffect, //300 SPELL_AURA_SHARE_DAMAGE_PCT implemented in Unit::DealDamage
&AuraEffect::HandleNoImmediateEffect, //301 SPELL_AURA_SCHOOL_HEAL_ABSORB implemented in Unit::CalcHealAbsorb
&AuraEffect::HandleNULL, //302 0 spells in 3.3.5
&AuraEffect::HandleNoImmediateEffect, //303 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE implemented in Unit::SpellDamageBonus, Unit::MeleeDamageBonus
&AuraEffect::HandleAuraModFakeInebriation, //304 SPELL_AURA_MOD_DRUNK
&AuraEffect::HandleAuraModIncreaseSpeed, //305 SPELL_AURA_MOD_MINIMUM_SPEED
&AuraEffect::HandleNULL, //306 0 spells in 3.3.5
&AuraEffect::HandleNULL, //307 0 spells in 3.3.5
&AuraEffect::HandleNoImmediateEffect, //308 SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER implemented in Unit::isSpellCrit, ObjectAccessor::GetUnitCriticalChance
&AuraEffect::HandleNULL, //309 0 spells in 3.3.5
&AuraEffect::HandleNoImmediateEffect, //310 SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE implemented in Spell::CalculateDamageDone
&AuraEffect::HandleNULL, //311 0 spells in 3.3.5
&AuraEffect::HandleNULL, //312 0 spells in 3.3.5
&AuraEffect::HandleNULL, //313 0 spells in 3.3.5
&AuraEffect::HandlePreventResurrection, //314 SPELL_AURA_PREVENT_RESURRECTION todo
&AuraEffect::HandleNoImmediateEffect, //315 SPELL_AURA_UNDERWATER_WALKING todo
&AuraEffect::HandleNoImmediateEffect, //316 SPELL_AURA_PERIODIC_HASTE implemented in AuraEffect::CalculatePeriodic
};
AuraEffect::AuraEffect(Aura* base, uint8 effIndex, int32 *baseAmount, Unit* caster):
m_base(base), m_spellInfo(base->GetSpellInfo()),
m_baseAmount(baseAmount ? *baseAmount : m_spellInfo->Effects[effIndex].BasePoints),
m_spellmod(NULL), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex),
m_canBeRecalculated(true), m_isPeriodic(false), m_critChance(0), m_oldAmount(0), m_isAuraEnabled(true), m_channelData(NULL)
{
CalculatePeriodic(caster, true, false);
CalculatePeriodicData();
m_amount = CalculateAmount(caster);
m_casterLevel = caster ? caster->getLevel() : 0;
m_applyResilience = caster ? caster->CanApplyResilience() : false;
m_auraGroup = sSpellMgr->GetSpellGroup(GetId());
CalculateSpellMod();
// Xinef: channel data structure
if (caster)
if (Spell* spell = caster->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
m_channelData = new ChannelTargetData(caster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT), spell->m_targets.HasDst() ? spell->m_targets.GetDst() : NULL);
}
AuraEffect::~AuraEffect()
{
delete m_spellmod;
delete m_channelData;
}
void AuraEffect::GetTargetList(std::list<Unit*> & targetList) const
{
Aura::ApplicationMap const & targetMap = GetBase()->GetApplicationMap();
// remove all targets which were not added to new list - they no longer deserve area aura
for (Aura::ApplicationMap::const_iterator appIter = targetMap.begin(); appIter != targetMap.end(); ++appIter)
{
if (appIter->second->HasEffect(GetEffIndex()))
targetList.push_back(appIter->second->GetTarget());
}
}
void AuraEffect::GetApplicationList(std::list<AuraApplication*> & applicationList) const
{
Aura::ApplicationMap const & targetMap = GetBase()->GetApplicationMap();
for (Aura::ApplicationMap::const_iterator appIter = targetMap.begin(); appIter != targetMap.end(); ++appIter)
{
if (appIter->second->HasEffect(GetEffIndex()))
applicationList.push_back(appIter->second);
}
}
int32 AuraEffect::CalculateAmount(Unit* caster)
{
int32 amount;
// default amount calculation
amount = m_spellInfo->Effects[m_effIndex].CalcValue(caster, &m_baseAmount, NULL);
// check item enchant aura cast
if (!amount && caster)
if (uint64 itemGUID = GetBase()->GetCastItemGUID())
if (Player* playerCaster = caster->ToPlayer())
if (Item* castItem = playerCaster->GetItemByGuid(itemGUID))
if (castItem->GetItemSuffixFactor())
{
ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(castItem->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; k++)
{
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(item_rand_suffix->enchant_id[k]);
if (pEnchant)
{
for (int t = 0; t < MAX_ITEM_ENCHANTMENT_EFFECTS; t++)
if (pEnchant->spellid[t] == m_spellInfo->Id)
{
amount = uint32((item_rand_suffix->prefix[k]*castItem->GetItemSuffixFactor()) / 10000);
break;
}
}
if (amount)
break;
}
}
}
// custom amount calculations go here
// xinef: normal auras
switch (GetAuraType())
{
// crowd control auras
case SPELL_AURA_MOD_CONFUSE:
case SPELL_AURA_MOD_FEAR:
case SPELL_AURA_MOD_STUN:
case SPELL_AURA_MOD_ROOT:
case SPELL_AURA_TRANSFORM:
m_canBeRecalculated = false;
if (!m_spellInfo->ProcFlags || m_spellInfo->HasAura(SPELL_AURA_PROC_TRIGGER_SPELL)) // xinef: skip auras with proctriggerspell, they must have procflags...
break;
amount = int32(GetBase()->GetUnitOwner()->CountPctFromMaxHealth(10));
if (caster)
{
// Glyphs increasing damage cap
Unit::AuraEffectList const& overrideClassScripts = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (Unit::AuraEffectList::const_iterator itr = overrideClassScripts.begin(); itr != overrideClassScripts.end(); ++itr)
{
if ((*itr)->IsAffectedOnSpell(m_spellInfo))
{
// Glyph of Fear, Glyph of Frost nova and similar auras
if ((*itr)->GetMiscValue() == 7801)
{
AddPct(amount, (*itr)->GetAmount());
break;
}
}
}
}
break;
case SPELL_AURA_SCHOOL_ABSORB:
case SPELL_AURA_MANA_SHIELD:
m_canBeRecalculated = false;
break;
case SPELL_AURA_MOD_BASE_RESISTANCE_PCT:
if (!caster)
break;
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID)
{
if (GetId() == 1178 && caster->HasAura(5229) && !caster->HasAura(70726)) // Feral t10 4p
amount -= 48; // percentage
else if (GetId() == 9635 && caster->HasAura(5229) && !caster->HasAura(70726)) // Feral t10 4p
amount -= 57; // percentage
}
break;
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE:
// Titan's Grip
if (!caster)
break;
if (GetId() == 49152 && caster->ToPlayer())
{
Item *item1 = caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK);
Item *item2 = caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK);
if (item1 && item2 && (item1->GetTemplate()->InventoryType == INVTYPE_2HWEAPON || item2->GetTemplate()->InventoryType == INVTYPE_2HWEAPON))
amount = -10;
else
amount = 0;
}
break;
default:
break;
}
// xinef: save base amount, before calculating sp etc. Used for Unit::CastDelayedSpellWithPeriodicAmount
SetOldAmount(amount*GetBase()->GetStackAmount());
GetBase()->CallScriptEffectCalcAmountHandlers(this, amount, m_canBeRecalculated);
// Xinef: Periodic auras
if (caster)
switch (GetAuraType())
{
case SPELL_AURA_PERIODIC_DAMAGE:
// xinef: save caster depending auras, always pass 1 as stack amount, effect will be multiplicated at the end of the function by correct value!
if (GetBase()->GetType() == UNIT_AURA_TYPE)
amount = caster->SpellDamageBonusDone(GetBase()->GetUnitOwner(), GetSpellInfo(), amount, DOT, GetPctMods(), 1);
break;
case SPELL_AURA_PERIODIC_LEECH:
// xinef: save caster depending auras, always pass 1 as stack amount, effect will be multiplicated at the end of the function by correct value!
if (GetBase()->GetType() == UNIT_AURA_TYPE)
amount = caster->SpellDamageBonusDone(GetBase()->GetUnitOwner(), GetSpellInfo(), amount, DOT, GetPctMods(), 1);
break;
case SPELL_AURA_PERIODIC_HEAL:
if (GetBase()->GetType() == UNIT_AURA_TYPE)
amount = caster->SpellHealingBonusDone(GetBase()->GetUnitOwner(), GetSpellInfo(), amount, DOT, GetPctMods(), 1);
break;
case SPELL_AURA_DAMAGE_SHIELD:
if (GetBase()->GetType() == UNIT_AURA_TYPE)
amount = caster->SpellDamageBonusDone(GetBase()->GetUnitOwner(), GetSpellInfo(), amount, SPELL_DIRECT_DAMAGE, 0.0f, 1);
break;
}
amount *= GetBase()->GetStackAmount();
return amount;
}
void AuraEffect::CalculatePeriodicData()
{
// xinef: save caster depending auras with pct mods
if (GetBase()->GetType() == UNIT_AURA_TYPE && GetCaster())
{
if (m_spellInfo->HasAura(SPELL_AURA_PERIODIC_HEAL))
m_pctMods = GetCaster()->SpellPctHealingModsDone(GetBase()->GetUnitOwner(), GetSpellInfo(), DOT);
else if (m_spellInfo->HasAura(SPELL_AURA_PERIODIC_DAMAGE) || m_spellInfo->HasAura(SPELL_AURA_PERIODIC_LEECH))
m_pctMods = GetCaster()->SpellPctDamageModsDone(GetBase()->GetUnitOwner(), GetSpellInfo(), DOT);
}
if (GetCaster())
SetCritChance(CalcPeriodicCritChance(GetCaster(), (GetBase()->GetType() == UNIT_AURA_TYPE ? GetBase()->GetUnitOwner() : NULL)));
}
void AuraEffect::CalculatePeriodic(Unit* caster, bool create, bool load)
{
m_amplitude = m_spellInfo->Effects[m_effIndex].Amplitude;
// prepare periodics
switch (GetAuraType())
{
case SPELL_AURA_OBS_MOD_POWER:
// 3 spells have no amplitude set
if (!m_amplitude)
m_amplitude = 1 * IN_MILLISECONDS;
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
case SPELL_AURA_PERIODIC_ENERGIZE:
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
case SPELL_AURA_PERIODIC_MANA_LEECH:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
case SPELL_AURA_POWER_BURN:
case SPELL_AURA_PERIODIC_DUMMY:
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
m_isPeriodic = true;
break;
default:
break;
}
GetBase()->CallScriptEffectCalcPeriodicHandlers(this, m_isPeriodic, m_amplitude);
if (!m_isPeriodic)
return;
// Xinef: fix broken data in dbc
if (m_amplitude <= 0)
m_amplitude = 1000;
Player* modOwner = caster ? caster->GetSpellModOwner() : NULL;
// Apply casting time mods
if (m_amplitude)
{
// Apply periodic time mod
if (modOwner)
modOwner->ApplySpellMod(GetId(), SPELLMOD_ACTIVATION_TIME, m_amplitude);
if (caster)
{
if (caster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, m_spellInfo) || m_spellInfo->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION))
m_amplitude = int32(m_amplitude * caster->GetFloatValue(UNIT_MOD_CAST_SPEED));
}
}
if (load) // aura loaded from db
{
m_tickNumber = m_amplitude ? GetBase()->GetDuration() / m_amplitude : 0;
m_periodicTimer = m_amplitude ? GetBase()->GetDuration() % m_amplitude : 0;
if (m_spellInfo->HasAttribute(SPELL_ATTR5_START_PERIODIC_AT_APPLY))
++m_tickNumber;
}
else // aura just created or reapplied
{
m_tickNumber = 0;
// reset periodic timer on aura create or on reapply when aura isn't dot
// possibly we should not reset periodic timers only when aura is triggered by proc
// or maybe there's a spell attribute somewhere
bool resetPeriodicTimer = create
|| ((GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE) && (GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE_PERCENT));
if (resetPeriodicTimer)
{
m_periodicTimer = 0;
// Start periodic on next tick or at aura apply
if (m_amplitude)
{
if (!GetSpellInfo()->HasAttribute(SPELL_ATTR5_START_PERIODIC_AT_APPLY))
m_periodicTimer += m_amplitude;
else if (caster && caster->IsTotem()) // for totems only ;d
{
m_periodicTimer = 100; // make it ALMOST instant
if (!GetBase()->IsPassive())
GetBase()->SetDuration(GetBase()->GetDuration()+100);
}
}
}
}
}
void AuraEffect::CalculateSpellMod()
{
switch (GetAuraType())
{
case SPELL_AURA_ADD_FLAT_MODIFIER:
case SPELL_AURA_ADD_PCT_MODIFIER:
if (!m_spellmod)
{
m_spellmod = new SpellModifier(GetBase());
m_spellmod->op = SpellModOp(GetMiscValue());
ASSERT(m_spellmod->op < MAX_SPELLMOD);
m_spellmod->type = SpellModType(GetAuraType()); // SpellModType value == spell aura types
m_spellmod->spellId = GetId();
m_spellmod->mask = GetSpellInfo()->Effects[GetEffIndex()].SpellClassMask;
m_spellmod->charges = GetBase()->GetCharges();
}
m_spellmod->value = GetAmount();
break;
default:
break;
}
GetBase()->CallScriptEffectCalcSpellModHandlers(this, m_spellmod);
}
void AuraEffect::ChangeAmount(int32 newAmount, bool mark, bool onStackOrReapply)
{
// Reapply if amount change
uint8 handleMask = 0;
if (newAmount != GetAmount())
handleMask |= AURA_EFFECT_HANDLE_CHANGE_AMOUNT;
if (onStackOrReapply)
handleMask |= AURA_EFFECT_HANDLE_REAPPLY;
if (!handleMask)
return;
std::list<AuraApplication*> effectApplications;
GetApplicationList(effectApplications);
for (std::list<AuraApplication*>::const_iterator apptItr = effectApplications.begin(); apptItr != effectApplications.end(); ++apptItr)
if ((*apptItr)->HasEffect(GetEffIndex()))
HandleEffect(*apptItr, handleMask, false);
if (handleMask & AURA_EFFECT_HANDLE_CHANGE_AMOUNT)
{
if (!mark)
m_amount = newAmount;
else
SetAmount(newAmount);
CalculateSpellMod();
}
for (std::list<AuraApplication*>::const_iterator apptItr = effectApplications.begin(); apptItr != effectApplications.end(); ++apptItr)
if ((*apptItr)->HasEffect(GetEffIndex()))
HandleEffect(*apptItr, handleMask, true);
}
void AuraEffect::HandleEffect(AuraApplication * aurApp, uint8 mode, bool apply)
{
// check if call is correct, we really don't want using bitmasks here (with 1 exception)
ASSERT(mode == AURA_EFFECT_HANDLE_REAL
|| mode == AURA_EFFECT_HANDLE_SEND_FOR_CLIENT
|| mode == AURA_EFFECT_HANDLE_CHANGE_AMOUNT
|| mode == AURA_EFFECT_HANDLE_STAT
|| mode == AURA_EFFECT_HANDLE_SKILL
|| mode == AURA_EFFECT_HANDLE_REAPPLY
|| mode == (AURA_EFFECT_HANDLE_CHANGE_AMOUNT | AURA_EFFECT_HANDLE_REAPPLY));
// register/unregister effect in lists in case of real AuraEffect apply/remove
// registration/unregistration is done always before real effect handling (some effect handlers code is depending on this)
if (mode & AURA_EFFECT_HANDLE_REAL)
aurApp->GetTarget()->_RegisterAuraEffect(this, apply);
// xinef: stacking system, force return if effect is disabled, prevents double apply / unapply
// xinef: placed here so above line can unregister effect from the list
// xinef: this condition works under assumption that effect handlers performs ALL necessery action with CHANGE_AMOUNT mode
// xinef: as far as i've checked, all grouped spells meet this condition
if (!aurApp->IsActive(GetEffIndex()))
return;
// real aura apply/remove, handle modifier
if (mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK)
ApplySpellMod(aurApp->GetTarget(), apply);
// call scripts helping/replacing effect handlers
bool prevented = false;
if (apply)
prevented = GetBase()->CallScriptEffectApplyHandlers(this, const_cast<AuraApplication const*>(aurApp), (AuraEffectHandleModes)mode);
else
prevented = GetBase()->CallScriptEffectRemoveHandlers(this, const_cast<AuraApplication const*>(aurApp), (AuraEffectHandleModes)mode);
// check if script events have removed the aura or if default effect prevention was requested
if ((apply && aurApp->GetRemoveMode()) || prevented)
return;
(*this.*AuraEffectHandler [GetAuraType()])(aurApp, mode, apply);
// check if script events have removed the aura or if default effect prevention was requested
if (apply && aurApp->GetRemoveMode())
return;
// call scripts triggering additional events after apply/remove
if (apply)
GetBase()->CallScriptAfterEffectApplyHandlers(this, aurApp, (AuraEffectHandleModes)mode);
else
GetBase()->CallScriptAfterEffectRemoveHandlers(this, aurApp, (AuraEffectHandleModes)mode);
}
void AuraEffect::HandleEffect(Unit* target, uint8 mode, bool apply)
{
AuraApplication* aurApp = GetBase()->GetApplicationOfTarget(target->GetGUID());
ASSERT(aurApp);
HandleEffect(aurApp, mode, apply);
}
void AuraEffect::ApplySpellMod(Unit* target, bool apply)
{
if (!m_spellmod || target->GetTypeId() != TYPEID_PLAYER)
return;
target->ToPlayer()->AddSpellMod(m_spellmod, apply);
// Auras with charges do not mod amount of passive auras
if (GetBase()->IsUsingCharges())
return;
// reapply some passive spells after add/remove related spellmods
// Warning: it is a dead loop if 2 auras each other amount-shouldn't happen
switch (GetMiscValue())
{
case SPELLMOD_ALL_EFFECTS:
case SPELLMOD_EFFECT1:
case SPELLMOD_EFFECT2:
case SPELLMOD_EFFECT3:
{
uint64 guid = target->GetGUID();
Unit::AuraApplicationMap & auras = target->GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator iter = auras.begin(); iter != auras.end(); ++iter)
{
Aura* aura = iter->second->GetBase();
// only passive and permament auras-active auras should have amount set on spellcast and not be affected
// if aura is casted by others, it will not be affected
if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == guid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod))
{
if (GetMiscValue() == SPELLMOD_ALL_EFFECTS)
{
for (uint8 i = 0; i<MAX_SPELL_EFFECTS; ++i)
{
if (AuraEffect* aurEff = aura->GetEffect(i))
aurEff->RecalculateAmount();
}
}
else if (GetMiscValue() == SPELLMOD_EFFECT1)
{
if (AuraEffect* aurEff = aura->GetEffect(0))
aurEff->RecalculateAmount();
}
else if (GetMiscValue() == SPELLMOD_EFFECT2)
{
if (AuraEffect* aurEff = aura->GetEffect(1))
aurEff->RecalculateAmount();
}
else //if (modOp == SPELLMOD_EFFECT3)
{
if (AuraEffect* aurEff = aura->GetEffect(2))
aurEff->RecalculateAmount();
}
}
}
Pet* pet = target->ToPlayer()->GetPet();
if (!pet)
break;
uint64 petguid = pet->GetGUID();
Unit::AuraApplicationMap & petauras = pet->GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator iter = petauras.begin(); iter != petauras.end(); ++iter)
{
Aura* aura = iter->second->GetBase();
// only passive auras-active auras should have amount set on spellcast and not be affected
// if aura is casted by others, it will not be affected
if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == petguid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod))
{
if (GetMiscValue() == SPELLMOD_ALL_EFFECTS)
{
for (uint8 i = 0; i<MAX_SPELL_EFFECTS; ++i)
{
if (AuraEffect* aurEff = aura->GetEffect(i))
aurEff->RecalculateAmount();
}
}
else if (GetMiscValue() == SPELLMOD_EFFECT1)
{
if (AuraEffect* aurEff = aura->GetEffect(0))
aurEff->RecalculateAmount();
}
else if (GetMiscValue() == SPELLMOD_EFFECT2)
{
if (AuraEffect* aurEff = aura->GetEffect(1))
aurEff->RecalculateAmount();
}
else //if (modOp == SPELLMOD_EFFECT3)
{
if (AuraEffect* aurEff = aura->GetEffect(2))
aurEff->RecalculateAmount();
}
}
}
}
default:
break;
}
}
void AuraEffect::Update(uint32 diff, Unit* caster)
{
if (m_isPeriodic && (GetBase()->GetDuration() >=0 || GetBase()->IsPassive() || GetBase()->IsPermanent()))
{
m_periodicTimer -= int32(diff);
while (m_periodicTimer <= 0)
{
++m_tickNumber;
// update before tick (aura can be removed in TriggerSpell or PeriodicTick calls)
m_periodicTimer += m_amplitude;
UpdatePeriodic(caster);
std::list<AuraApplication*> effectApplications;
GetApplicationList(effectApplications);
// tick on targets of effects
for (std::list<AuraApplication*>::const_iterator apptItr = effectApplications.begin(); apptItr != effectApplications.end(); ++apptItr)
if ((*apptItr)->HasEffect(GetEffIndex()))
PeriodicTick(*apptItr, caster);
}
}
}
void AuraEffect::UpdatePeriodic(Unit* caster)
{
switch (GetAuraType())
{
case SPELL_AURA_PERIODIC_DUMMY:
switch (GetSpellInfo()->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (GetId())
{
// Drink
case 430:
case 431:
case 432:
case 1133:
case 1135:
case 1137:
case 10250:
case 22734:
case 27089:
case 34291:
case 43182:
case 43183:
case 46755:
case 49472: // Drink Coffee
case 57073:
case 61830:
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
// Get SPELL_AURA_MOD_POWER_REGEN aura from spell
if (AuraEffect* aurEff = GetBase()->GetEffect(0))
{
if (aurEff->GetAuraType() != SPELL_AURA_MOD_POWER_REGEN)
{
m_isPeriodic = false;
sLog->outError("Aura %d structure has been changed - first aura is no longer SPELL_AURA_MOD_POWER_REGEN", GetId());
}
else
{
aurEff->ChangeAmount(GetAmount());
m_isPeriodic = false;
}
}
break;
case 58549: // Tenacity
case 59911: // Tenacity (vehicle)
GetBase()->RefreshDuration();
break;
case 66823: case 67618: case 67619: case 67620: // Paralytic Toxin
// Get 0 effect aura
if (AuraEffect* slow = GetBase()->GetEffect(0))
{
int32 newAmount = slow->GetAmount() - 10;
if (newAmount < -100)
newAmount = -100;
slow->ChangeAmount(newAmount);
}
break;
case 66020:
// Get 0 effect aura
if (AuraEffect *slow = GetBase()->GetEffect(0))
{
int32 newAmount = slow->GetAmount() + GetAmount();
if (newAmount > 0)
newAmount = 0;
slow->ChangeAmount(newAmount);
}
break;
default:
break;
}
break;
default:
break;
}
default:
break;
}
GetBase()->CallScriptEffectUpdatePeriodicHandlers(this);
}
float AuraEffect::CalcPeriodicCritChance(Unit const* caster, Unit const* target) const
{
float critChance = 0.0f;
if (caster)
{
if (Player* modOwner = caster->GetSpellModOwner())
{
Unit::AuraEffectList const& mPeriodicCritAuras = modOwner->GetAuraEffectsByType(SPELL_AURA_ABILITY_PERIODIC_CRIT);
for (Unit::AuraEffectList::const_iterator itr = mPeriodicCritAuras.begin(); itr != mPeriodicCritAuras.end(); ++itr)
{
if ((*itr)->IsAffectedOnSpell(GetSpellInfo()))
{
critChance = modOwner->SpellDoneCritChance(NULL, GetSpellInfo(), GetSpellInfo()->GetSchoolMask(), (GetSpellInfo()->DmgClass == SPELL_DAMAGE_CLASS_RANGED ? RANGED_ATTACK : BASE_ATTACK), true);
break;
}
}
switch(GetSpellInfo()->SpellFamilyName)
{
// Rupture - since 3.3.3 can crit
case SPELLFAMILY_ROGUE:
if (GetSpellInfo()->SpellFamilyFlags[0] & 0x100000)
critChance = modOwner->SpellDoneCritChance(NULL, GetSpellInfo(), GetSpellInfo()->GetSchoolMask(), BASE_ATTACK, true);
break;
}
}
}
if (target && critChance > 0.0f)
critChance = target->SpellTakenCritChance(caster, GetSpellInfo(), GetSpellInfo()->GetSchoolMask(), critChance, BASE_ATTACK, true);
return std::max(0.0f, critChance);
}
bool AuraEffect::IsAffectedOnSpell(SpellInfo const* spell) const
{
if (!spell)
return false;
// Check family name
if (spell->SpellFamilyName != m_spellInfo->SpellFamilyName)
return false;
// Check EffectClassMask
if (m_spellInfo->Effects[m_effIndex].SpellClassMask & spell->SpellFamilyFlags)
return true;
return false;
}
void AuraEffect::SendTickImmune(Unit* target, Unit* caster) const
{
if (caster)
caster->SendSpellDamageImmune(target, m_spellInfo->Id);
}
void AuraEffect::PeriodicTick(AuraApplication * aurApp, Unit* caster) const
{
bool prevented = GetBase()->CallScriptEffectPeriodicHandlers(this, aurApp);
if (prevented)
return;
Unit* target = aurApp->GetTarget();
switch (GetAuraType())
{
case SPELL_AURA_PERIODIC_DUMMY:
HandlePeriodicDummyAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
HandlePeriodicTriggerSpellAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
HandlePeriodicTriggerSpellWithValueAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
HandlePeriodicDamageAurasTick(target, caster);
break;
case SPELL_AURA_PERIODIC_LEECH:
HandlePeriodicHealthLeechAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
HandlePeriodicHealthFunnelAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
HandlePeriodicHealAurasTick(target, caster);
break;
case SPELL_AURA_PERIODIC_MANA_LEECH:
HandlePeriodicManaLeechAuraTick(target, caster);
break;
case SPELL_AURA_OBS_MOD_POWER:
HandleObsModPowerAuraTick(target, caster);
break;
case SPELL_AURA_PERIODIC_ENERGIZE:
HandlePeriodicEnergizeAuraTick(target, caster);
break;
case SPELL_AURA_POWER_BURN:
HandlePeriodicPowerBurnAuraTick(target, caster);
break;
default:
break;
}
}
void AuraEffect::HandleProc(AuraApplication* aurApp, ProcEventInfo& eventInfo)
{
bool prevented = GetBase()->CallScriptEffectProcHandlers(this, aurApp, eventInfo);
if (prevented)
return;
switch (GetAuraType())
{
case SPELL_AURA_PROC_TRIGGER_SPELL:
HandleProcTriggerSpellAuraProc(aurApp, eventInfo);
break;
case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
HandleProcTriggerSpellWithValueAuraProc(aurApp, eventInfo);
break;
case SPELL_AURA_PROC_TRIGGER_DAMAGE:
HandleProcTriggerDamageAuraProc(aurApp, eventInfo);
break;
case SPELL_AURA_RAID_PROC_FROM_CHARGE:
HandleRaidProcFromChargeAuraProc(aurApp, eventInfo);
break;
case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE:
HandleRaidProcFromChargeWithValueAuraProc(aurApp, eventInfo);
break;
default:
break;
}
GetBase()->CallScriptAfterEffectProcHandlers(this, aurApp, eventInfo);
}
void AuraEffect::CleanupTriggeredSpells(Unit* target)
{
uint32 tSpellId = m_spellInfo->Effects[GetEffIndex()].TriggerSpell;
if (!tSpellId)
return;
SpellInfo const* tProto = sSpellMgr->GetSpellInfo(tSpellId);
if (!tProto)
return;
if (tProto->GetDuration() != -1)
return;
// needed for spell 43680, maybe others
// TODO: is there a spell flag, which can solve this in a more sophisticated way?
if (m_spellInfo->Effects[GetEffIndex()].ApplyAuraName == SPELL_AURA_PERIODIC_TRIGGER_SPELL &&
uint32(m_spellInfo->GetDuration()) == m_spellInfo->Effects[GetEffIndex()].Amplitude)
return;
target->RemoveAurasDueToSpell(tSpellId, GetCasterGUID());
}
void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const
{
uint32 spellId = 0;
uint32 spellId2 = 0;
//uint32 spellId3 = 0;
uint32 HotWSpellId = 0;
switch (GetMiscValue())
{
case FORM_CAT:
spellId = 3025;
HotWSpellId = 24900;
break;
case FORM_TREE:
spellId = 34123;
break;
case FORM_TRAVEL:
spellId = 5419;
break;
case FORM_AQUA:
spellId = 5421;
break;
case FORM_BEAR:
spellId = 1178;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_DIREBEAR:
spellId = 9635;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_BATTLESTANCE:
spellId = 21156;
break;
case FORM_DEFENSIVESTANCE:
spellId = 7376;
break;
case FORM_BERSERKERSTANCE:
spellId = 7381;
break;
case FORM_MOONKIN:
spellId = 24905;
spellId2 = 69366;
break;
case FORM_FLIGHT:
spellId = 33948;
spellId2 = 34764;
break;
case FORM_FLIGHT_EPIC:
spellId = 40122;
spellId2 = 40121;
break;
case FORM_METAMORPHOSIS:
spellId = 54817;
spellId2 = 54879;
break;
case FORM_SPIRITOFREDEMPTION:
spellId = 27792;
spellId2 = 27795; // must be second, this important at aura remove to prevent to early iterator invalidation.
break;
case FORM_SHADOW:
spellId = 49868;
spellId2 = 71167;
break;
case FORM_GHOSTWOLF:
spellId = 67116;
break;
case FORM_GHOUL:
case FORM_AMBIENT:
case FORM_STEALTH:
case FORM_CREATURECAT:
case FORM_CREATUREBEAR:
break;
default:
break;
}
Player* player = target->ToPlayer();
if (apply)
{
// Remove cooldown of spells triggered on stance change - they may share cooldown with stance spell
if (spellId)
{
if (player)
player->RemoveSpellCooldown(spellId);
target->CastSpell(target, spellId, true, NULL, this, target->GetGUID());
}
if (spellId2)
{
if (player)
player->RemoveSpellCooldown(spellId2);
target->CastSpell(target, spellId2, true, NULL, this, target->GetGUID());
}
if (player)
{
const PlayerSpellMap& sp_list = player->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(player->GetActiveSpec()))
continue;
if (itr->first == spellId || itr->first == spellId2)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE)))
continue;
if (spellInfo->Stances & (1<<(GetMiscValue()-1)))
target->CastSpell(target, itr->first, true, NULL, this, target->GetGUID());
}
// xinef: talent stance auras are not on m_spells map, so iterate talents
const PlayerTalentMap& tl_list = player->GetTalentMap();
for (PlayerTalentMap::const_iterator itr = tl_list.begin(); itr != tl_list.end(); ++itr)
{
if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(player->GetActiveSpec()))
continue;
if (itr->first == spellId || itr->first == spellId2)
continue;
// Xinef: skip talents with effect learn spell
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE)) || spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL))
continue;
if (spellInfo->Stances & (1<<(GetMiscValue()-1)))
target->CastSpell(target, itr->first, true, NULL, this, target->GetGUID());
}
// Leader of the Pack
if (player->HasTalent(17007, player->GetActiveSpec()))
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(24932);
if (spellInfo && spellInfo->Stances & (1<<(GetMiscValue()-1)))
target->CastSpell(target, 24932, true, NULL, this, target->GetGUID());
}
// Improved Barkskin - apply/remove armor bonus due to shapeshift
if (player->HasTalent(63410, player->GetActiveSpec()) || player->HasTalent(63411, player->GetActiveSpec()))
{
target->RemoveAurasDueToSpell(66530);
if (GetMiscValue() == FORM_TRAVEL || GetMiscValue() == FORM_NONE) // "while in Travel Form or while not shapeshifted"
target->CastSpell(target, 66530, true);
}
// Heart of the Wild
if (HotWSpellId)
{ // hacky, but the only way as spell family is not SPELLFAMILY_DRUID
Unit::AuraEffectList const& mModTotalStatPct = target->GetAuraEffectsByType(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE);
for (Unit::AuraEffectList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i)
{
// Heart of the Wild
if ((*i)->GetSpellInfo()->SpellIconID == 240 && (*i)->GetMiscValue() == STAT_INTELLECT)
{
int32 HotWMod = (*i)->GetAmount() / 2; // For each 2% Intelligence, you get 1% stamina and 1% attack power.
target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this, target->GetGUID());
break;
}
}
}
switch (GetMiscValue())
{
case FORM_CAT:
// Savage Roar
if (target->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_DRUID, 0, 0x10000000, 0))
target->CastSpell(target, 62071, true);
// Nurturing Instinct
if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT, SPELLFAMILY_DRUID, 2254, 0))
{
uint32 spellId3 = 0;
switch (aurEff->GetId())
{
case 33872:
spellId3 = 47179;
break;
case 33873:
spellId3 = 47180;
break;
}
target->CastSpell(target, spellId3, true, NULL, this, target->GetGUID());
}
// Master Shapeshifter - Cat
if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0))
{
int32 bp = aurEff->GetAmount();
target->CastCustomSpell(target, 48420, &bp, NULL, NULL, true);
}
break;
case FORM_DIREBEAR:
case FORM_BEAR:
// Master Shapeshifter - Bear
if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0))
{
int32 bp = aurEff->GetAmount();
target->CastCustomSpell(target, 48418, &bp, NULL, NULL, true);
}
// Survival of the Fittest
if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DRUID, 961, 0))
{
int32 bp = aurEff->GetSpellInfo()->Effects[EFFECT_2].CalcValue();
target->CastCustomSpell(target, 62069, &bp, NULL, NULL, true, 0, this, target->GetGUID());
}
break;
case FORM_MOONKIN:
// Master Shapeshifter - Moonkin
if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0))
{
int32 bp = aurEff->GetAmount();
target->CastCustomSpell(target, 48421, &bp, NULL, NULL, true);
}
break;
// Master Shapeshifter - Tree of Life
case FORM_TREE:
if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0))
{
int32 bp = aurEff->GetAmount();
target->CastCustomSpell(target, 48422, &bp, NULL, NULL, true);
}
break;
}
}
}
else
{
if (spellId)
target->RemoveOwnedAura(spellId);
if (spellId2)
target->RemoveOwnedAura(spellId2);
// Improved Barkskin - apply/remove armor bonus due to shapeshift
if (player)
{
if (player->HasTalent(63410, player->GetActiveSpec()) || player->HasTalent(63411, player->GetActiveSpec()))
{
target->RemoveAurasDueToSpell(66530);
target->CastSpell(target, 66530, true);
}
}
const Unit::AuraEffectList& shapeshifts = target->GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT);
AuraEffect* newAura = NULL;
// Iterate through all the shapeshift auras that the target has, if there is another aura with SPELL_AURA_MOD_SHAPESHIFT, then this aura is being removed due to that one being applied
for (Unit::AuraEffectList::const_iterator itr = shapeshifts.begin(); itr != shapeshifts.end(); ++itr)
{
if ((*itr) != this)
{
newAura = *itr;
break;
}
}
// Use the new aura to see on what stance the target will be
uint32 newStance = (1<<((newAura ? newAura->GetMiscValue() : 0)-1));
Unit::AuraApplicationMap& tAuras = target->GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
{
// If the stances are not compatible with the spell, remove it
// Xinef: Remove all passive auras, they will be added if needed
if (itr->second->GetBase()->IsRemovedOnShapeLost(target) && (!(itr->second->GetBase()->GetSpellInfo()->Stances & newStance) || itr->second->GetBase()->IsPassive()))
target->RemoveAura(itr);
else
++itr;
}
// Xinef: Remove autoattack spells
if (Spell* spell = target->GetCurrentSpell(CURRENT_MELEE_SPELL))
if (spell->GetSpellInfo()->CheckShapeshift(newAura ? newAura->GetMiscValue() : 0) != SPELL_CAST_OK)
spell->cancel(true);
}
}
/*********************************************************/
/*** AURA EFFECT HANDLERS ***/
/*********************************************************/
/**************************************/
/*** VISIBILITY & PHASES ***/
/**************************************/
void AuraEffect::HandleModInvisibilityDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
InvisibilityType type = InvisibilityType(GetMiscValue());
if (apply)
{
target->m_invisibilityDetect.AddFlag(type);
target->m_invisibilityDetect.AddValue(type, GetAmount());
}
else
{
if (!target->HasAuraType(SPELL_AURA_MOD_INVISIBILITY_DETECT))
target->m_invisibilityDetect.DelFlag(type);
target->m_invisibilityDetect.AddValue(type, -GetAmount());
}
// call functions which may have additional effects after chainging state of unit
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()));
}
void AuraEffect::HandleModInvisibility(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
InvisibilityType type = InvisibilityType(GetMiscValue());
if (apply)
{
// apply glow vision
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
target->m_invisibility.AddFlag(type);
target->m_invisibility.AddValue(type, GetAmount());
}
else
{
if (!target->HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
{
// if not have different invisibility auras.
// remove glow vision
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
target->m_invisibility.DelFlag(type);
}
else
{
bool found = false;
Unit::AuraEffectList const& invisAuras = target->GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
for (Unit::AuraEffectList::const_iterator i = invisAuras.begin(); i != invisAuras.end(); ++i)
{
if (GetMiscValue() == (*i)->GetMiscValue())
{
found = true;
break;
}
}
if (!found)
target->m_invisibility.DelFlag(type);
}
target->m_invisibility.AddValue(type, -GetAmount());
}
// call functions which may have additional effects after chainging state of unit
if (apply && (mode & AURA_EFFECT_HANDLE_REAL))
{
// drop flag at invisibiliy in bg
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
if (!apply && aurApp->GetRemoveMode() == AURA_REMOVE_BY_DEFAULT)
{
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()), true);
target->bRequestForcedVisibilityUpdate = false;
}
else
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()));
}
void AuraEffect::HandleModStealthDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
StealthType type = StealthType(GetMiscValue());
if (apply)
{
target->m_stealthDetect.AddFlag(type);
target->m_stealthDetect.AddValue(type, GetAmount());
}
else
{
if (!target->HasAuraType(SPELL_AURA_MOD_STEALTH_DETECT))
target->m_stealthDetect.DelFlag(type);
target->m_stealthDetect.AddValue(type, -GetAmount());
}
// call functions which may have additional effects after chainging state of unit
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()));
}
void AuraEffect::HandleModStealth(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
StealthType type = StealthType(GetMiscValue());
if (apply)
{
target->m_stealth.AddFlag(type);
target->m_stealth.AddValue(type, GetAmount());
target->SetStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH);
// interrupt autoshot
if (target->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL))
{
target->FinishSpell(CURRENT_AUTOREPEAT_SPELL);
target->ToPlayer()->SendAutoRepeatCancel(target);
}
}
else
{
target->m_stealth.AddValue(type, -GetAmount());
if (!target->HasAuraType(SPELL_AURA_MOD_STEALTH)) // if last SPELL_AURA_MOD_STEALTH
{
target->m_stealth.DelFlag(type);
target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH);
}
}
// call functions which may have additional effects after chainging state of unit
if (apply && (mode & AURA_EFFECT_HANDLE_REAL))
{
// drop flag at stealth in bg
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
if (!apply && aurApp->GetRemoveMode() == AURA_REMOVE_BY_DEFAULT)
{
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()), true);
target->bRequestForcedVisibilityUpdate = false;
}
else
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()));
}
void AuraEffect::HandleModStealthLevel(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
StealthType type = StealthType(GetMiscValue());
if (apply)
target->m_stealth.AddValue(type, GetAmount());
else
target->m_stealth.AddValue(type, -GetAmount());
// call functions which may have additional effects after chainging state of unit
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER || IS_PLAYER_GUID(target->GetOwnerGUID()));
}
void AuraEffect::HandleSpiritOfRedemption(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// prepare spirit state
if (apply)
{
// disable breath/etc timers
target->ToPlayer()->StopMirrorTimers();
// set stand state (expected in this form)
if (!target->IsStandState())
target->SetStandState(UNIT_STAND_STATE_STAND);
target->SetHealth(1);
}
// die at aura end
else if (target->IsAlive())
// call functions which may have additional effects after chainging state of unit
target->setDeathState(JUST_DIED);
// xinef: damage immunity spell, not needed because of 93 aura (adds non_attackable state)
// xinef: probably blizzard added it just in case in wotlk (id > 46000)
if (apply)
target->CastSpell(target, 62371, true);
else
target->RemoveAurasDueToSpell(62371);
}
void AuraEffect::HandleAuraGhost(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
{
target->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST);
target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST);
}
else
{
if (target->HasAuraType(SPELL_AURA_GHOST))
return;
target->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE);
target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE);
}
}
void AuraEffect::HandlePhase(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
// no-phase is also phase state so same code for apply and remove
uint32 newPhase = 0;
Unit::AuraEffectList const& phases = target->GetAuraEffectsByType(SPELL_AURA_PHASE);
if (!phases.empty())
for (Unit::AuraEffectList::const_iterator itr = phases.begin(); itr != phases.end(); ++itr)
newPhase |= (*itr)->GetMiscValue();
if (Player* player = target->ToPlayer())
{
if (!newPhase)
newPhase = PHASEMASK_NORMAL;
// GM-mode have mask 0xFFFFFFFF
if (player->IsGameMaster())
newPhase = 0xFFFFFFFF;
player->SetPhaseMask(newPhase, false);
player->GetSession()->SendSetPhaseShift(newPhase);
}
else
{
if (!newPhase)
{
newPhase = PHASEMASK_NORMAL;
if (Creature* creature = target->ToCreature())
if (CreatureData const* data = sObjectMgr->GetCreatureData(creature->GetDBTableGUIDLow()))
newPhase = data->phaseMask;
}
target->SetPhaseMask(newPhase, false);
}
// call functions which may have additional effects after chainging state of unit
// phase auras normally not expected at BG but anyway better check
if (apply)
{
// drop flag at invisibiliy in bg
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
// need triggering visibility update base at phase update of not GM invisible (other GMs anyway see in any phases)
if (target->IsVisible())
{
target->UpdateObjectVisibility(false);
target->m_last_notify_position.Relocate(-5000.0f, -5000.0f, -5000.0f);
}
}
/**********************/
/*** UNIT MODEL ***/
/**********************/
void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
uint32 modelid = 0;
Powers PowerType = POWER_MANA;
ShapeshiftForm form = ShapeshiftForm(GetMiscValue());
switch (form)
{
case FORM_CAT: // 0x01
case FORM_GHOUL: // 0x07
PowerType = POWER_ENERGY;
break;
case FORM_BEAR: // 0x05
case FORM_DIREBEAR: // 0x08
case FORM_BATTLESTANCE: // 0x11
case FORM_DEFENSIVESTANCE: // 0x12
case FORM_BERSERKERSTANCE: // 0x13
PowerType = POWER_RAGE;
break;
case FORM_TREE: // 0x02
case FORM_TRAVEL: // 0x03
case FORM_AQUA: // 0x04
case FORM_AMBIENT: // 0x06
case FORM_STEVES_GHOUL: // 0x09
case FORM_THARONJA_SKELETON: // 0x0A
case FORM_TEST_OF_STRENGTH: // 0x0B
case FORM_BLB_PLAYER: // 0x0C
case FORM_SHADOW_DANCE: // 0x0D
case FORM_CREATUREBEAR: // 0x0E
case FORM_CREATURECAT: // 0x0F
case FORM_GHOSTWOLF: // 0x10
case FORM_TEST: // 0x14
case FORM_ZOMBIE: // 0x15
case FORM_METAMORPHOSIS: // 0x16
case FORM_UNDEAD: // 0x19
case FORM_MASTER_ANGLER: // 0x1A
case FORM_FLIGHT_EPIC: // 0x1B
case FORM_SHADOW: // 0x1C
case FORM_FLIGHT: // 0x1D
case FORM_STEALTH: // 0x1E
case FORM_MOONKIN: // 0x1F
case FORM_SPIRITOFREDEMPTION: // 0x20
break;
default:
sLog->outError("Auras: Unknown Shapeshift Type: %u", GetMiscValue());
}
modelid = target->GetModelForForm(form);
if (apply)
{
// remove polymorph before changing display id to keep new display id
switch (form)
{
case FORM_CAT:
case FORM_TREE:
case FORM_TRAVEL:
case FORM_AQUA:
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_FLIGHT_EPIC:
case FORM_FLIGHT:
case FORM_MOONKIN:
{
// remove movement affects
target->RemoveAurasByShapeShift();
// and polymorphic affects
if (target->IsPolymorphed())
target->RemoveAurasDueToSpell(target->getTransForm());
break;
}
default:
break;
}
// remove other shapeshift before applying a new one
// xinef: rogue shouldnt be wrapped by this check (shadow dance vs stealth)
if (GetSpellInfo()->SpellFamilyName != SPELLFAMILY_ROGUE)
target->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT, 0, GetBase());
// stop handling the effect if it was removed by linked event
if (aurApp->GetRemoveMode())
return;
if (PowerType != POWER_MANA)
{
uint32 oldPower = target->GetPower(PowerType);
// reset power to default values only at power change
if (target->getPowerType() != PowerType)
target->setPowerType(PowerType);
switch (form)
{
case FORM_CAT:
case FORM_BEAR:
case FORM_DIREBEAR:
{
// get furor proc chance
uint32 FurorChance = 0;
if (AuraEffect const* dummy = target->GetDummyAuraEffect(SPELLFAMILY_DRUID, 238, 0))
FurorChance = std::max(dummy->GetAmount(), 0);
switch (GetMiscValue())
{
case FORM_CAT:
{
int32 basePoints = int32(std::min(oldPower, FurorChance));
target->SetPower(POWER_ENERGY, 0);
target->CastCustomSpell(target, 17099, &basePoints, NULL, NULL, true, NULL, this);
break;
}
case FORM_BEAR:
case FORM_DIREBEAR:
if (urand(0, 99) < FurorChance)
target->CastSpell(target, 17057, true);
break;
default:
{
uint32 newEnergy = std::min(target->GetPower(POWER_ENERGY), FurorChance);
target->SetPower(POWER_ENERGY, newEnergy);
break;
}
}
break;
}
default:
break;
}
}
// stop handling the effect if it was removed by linked event
if (aurApp->GetRemoveMode())
return;
target->SetShapeshiftForm(form);
// xinef: allow shapeshift to override model id if forced transform aura is not present!
if (modelid > 0)
{
bool allow = true;
if (target->getTransForm())
if (SpellInfo const* transformSpellInfo = sSpellMgr->GetSpellInfo(target->getTransForm()))
if (transformSpellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || !transformSpellInfo->IsPositive())
allow = false;
if (allow)
target->SetDisplayId(modelid);
}
}
else
{
// reset model id if no other auras present
// may happen when aura is applied on linked event on aura removal
if (!target->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
{
target->SetShapeshiftForm(FORM_NONE);
if (target->getClass() == CLASS_DRUID)
{
target->setPowerType(POWER_MANA);
// Remove movement impairing effects also when shifting out
target->RemoveAurasByShapeShift();
}
}
if (modelid > 0)
target->RestoreDisplayId();
switch (form)
{
// Nordrassil Harness - bonus
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_CAT:
if (AuraEffect* dummy = target->GetAuraEffect(37315, 0))
target->CastSpell(target, 37316, true, NULL, dummy);
break;
// Nordrassil Regalia - bonus
case FORM_MOONKIN:
if (AuraEffect* dummy = target->GetAuraEffect(37324, 0))
target->CastSpell(target, 37325, true, NULL, dummy);
break;
case FORM_BATTLESTANCE:
case FORM_DEFENSIVESTANCE:
case FORM_BERSERKERSTANCE:
{
uint32 Rage_val = 0;
// Defensive Tactics
if (form == FORM_DEFENSIVESTANCE)
{
if (AuraEffect const* aurEff = target->IsScriptOverriden(m_spellInfo, 831))
Rage_val += aurEff->GetAmount() * 10;
}
// Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch)
if (target->GetTypeId() == TYPEID_PLAYER)
{
// Stance mastery - trainer spell
PlayerSpellMap const& sp_list = target->ToPlayer()->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec()))
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139)
Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10;
}
// Tactical Mastery - talent
PlayerTalentMap const& tp_list = target->ToPlayer()->GetTalentMap();
for (PlayerTalentMap::const_iterator itr = tp_list.begin(); itr != tp_list.end(); ++itr)
{
if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec()))
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139)
Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10;
}
}
if (target->GetPower(POWER_RAGE) > Rage_val)
target->SetPower(POWER_RAGE, Rage_val);
break;
}
default:
break;
}
}
// adding/removing linked auras
// add/remove the shapeshift aura's boosts
HandleShapeshiftBoosts(target, apply);
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->InitDataForForm();
if (target->getClass() == CLASS_DRUID)
{
// Dash
if (AuraEffect* aurEff = target->GetAuraEffect(SPELL_AURA_MOD_INCREASE_SPEED, SPELLFAMILY_DRUID, 0, 0, 0x8))
aurEff->RecalculateAmount();
// Disarm handling
// If druid shifts while being disarmed we need to deal with that since forms aren't affected by disarm
// and also HandleAuraModDisarm is not triggered
if (!target->CanUseAttackType(BASE_ATTACK))
{
if (Item* pItem = target->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
{
target->ToPlayer()->_ApplyWeaponDamage(EQUIPMENT_SLOT_MAINHAND, pItem->GetTemplate(), NULL, apply);
}
}
}
// stop handling the effect if it was removed by linked event
if (apply && aurApp->GetRemoveMode())
return;
if (target->GetTypeId() == TYPEID_PLAYER)
{
SpellShapeshiftEntry const* shapeInfo = sSpellShapeshiftStore.LookupEntry(form);
// Learn spells for shapeshift form - no need to send action bars or add spells to spellbook
for (uint8 i = 0; i<MAX_SHAPESHIFT_SPELLS; ++i)
{
if (!shapeInfo->stanceSpell[i])
continue;
if (apply)
target->ToPlayer()->_addSpell(shapeInfo->stanceSpell[i], SPEC_MASK_ALL, true);
else
target->ToPlayer()->removeSpell(shapeInfo->stanceSpell[i], SPEC_MASK_ALL, true);
}
}
}
void AuraEffect::HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
// update active transform spell only when transform or shapeshift not set or not overwriting negative by positive case
if (GetSpellInfo()->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || !target->GetModelForForm(target->GetShapeshiftForm()) || !GetSpellInfo()->IsPositive())
{
// special case (spell specific functionality)
if (GetMiscValue() == 0)
{
switch (GetId())
{
// Orb of Deception
case 16739:
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
switch (target->getRace())
{
// Blood Elf
case RACE_BLOODELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 17829 : 17830);
break;
// Orc
case RACE_ORC:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10139 : 10140);
break;
// Troll
case RACE_TROLL:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10135 : 10134);
break;
// Tauren
case RACE_TAUREN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10136 : 10147);
break;
// Undead
case RACE_UNDEAD_PLAYER:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10146 : 10145);
break;
// Draenei
case RACE_DRAENEI:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 17827 : 17828);
break;
// Dwarf
case RACE_DWARF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10141 : 10142);
break;
// Gnome
case RACE_GNOME:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10148 : 10149);
break;
// Human
case RACE_HUMAN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10137 : 10138);
break;
// Night Elf
case RACE_NIGHTELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 10143 : 10144);
break;
default:
break;
}
break;
}
// Murloc costume
case 42365:
target->SetDisplayId(21723);
break;
// Dread Corsair
case 50517:
// Corsair Costume
case 51926:
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
switch (target->getRace())
{
// Blood Elf
case RACE_BLOODELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043);
break;
// Orc
case RACE_ORC:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050);
break;
// Troll
case RACE_TROLL:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052);
break;
// Tauren
case RACE_TAUREN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051);
break;
// Undead
case RACE_UNDEAD_PLAYER:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053);
break;
// Draenei
case RACE_DRAENEI:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044);
break;
// Dwarf
case RACE_DWARF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045);
break;
// Gnome
case RACE_GNOME:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046);
break;
// Human
case RACE_HUMAN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048);
break;
// Night Elf
case RACE_NIGHTELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049);
break;
default:
break;
}
break;
}
// Pygmy Oil
case 53806:
target->SetDisplayId(22512);
break;
// Honor the Dead
case 65386:
case 65495:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 29203 : 29204);
break;
// Darkspear Pride
case 75532:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 31737 : 31738);
break;
// Gnomeregan Pride
case 75531:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 31654 : 31655);
break;
default:
break;
}
}
else
{
CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(GetMiscValue());
if (!ci)
{
target->SetDisplayId(16358); // pig pink ^_^
sLog->outError("Auras: unknown creature id = %d (only need its modelid) From Spell Aura Transform in Spell ID = %d", GetMiscValue(), GetId());
}
else
{
uint32 model_id = 0;
if (uint32 modelid = ci->GetRandomValidModelId())
model_id = modelid; // Will use the default model here
// Polymorph (sheep)
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_MAGE && GetSpellInfo()->SpellIconID == 82 && GetSpellInfo()->SpellVisual[0] == 12978)
if (Unit* caster = GetCaster())
if (caster->HasAura(52648)) // Glyph of the Penguin
model_id = 26452;
target->SetDisplayId(model_id);
// Dragonmaw Illusion (set mount model also)
if (GetId() == 42016 && target->GetMountID() && !target->GetAuraEffectsByType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED).empty())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
}
}
// update active transform spell only when transform or shapeshift not set or not overwriting negative by positive case
SpellInfo const* transformSpellInfo = sSpellMgr->GetSpellInfo(target->getTransForm());
if (!transformSpellInfo || GetSpellInfo()->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || !GetSpellInfo()->IsPositive() || transformSpellInfo->IsPositive())
target->setTransForm(GetId());
// polymorph case
if ((mode & AURA_EFFECT_HANDLE_REAL) && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed())
{
// for players, start regeneration after 1s (in polymorph fast regeneration case)
// only if caster is Player (after patch 2.4.2)
if (IS_PLAYER_GUID(GetCasterGUID()))
target->ToPlayer()->setRegenTimerCount(1*IN_MILLISECONDS);
//dismount polymorphed target (after patch 2.4.2)
if (target->IsMounted())
target->RemoveAurasByType(SPELL_AURA_MOUNTED);
}
}
else
{
// HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true) will reapply it if need
if (target->getTransForm() == GetId())
target->setTransForm(0);
target->RestoreDisplayId();
// Dragonmaw Illusion (restore mount model)
if (GetId() == 42016 && target->GetMountID() == 16314)
{
if (!target->GetAuraEffectsByType(SPELL_AURA_MOUNTED).empty())
{
uint32 cr_id = target->GetAuraEffectsByType(SPELL_AURA_MOUNTED).front()->GetMiscValue();
if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(cr_id))
{
uint32 displayID = ObjectMgr::ChooseDisplayId(ci);
sObjectMgr->GetCreatureModelRandomGender(&displayID);
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, displayID);
}
}
}
}
}
void AuraEffect::HandleAuraModScale(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
float scale = target->GetFloatValue(OBJECT_FIELD_SCALE_X);
ApplyPercentModFloatVar(scale, float(GetAmount()), apply);
target->SetObjectScale(scale);
}
void AuraEffect::HandleAuraCloneCaster(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
Unit* caster = GetCaster();
if (!caster || caster == target)
return;
// What must be cloned? at least display and scale
target->SetDisplayId(caster->GetDisplayId());
//target->SetObjectScale(caster->GetFloatValue(OBJECT_FIELD_SCALE_X)); // we need retail info about how scaling is handled (aura maybe?)
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_MIRROR_IMAGE);
}
else
{
target->SetDisplayId(target->GetNativeDisplayId());
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_MIRROR_IMAGE);
}
}
/************************/
/*** FIGHT ***/
/************************/
void AuraEffect::HandleFeignDeath(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
{
/*
WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
data<<target->GetGUID();
data<<uint8(0);
target->SendMessageToSet(&data, true);
*/
UnitList targets;
Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(target, target, target->GetVisibilityRange()); // no VISIBILITY_COMPENSATION, distance is enough
Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(target, targets, u_check);
target->VisitNearbyObject(target->GetVisibilityRange(), searcher); // no VISIBILITY_COMPENSATION, distance is enough
for (UnitList::iterator iter = targets.begin(); iter != targets.end(); ++iter)
{
if (!(*iter)->HasUnitState(UNIT_STATE_CASTING))
continue;
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
{
if ((*iter)->GetCurrentSpell(i) && (*iter)->GetCurrentSpell(i)->m_targets.GetUnitTargetGUID() == target->GetGUID())
{
const SpellInfo* si = (*iter)->GetCurrentSpell(i)->GetSpellInfo();
if (si->HasAttribute(SPELL_ATTR6_CAN_TARGET_INVISIBLE) && (*iter)->GetTypeId() == TYPEID_UNIT)
{
Creature* c = (*iter)->ToCreature();
if ((!c->IsPet() && c->GetCreatureTemplate()->rank == CREATURE_ELITE_WORLDBOSS) || c->isWorldBoss() || c->IsDungeonBoss())
continue;
}
bool interrupt = false; // pussywizard: skip spells that don't target units, but casted on unit (eg. TARGET_DEST_TARGET_ENEMY)
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
if (si->Effects[j].Effect && (si->Effects[j].GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT || si->Effects[j].GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT_AND_DEST))
{
// at least one effect truly targets an unit, interrupt the spell
interrupt = true;
break;
}
if (interrupt)
(*iter)->InterruptSpell(CurrentSpellTypes(i), false);
}
}
}
target->CombatStop();
target->getHostileRefManager().deleteReferences();
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// prevent interrupt message
if (GetCasterGUID() == target->GetGUID())
{
if (target->GetCurrentSpell(CURRENT_GENERIC_SPELL))
target->FinishSpell(CURRENT_GENERIC_SPELL, true);
// interrupt autoshot
if (target->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL))
{
target->FinishSpell(CURRENT_AUTOREPEAT_SPELL);
target->ToPlayer()->SendAutoRepeatCancel(target);
}
}
target->InterruptNonMeleeSpells(true);
// stop handling the effect if it was removed by linked event
if (aurApp->GetRemoveMode())
return;
// blizz like 2.0.x
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
// blizz like 2.0.x
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
// blizz like 2.0.x
target->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
target->AddUnitState(UNIT_STATE_DIED);
}
else
{
/*
WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
data<<target->GetGUID();
data<<uint8(1);
target->SendMessageToSet(&data, true);
*/
// blizz like 2.0.x
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
// blizz like 2.0.x
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
// blizz like 2.0.x
target->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
target->ClearUnitState(UNIT_STATE_DIED);
}
}
void AuraEffect::HandleModUnattackable(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (!apply && target->HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
return;
target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, apply);
// call functions which may have additional effects after chainging state of unit
if (apply && (mode & AURA_EFFECT_HANDLE_REAL))
{
// xinef: this aura should not stop combat (movie with sindragosa proves that)
//target->CombatStop();
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
}
void AuraEffect::HandleAuraModDisarm(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
AuraType type = GetAuraType();
//Prevent handling aura twice
if ((apply) ? target->GetAuraEffectsByType(type).size() > 1 : target->HasAuraType(type))
return;
uint32 field, flag, slot;
WeaponAttackType attType;
switch (type)
{
case SPELL_AURA_MOD_DISARM:
field = UNIT_FIELD_FLAGS;
flag = UNIT_FLAG_DISARMED;
slot = EQUIPMENT_SLOT_MAINHAND;
attType = BASE_ATTACK;
break;
case SPELL_AURA_MOD_DISARM_OFFHAND:
field = UNIT_FIELD_FLAGS_2;
flag = UNIT_FLAG2_DISARM_OFFHAND;
slot = EQUIPMENT_SLOT_OFFHAND;
attType = OFF_ATTACK;
break;
case SPELL_AURA_MOD_DISARM_RANGED:
field = UNIT_FIELD_FLAGS_2;
flag = UNIT_FLAG2_DISARM_RANGED;
slot = EQUIPMENT_SLOT_RANGED;
attType = RANGED_ATTACK;
break;
default:
return;
}
// if disarm aura is to be removed, remove the flag first to reapply damage/aura mods
if (!apply)
target->RemoveFlag(field, flag);
// Handle damage modification, shapeshifted druids are not affected
if (target->GetTypeId() == TYPEID_PLAYER && (!target->IsInFeralForm() || target->GetShapeshiftForm() == FORM_GHOSTWOLF))
{
if (Item* pItem = target->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
{
uint8 attacktype = Player::GetAttackBySlot(slot);
if (attacktype < MAX_ATTACK)
{
target->ToPlayer()->_ApplyWeaponDamage(slot, pItem->GetTemplate(), NULL, !apply);
target->ToPlayer()->_ApplyWeaponDependentAuraMods(pItem, WeaponAttackType(attacktype), !apply);
}
}
}
// if disarm effects should be applied, wait to set flag until damage mods are unapplied
if (apply)
target->SetFlag(field, flag);
if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->GetCurrentEquipmentId())
target->UpdateDamagePhysical(attType);
}
void AuraEffect::HandleAuraModSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
// call functions which may have additional effects after chainging state of unit
// Stop cast only spells vs PreventionType == SPELL_PREVENTION_TYPE_SILENCE
for (uint32 i = CURRENT_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
// Stop spells on prepare or casting state
target->InterruptSpell(CurrentSpellTypes(i), false);
}
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(SPELL_AURA_MOD_SILENCE) || target->HasAuraType(SPELL_AURA_MOD_PACIFY_SILENCE))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
}
}
void AuraEffect::HandleAuraModPacify(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
//target->AttackStop(); // pussywizard: wtf? why having this flag prevents from being in combat? it should just prevent melee attack >_> tc retards https://github.com/SunwellCore/SunwellCore/commit/06f50110713feec2d6957e68ce2c5a5d2a997d6a
}
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(SPELL_AURA_MOD_PACIFY) || target->HasAuraType(SPELL_AURA_MOD_PACIFY_SILENCE))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
}
}
void AuraEffect::HandleAuraModPacifyAndSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!(apply))
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(SPELL_AURA_MOD_PACIFY_SILENCE))
return;
}
HandleAuraModPacify(aurApp, mode, apply);
HandleAuraModSilence(aurApp, mode, apply);
}
void AuraEffect::HandleAuraAllowOnlyAbility(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
target->SetFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY);
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(SPELL_AURA_ALLOW_ONLY_ABILITY))
return;
target->RemoveFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY);
}
}
}
/****************************/
/*** TRACKING ***/
/****************************/
void AuraEffect::HandleAuraTrackCreatures(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
target->SetFlag(PLAYER_TRACK_CREATURES, uint32(1) << (GetMiscValue() - 1));
else
target->RemoveFlag(PLAYER_TRACK_CREATURES, uint32(1) << (GetMiscValue() - 1));
}
void AuraEffect::HandleAuraTrackResources(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
target->SetFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (GetMiscValue() - 1));
else
target->RemoveFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (GetMiscValue() - 1));
}
void AuraEffect::HandleAuraTrackStealthed(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (!(apply))
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
}
target->ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply);
}
void AuraEffect::HandleAuraModStalked(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
// used by spells: Hunter's Mark, Mind Vision, Syndicate Tracker (MURP) DND
if (apply)
target->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (!target->HasAuraType(GetAuraType()))
target->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
}
// call functions which may have additional effects after chainging state of unit
target->UpdateObjectVisibility(target->GetTypeId() == TYPEID_PLAYER);
}
void AuraEffect::HandleAuraUntrackable(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
target->SetByteFlag(UNIT_FIELD_BYTES_1, 2, UNIT_STAND_FLAGS_UNTRACKABLE);
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
target->RemoveByteFlag(UNIT_FIELD_BYTES_1, 2, UNIT_STAND_FLAGS_UNTRACKABLE);
}
}
/****************************/
/*** SKILLS & TALENTS ***/
/****************************/
void AuraEffect::HandleAuraModPetTalentsPoints(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate pet talent points
if (Pet* pet = target->ToPlayer()->GetPet())
pet->InitTalentForLevel();
}
void AuraEffect::HandleAuraModSkill(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_SKILL)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
uint32 prot = GetMiscValue();
int32 points = GetAmount();
target->ToPlayer()->ModifySkillBonus(prot, ((apply) ? points: -points), GetAuraType() == SPELL_AURA_MOD_SKILL_TALENT);
if (prot == SKILL_DEFENSE)
target->ToPlayer()->UpdateDefenseBonusesMod();
}
/****************************/
/*** MOVEMENT ***/
/****************************/
void AuraEffect::HandleAuraMounted(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
uint32 creatureEntry = GetMiscValue();
// Festive Holiday Mount
if (target->HasAura(62061))
{
if (GetBase()->HasEffectType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED))
creatureEntry = 24906;
else
creatureEntry = 15665;
}
CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(creatureEntry);
if (!ci)
{
sLog->outErrorDb("AuraMounted: `creature_template`='%u' not found in database (only need its modelid)", GetMiscValue());
return;
}
uint32 displayID = ObjectMgr::ChooseDisplayId(ci);
sObjectMgr->GetCreatureModelRandomGender(&displayID);
//some spell has one aura of mount and one of vehicle
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (GetSpellInfo()->Effects[i].Effect == SPELL_EFFECT_SUMMON
&& GetSpellInfo()->Effects[i].MiscValue == GetMiscValue())
displayID = 0;
target->Mount(displayID, ci->VehicleId, GetMiscValue());
}
else
{
target->Dismount();
//some mounts like Headless Horseman's Mount or broom stick are skill based spell
// need to remove ALL arura related to mounts, this will stop client crash with broom stick
// and never endless flying after using Headless Horseman's Mount
if (mode & AURA_EFFECT_HANDLE_REAL)
target->RemoveAurasByType(SPELL_AURA_MOUNTED);
}
}
void AuraEffect::HandleAuraAllowFlight(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!apply)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()) || target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED))
return;
}
if (target->SetCanFly(apply))
if (!apply && !target->IsLevitating())
target->GetMotionMaster()->MoveFall();
}
void AuraEffect::HandleAuraWaterWalk(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!apply)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
}
target->SetWaterWalking(apply);
}
void AuraEffect::HandleAuraFeatherFall(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!apply)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
}
target->SetFeatherFall(apply);
// start fall from current height
if (!apply && target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->SetFallInformation(time(NULL), target->GetPositionZ());
}
void AuraEffect::HandleAuraHover(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!apply)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
}
target->SetHover(apply); //! Sets movementflags
}
void AuraEffect::HandleWaterBreathing(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
// update timers in client
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->UpdateMirrorTimers();
}
void AuraEffect::HandleForceMoveForward(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT);
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT);
}
}
/****************************/
/*** THREAT ***/
/****************************/
void AuraEffect::HandleModThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
for (int8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (GetMiscValue() & (1 << i))
ApplyPercentModFloatVar(target->m_threatModifier[i], float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModTotalThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!target->IsAlive() || target->GetTypeId() != TYPEID_PLAYER)
return;
Unit* caster = GetCaster();
if (caster && caster->IsAlive())
target->getHostileRefManager().addTempThreat((float)GetAmount(), apply);
}
void AuraEffect::HandleModTaunt(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (!target->IsAlive() || !target->CanHaveThreatList())
return;
Unit* caster = GetCaster();
if (!caster || !caster->IsAlive())
return;
if (apply)
target->TauntApply(caster);
else
{
// When taunt aura fades out, mob will switch to previous target if current has less than 1.1 * secondthreat
target->TauntFadeOut(caster);
}
}
/*****************************/
/*** CONTROL ***/
/*****************************/
void AuraEffect::HandleModConfuse(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->SetControlled(apply, UNIT_STATE_CONFUSED);
}
void AuraEffect::HandleModFear(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->SetControlled(apply, UNIT_STATE_FLEEING);
}
void AuraEffect::HandleAuraModStun(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->SetControlled(apply, UNIT_STATE_STUNNED);
}
void AuraEffect::HandleAuraModRoot(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->SetControlled(apply, UNIT_STATE_ROOT);
}
void AuraEffect::HandlePreventFleeing(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
// Since patch 3.0.2 this mechanic no longer affects fear effects. It will ONLY prevent humanoids from fleeing due to low health.
if (target->GetTypeId() == TYPEID_PLAYER || !apply || target->HasAuraType(SPELL_AURA_MOD_FEAR))
return;
/// TODO: find a way to cancel fleeing for assistance.
/// Currently this will only stop creatures fleeing due to low health that could not find nearby allies to flee towards.
target->SetControlled(false, UNIT_STATE_FLEEING);
}
/***************************/
/*** CHARM ***/
/***************************/
void AuraEffect::HandleModPossess(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
Unit* caster = GetCaster();
// no support for posession AI yet
if (caster && caster->GetTypeId() == TYPEID_UNIT)
{
HandleModCharm(aurApp, mode, apply);
return;
}
if (apply)
target->SetCharmedBy(caster, CHARM_TYPE_POSSESS, aurApp);
else
target->RemoveCharmedBy(caster);
}
void AuraEffect::HandleModPossessPet(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
// Used by spell "Eyes of the Beast"
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
//seems it may happen that when removing it is no longer owner's pet
//if (caster->ToPlayer()->GetPet() != target)
// return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_UNIT || !target->IsPet())
return;
Pet* pet = target->ToPet();
if (apply)
{
if (caster->ToPlayer()->GetPet() != pet)
return;
// Must clear current motion or pet leashes back to owner after a few yards
// when under spell 'Eyes of the Beast'
pet->GetMotionMaster()->Clear();
pet->SetCharmedBy(caster, CHARM_TYPE_POSSESS, aurApp);
}
else
{
pet->RemoveCharmedBy(caster);
if (!pet->IsWithinDistInMap(caster, pet->GetMap()->GetVisibilityRange()))
pet->Remove(PET_SAVE_NOT_IN_SLOT, true);
else
{
// Reinitialize the pet bar or it will appear greyed out
caster->ToPlayer()->PetSpellInitialize();
// Follow owner only if not fighting or owner didn't click "stay" at new location
// This may be confusing because pet bar shows "stay" when under the spell but it retains
// the "follow" flag. Player MUST click "stay" while under the spell.
if (!pet->GetVictim() && !pet->GetCharmInfo()->HasCommandState(COMMAND_STAY))
{
pet->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, pet->GetFollowAngle());
}
}
}
}
void AuraEffect::HandleModCharm(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
Unit* caster = GetCaster();
if (apply)
target->SetCharmedBy(caster, CHARM_TYPE_CHARM, aurApp);
else
target->RemoveCharmedBy(caster);
}
void AuraEffect::HandleCharmConvert(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
Unit* caster = GetCaster();
if (apply)
target->SetCharmedBy(caster, CHARM_TYPE_CONVERT, aurApp);
else
target->RemoveCharmedBy(caster);
}
/**
* Such auras are applied from a caster(=player) to a vehicle.
* This has been verified using spell #49256
*/
void AuraEffect::HandleAuraControlVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (!target->IsVehicle())
return;
Unit* caster = GetCaster();
if (!caster || caster == target)
return;
if (apply)
{
// Currently spells that have base points 0 and DieSides 0 = "0/0" exception are pushed to -1,
// however the idea of 0/0 is to ingore flag VEHICLE_SEAT_FLAG_CAN_ENTER_OR_EXIT and -1 checks for it,
// so this break such spells or most of them.
// Current formula about m_amount: effect base points + dieside - 1
// TO DO: Reasearch more about 0/0 and fix it.
caster->_EnterVehicle(target->GetVehicleKit(), m_amount - 1, aurApp);
}
else
{
if (GetId() == 53111) // Devour Humanoid
{
Unit::Kill(target, caster);
if (caster->GetTypeId() == TYPEID_UNIT)
caster->ToCreature()->RemoveCorpse();
}
caster->_ExitVehicle();
// some SPELL_AURA_CONTROL_VEHICLE auras have a dummy effect on the player - remove them
caster->RemoveAurasDueToSpell(GetId());
}
}
/*********************************************************/
/*** MODIFY SPEED ***/
/*********************************************************/
void AuraEffect::HandleAuraModIncreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
target->UpdateSpeed(MOVE_RUN, true);
}
void AuraEffect::HandleAuraModIncreaseMountedSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
HandleAuraModIncreaseSpeed(aurApp, mode, apply);
}
void AuraEffect::HandleAuraModIncreaseFlightSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK)
target->UpdateSpeed(MOVE_FLIGHT, true);
//! Update ability to fly
if (GetAuraType() == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK && (apply || (!target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !target->HasAuraType(SPELL_AURA_FLY))))
{
if (target->SetCanFly(apply))
if (!apply && !target->IsLevitating())
target->GetMotionMaster()->MoveFall();
}
//! Someone should clean up these hacks and remove it from this function. It doesn't even belong here.
if (mode & AURA_EFFECT_HANDLE_REAL)
{
//Players on flying mounts must be immune to polymorph
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
// Dragonmaw Illusion (overwrite mount model, mounted aura already applied)
if (apply && target->HasAuraEffect(42016, 0) && target->GetMountID())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
}
}
void AuraEffect::HandleAuraModIncreaseSwimSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
target->UpdateSpeed(MOVE_SWIM, true);
}
void AuraEffect::HandleAuraModDecreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
target->UpdateSpeed(MOVE_RUN_BACK, true);
target->UpdateSpeed(MOVE_SWIM_BACK, true);
target->UpdateSpeed(MOVE_FLIGHT_BACK, true);
}
void AuraEffect::HandleAuraModUseNormalSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
}
/*********************************************************/
/*** IMMUNITY ***/
/*********************************************************/
void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
std::list <AuraType> aura_immunity_list;
uint32 mechanic_immunity_list = 0;
int32 miscVal = GetMiscValue();
switch (miscVal)
{
case 96:
case 1615:
{
if (!GetAmount())
{
mechanic_immunity_list = (1 << MECHANIC_CHARM) | (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)
| (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM)
| (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR)
| (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED)
| (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_CHARM);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
break;
}
case 679:
{
if (GetId() == 57742)
{
mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)
| (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM)
| (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR)
| (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED)
| (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
break;
}
case 1557:
{
if (GetId() == 64187)
{
mechanic_immunity_list = (1 << MECHANIC_STUN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
}
else
{
mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)
| (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM)
| (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR)
| (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED)
| (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
break;
}
case 1614:
case 1694:
{
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT);
break;
}
case 1630:
{
if (!GetAmount())
{
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT);
}
else
{
mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)
| (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM)
| (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR)
| (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED)
| (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
break;
}
case 477:
case 1733:
case 1632:
{
if (!GetAmount())
{
mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT)
| (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM)
| (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR)
| (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED)
| (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN) | (1 << MECHANIC_BANISH);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_BANISH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK_DEST, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
break;
}
case 878:
{
if (GetAmount() == 1)
{
mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_STUN)
| (1 << MECHANIC_DISORIENTED) | (1 << MECHANIC_FREEZE);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
}
break;
}
default:
break;
}
if (aura_immunity_list.empty())
{
// Roots, OK
if (GetMiscValue() & (1<<0))
{
mechanic_immunity_list = (1 << MECHANIC_SNARE);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT);
}
// Taunt, OK
if (GetMiscValue() & (1<<1))
{
aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT);
}
// Crowd-Control auras?
if (GetMiscValue() & (1<<2))
{
mechanic_immunity_list = (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE);
}
// Interrupt, OK
if (GetMiscValue() & (1<<3))
{
mechanic_immunity_list = (1 << MECHANIC_INTERRUPT);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_INTERRUPT, apply);
}
// Transform?
if (GetMiscValue() & (1<<4))
{
aura_immunity_list.push_back(SPELL_AURA_TRANSFORM);
}
// Stun auras breakable by damage (Incapacitate effects), OK
if (GetMiscValue() & (1<<5))
{
mechanic_immunity_list = (1 << MECHANIC_KNOCKOUT);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_KNOCKOUT, apply);
}
// // Slowing effects
if (GetMiscValue() & (1<<6))
{
mechanic_immunity_list = (1 << MECHANIC_SNARE);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED);
}
// Charm auras?, 90%
if ((GetMiscValue() & (1<<7)))
{
mechanic_immunity_list = (1 << MECHANIC_CHARM);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_CHARM);
aura_immunity_list.push_back(SPELL_AURA_MOD_POSSESS);
}
// UNK
if ((GetMiscValue() & (1<<8)))
{
}
// Fear, OK
if (GetMiscValue() & (1<<9))
{
mechanic_immunity_list = (1 << MECHANIC_FEAR);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR);
}
// Stuns, OK
if (GetMiscValue() & (1<<10))
{
mechanic_immunity_list = (1 << MECHANIC_STUN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
aura_immunity_list.push_back(SPELL_AURA_MOD_STUN);
}
}
// apply immunities
for (std::list <AuraType>::iterator iter = aura_immunity_list.begin(); iter != aura_immunity_list.end(); ++iter)
target->ApplySpellImmune(GetId(), IMMUNITY_STATE, *iter, apply);
// Patch 3.0.3 Bladestorm now breaks all snares and roots on the warrior when activated.
if (GetId() == 46924)
{
if (apply)
{
target->resetAttackTimer();
target->resetAttackTimer(OFF_ATTACK);
}
// Knockback and hex
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, apply);
}
if (apply && GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY))
{
target->RemoveAurasWithMechanic(mechanic_immunity_list, AURA_REMOVE_BY_DEFAULT, GetId());
for (std::list <AuraType>::iterator iter = aura_immunity_list.begin(); iter != aura_immunity_list.end(); ++iter)
target->RemoveAurasByType(*iter);
}
}
void AuraEffect::HandleModMechanicImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
uint32 mechanic;
switch (GetId())
{
case 34471: // The Beast Within
case 19574: // Bestial Wrath
mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_KNOCKOUT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_BANISH, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SHACKLE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DAZE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply);
break;
case 42292: // PvP trinket
case 59752: // Every Man for Himself
case 65547: // PvP trinket for Faction Champions (ToC 25)
case 53490: // Bullheaded
case 46227: // Medalion of Immunity
mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
target->RemoveAurasByType(SPELL_AURA_PREVENTS_FLEEING); // xinef: Patch 2.3.0 PvP Trinkets: Insignia of the Alliance, Insignia of the Horde, Medallion of the Alliance, and Medallion of the Horde now clear the debuff from Judgement of Justice.
// Actually we should apply immunities here, too, but the aura has only 100 ms duration, so there is practically no point
break;
case 54508: // Demonic Empowerment
mechanic = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT);
target->RemoveAurasByType(SPELL_AURA_MOD_STUN);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply);
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply);
break;
default:
if (GetMiscValue() < 1)
return;
mechanic = 1 << GetMiscValue();
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, GetMiscValue(), apply);
break;
}
if (apply && GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY))
{
// Xinef: exception for purely snare mechanic (eg. hands of freedom)!
if (mechanic == (1 << MECHANIC_SNARE))
target->RemoveMovementImpairingAuras(false);
else
target->RemoveAurasWithMechanic(mechanic, AURA_REMOVE_BY_DEFAULT, GetId());
}
}
void AuraEffect::HandleAuraModEffectImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, GetMiscValue(), apply);
}
void AuraEffect::HandleAuraModStateImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_STATE, GetMiscValue(), apply);
if (apply && GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY))
target->RemoveAurasByType(AuraType(GetMiscValue()), 0, GetBase());
}
void AuraEffect::HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_SCHOOL, GetMiscValue(), (apply));
if (GetSpellInfo()->Mechanic == MECHANIC_BANISH)
{
if (apply)
target->AddUnitState(UNIT_STATE_ISOLATED);
else
{
bool banishFound = false;
Unit::AuraEffectList const& banishAuras = target->GetAuraEffectsByType(GetAuraType());
for (Unit::AuraEffectList::const_iterator i = banishAuras.begin(); i != banishAuras.end(); ++i)
if ((*i)->GetSpellInfo()->Mechanic == MECHANIC_BANISH)
{
banishFound = true;
break;
}
if (!banishFound)
target->ClearUnitState(UNIT_STATE_ISOLATED);
}
}
if (apply && GetMiscValue() == SPELL_SCHOOL_MASK_NORMAL)
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// remove all flag auras (they are positive, but they must be removed when you are immune)
if (GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
&& GetSpellInfo()->HasAttribute(SPELL_ATTR2_DAMAGE_REDUCED_SHIELD))
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// TODO: optimalize this cycle - use RemoveAurasWithInterruptFlags call or something else
if ((apply)
&& GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
&& GetSpellInfo()->IsPositive()) //Only positive immunity removes auras
{
uint32 school_mask = GetMiscValue();
Unit::AuraApplicationMap& Auras = target->GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator iter = Auras.begin(); iter != Auras.end();)
{
SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo();
if ((spell->GetSchoolMask() & school_mask)//Check for school mask
&& GetSpellInfo()->CanDispelAura(spell)
&& !iter->second->IsPositive() //Don't remove positive spells
&& spell->Id != GetId()) //Don't remove self
{
target->RemoveAura(iter);
}
else
++iter;
}
}
}
void AuraEffect::HandleAuraModDmgImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_DAMAGE, GetMiscValue(), apply);
}
void AuraEffect::HandleAuraModDispelImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
target->ApplySpellDispelImmunity(m_spellInfo, DispelType(GetMiscValue()), (apply));
}
/*********************************************************/
/*** MODIFY STATS ***/
/*********************************************************/
/********************************/
/*** RESISTANCE ***/
/********************************/
void AuraEffect::HandleAuraModResistanceExclusive(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++)
{
if (GetMiscValue() & int32(1<<x))
{
int32 amount = target->GetMaxPositiveAuraModifierByMiscMask(SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE, 1<<x, this);
if (amount < GetAmount())
{
float value = float(GetAmount() - amount);
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_VALUE, value, apply);
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplyResistanceBuffModsMod(SpellSchools(x), aurApp->IsPositive(), value, apply);
}
}
}
}
void AuraEffect::HandleAuraModResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++)
{
if (GetMiscValue() & int32(1<<x))
{
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(GetAmount()), apply);
if (target->GetTypeId() == TYPEID_PLAYER || target->IsPet())
target->ApplyResistanceBuffModsMod(SpellSchools(x), GetAmount() > 0, (float)GetAmount(), apply);
}
}
}
void AuraEffect::HandleAuraModBaseResistancePCT(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// only players have base stats
if (target->GetTypeId() != TYPEID_PLAYER)
{
//pets only have base armor
if (target->IsPet() && (GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL))
target->HandleStatModifier(UNIT_MOD_ARMOR, BASE_PCT, float(GetAmount()), apply);
}
else
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++)
{
if (GetMiscValue() & int32(1<<x))
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_PCT, float(GetAmount()), apply);
}
}
}
void AuraEffect::HandleModResistancePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; i++)
{
if (GetMiscValue() & int32(1<<i))
{
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_PCT, float(GetAmount()), apply);
if (target->GetTypeId() == TYPEID_PLAYER || target->IsPet())
{
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), true, (float)GetAmount(), apply);
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), false, (float)GetAmount(), apply);
}
}
}
}
void AuraEffect::HandleModBaseResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// only players have base stats
if (target->GetTypeId() != TYPEID_PLAYER)
{
//only pets have base stats
if (target->IsPet() && (GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL))
target->HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(GetAmount()), apply);
}
else
{
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; i++)
if (GetMiscValue() & (1<<i))
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_VALUE, float(GetAmount()), apply);
}
}
void AuraEffect::HandleModTargetResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// applied to damage as HandleNoImmediateEffect in Unit::CalcAbsorbResist and Unit::CalcArmorReducedDamage
// show armor penetration
if (target->GetTypeId() == TYPEID_PLAYER && (GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL))
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, GetAmount(), apply);
// show as spell penetration only full spell penetration bonuses (all resistances except armor and holy
if (target->GetTypeId() == TYPEID_PLAYER && (GetMiscValue() & SPELL_SCHOOL_MASK_SPELL) == SPELL_SCHOOL_MASK_SPELL)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, GetAmount(), apply);
}
/********************************/
/*** STAT ***/
/********************************/
void AuraEffect::HandleAuraModStat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (GetMiscValue() < -2 || GetMiscValue() > 4)
{
sLog->outError("WARNING: Spell %u effect %u has an unsupported misc value (%i) for SPELL_AURA_MOD_STAT ", GetId(), GetEffIndex(), GetMiscValue());
return;
}
for (int32 i = STAT_STRENGTH; i < MAX_STATS; i++)
{
// -1 or -2 is all stats (misc < -2 checked in function beginning)
if (GetMiscValue() < 0 || GetMiscValue() == i)
{
//target->ApplyStatMod(Stats(i), m_amount, apply);
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(GetAmount()), apply);
if (target->GetTypeId() == TYPEID_PLAYER || target->IsPet())
target->ApplyStatBuffMod(Stats(i), (float)GetAmount(), apply);
}
}
}
void AuraEffect::HandleModPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (GetMiscValue() < -1 || GetMiscValue() > 4)
{
sLog->outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
// only players have base stats
if (target->GetTypeId() != TYPEID_PLAYER)
return;
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
if (GetMiscValue() == i || GetMiscValue() == -1)
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), BASE_PCT, float(m_amount), apply);
}
}
void AuraEffect::HandleModSpellDamagePercentFromStat(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonus
// This information for client side use only
// Recalculate bonus
target->ToPlayer()->UpdateSpellDamageAndHealingBonus();
}
void AuraEffect::HandleModSpellHealingPercentFromStat(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
target->ToPlayer()->UpdateSpellDamageAndHealingBonus();
}
void AuraEffect::HandleModSpellDamagePercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonus
// This information for client side use only
// Recalculate bonus
target->ToPlayer()->UpdateSpellDamageAndHealingBonus();
}
void AuraEffect::HandleModSpellHealingPercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
target->ToPlayer()->UpdateSpellDamageAndHealingBonus();
}
void AuraEffect::HandleModHealingDone(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// implemented in Unit::SpellHealingBonus
// this information is for client side only
target->ToPlayer()->UpdateSpellDamageAndHealingBonus();
}
void AuraEffect::HandleModTotalPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (GetMiscValue() < -1 || GetMiscValue() > 4)
{
sLog->outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
// save current health state
float healthPct = target->GetHealthPct();
bool alive = target->IsAlive();
float value = GetAmount();
if (GetId() == 67480) // xinef: hack fix for blessing of sanctuary stats stack with blessing of kings...
{
if (value) // not turned off
value = 10.0f;
for (int32 i = STAT_STRENGTH; i < MAX_STATS; i++)
{
if (i == STAT_STRENGTH || i == STAT_STAMINA)
{
if (apply && (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()))
target->ApplyStatPercentBuffMod(Stats(i), value, apply);
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, value, apply);
if (!apply && (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()))
target->ApplyStatPercentBuffMod(Stats(i), value, apply);
}
}
return;
}
for (int32 i = STAT_STRENGTH; i < MAX_STATS; i++)
{
if (GetMiscValue() == i || GetMiscValue() == -1)
{
if (apply && (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()))
target->ApplyStatPercentBuffMod(Stats(i), value, apply);
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, value, apply);
if (!apply && (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()))
target->ApplyStatPercentBuffMod(Stats(i), value, apply);
}
}
// recalculate current HP/MP after applying aura modifications (only for spells with SPELL_ATTR0_UNK4 0x00000010 flag)
// this check is total bullshit i think
if (GetMiscValue() == STAT_STAMINA && m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY))
target->SetHealth(std::max<uint32>(uint32(healthPct * target->GetMaxHealth() * 0.01f), (alive ? 1 : 0)));
}
void AuraEffect::HandleAuraModResistenceOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (GetMiscValue() != SPELL_SCHOOL_MASK_NORMAL)
{
// support required adding replace UpdateArmor by loop by UpdateResistence at intellect update
// and include in UpdateResistence same code as in UpdateArmor for aura mod apply.
sLog->outError("Aura SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT(182) does not work for non-armor type resistances!");
return;
}
// Recalculate Armor
target->UpdateArmor();
}
void AuraEffect::HandleAuraModExpertise(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
target->ToPlayer()->UpdateExpertise(BASE_ATTACK);
target->ToPlayer()->UpdateExpertise(OFF_ATTACK);
}
/********************************/
/*** HEAL & ENERGIZE ***/
/********************************/
void AuraEffect::HandleModPowerRegen(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Update manaregen value
if (GetMiscValue() == POWER_MANA)
target->ToPlayer()->UpdateManaRegen();
else if (GetMiscValue() == POWER_RUNE)
target->ToPlayer()->UpdateRuneRegen(RuneType(GetMiscValueB()));
// other powers are not immediate effects - implemented in Player::Regenerate, Creature::Regenerate
}
void AuraEffect::HandleModPowerRegenPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
HandleModPowerRegen(aurApp, mode, apply);
}
void AuraEffect::HandleModManaRegen(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
//Note: an increase in regen does NOT cause threat.
target->ToPlayer()->UpdateManaRegen();
}
void AuraEffect::HandleAuraModIncreaseHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(GetAmount()), apply);
target->ModifyHealth(GetAmount());
}
else
{
if (int32(target->GetHealth()) > GetAmount())
target->ModifyHealth(-GetAmount());
else
target->SetHealth(1);
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(GetAmount()), apply);
}
}
void AuraEffect::HandleAuraModIncreaseMaxHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
uint32 oldhealth = target->GetHealth();
double healthPercentage = (double)oldhealth / (double)target->GetMaxHealth();
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(GetAmount()), apply);
// refresh percentage
if (oldhealth > 0)
{
uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage));
if (newhealth == 0)
newhealth = 1;
target->SetHealth(newhealth);
}
}
void AuraEffect::HandleAuraModIncreaseEnergy(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
Powers powerType = Powers(GetMiscValue());
// do not check power type, we can always modify the maximum
// as the client will not see any difference
// also, placing conditions that may change during the aura duration
// inside effect handlers is not a good idea
//if (int32(powerType) != GetMiscValue())
// return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
target->HandleStatModifier(unitMod, TOTAL_VALUE, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModIncreaseEnergyPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
Powers powerType = Powers(GetMiscValue());
// do not check power type, we can always modify the maximum
// as the client will not see any difference
// also, placing conditions that may change during the aura duration
// inside effect handlers is not a good idea
//if (int32(powerType) != GetMiscValue())
// return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
float amount = float(GetAmount());
if (apply)
{
target->HandleStatModifier(unitMod, TOTAL_PCT, amount, apply);
target->ModifyPowerPct(powerType, amount, apply);
}
else
{
target->ModifyPowerPct(powerType, amount, apply);
target->HandleStatModifier(unitMod, TOTAL_PCT, amount, apply);
}
}
void AuraEffect::HandleAuraModIncreaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// Unit will keep hp% after MaxHealth being modified if unit is alive.
float percent = target->GetHealthPct();
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_PCT, float(GetAmount()), apply);
// Xinef: idiots, pct was rounded down and could "kill" creature by setting its health to 0 making npc zombie
if (target->IsAlive())
if (uint32 healthAmount = CalculatePct(target->GetMaxHealth(), percent))
target->SetHealth(healthAmount);
}
void AuraEffect::HandleAuraIncreaseBaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->HandleStatModifier(UNIT_MOD_HEALTH, BASE_PCT, float(GetAmount()), apply);
}
/********************************/
/*** FIGHT ***/
/********************************/
void AuraEffect::HandleAuraModParryPercent(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
target->ToPlayer()->UpdateParryPercentage();
}
void AuraEffect::HandleAuraModDodgePercent(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
target->ToPlayer()->UpdateDodgePercentage();
}
void AuraEffect::HandleAuraModBlockPercent(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
target->ToPlayer()->UpdateBlockPercentage();
}
void AuraEffect::HandleAuraModRegenInterrupt(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
HandleModManaRegen(aurApp, mode, apply);
}
void AuraEffect::HandleAuraModWeaponCritPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = target->ToPlayer()->GetWeaponForAttack(WeaponAttackType(i), true))
target->ToPlayer()->_ApplyWeaponDependentAuraCritMod(pItem, WeaponAttackType(i), this, apply);
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// GetMiscValue() comparison with item generated damage types
if (GetSpellInfo()->EquippedItemClass == -1)
{
target->ToPlayer()->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
target->ToPlayer()->HandleBaseModValue(OFFHAND_CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
target->ToPlayer()->HandleBaseModValue(RANGED_CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
}
void AuraEffect::HandleModHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
{
target->ToPlayer()->UpdateMeleeHitChances();
target->ToPlayer()->UpdateRangedHitChances();
}
else
{
target->m_modMeleeHitChance += (apply) ? GetAmount() : (-GetAmount());
target->m_modRangedHitChance += (apply) ? GetAmount() : (-GetAmount());
}
}
void AuraEffect::HandleModSpellHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->UpdateSpellHitChances();
else
target->m_modSpellHitChance += (apply) ? GetAmount(): (-GetAmount());
}
void AuraEffect::HandleModSpellCritChance(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->UpdateAllSpellCritChances();
else
target->m_baseSpellCritChance += (apply) ? GetAmount():-GetAmount();
}
void AuraEffect::HandleModSpellCritChanceShool(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school)
if (GetMiscValue() & (1<<school))
target->ToPlayer()->UpdateSpellCritChance(school);
}
void AuraEffect::HandleAuraModCritPct(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
{
target->m_baseSpellCritChance += (apply) ? GetAmount():-GetAmount();
return;
}
target->ToPlayer()->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
target->ToPlayer()->HandleBaseModValue(OFFHAND_CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
target->ToPlayer()->HandleBaseModValue(RANGED_CRIT_PERCENTAGE, FLAT_MOD, float (GetAmount()), apply);
// included in Player::UpdateSpellCritChance calculation
target->ToPlayer()->UpdateAllSpellCritChances();
}
/********************************/
/*** ATTACK SPEED ***/
/********************************/
void AuraEffect::HandleModCastingSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// Xinef: Do not apply such auras in normal way
if (GetAmount() >= 1000)
{
target->SetInstantCast(apply);
return;
}
target->ApplyCastTimePercentMod((float)GetAmount(), apply);
}
void AuraEffect::HandleModMeleeRangedSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, (float)GetAmount(), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, (float)GetAmount(), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, (float)GetAmount(), apply);
}
void AuraEffect::HandleModCombatSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->ApplyCastTimePercentMod(float(GetAmount()), apply);
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(GetAmount()), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(GetAmount()), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(GetAmount()), apply);
}
void AuraEffect::HandleModAttackSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(GetAmount()), apply);
target->UpdateDamagePhysical(BASE_ATTACK);
}
void AuraEffect::HandleModMeleeSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(GetAmount()), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModRangedHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->ApplyAttackTimePercentMod(RANGED_ATTACK, (float)GetAmount(), apply);
}
void AuraEffect::HandleRangedAmmoHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
target->ApplyAttackTimePercentMod(RANGED_ATTACK, (float)GetAmount(), apply);
}
/********************************/
/*** COMBAT RATING ***/
/********************************/
void AuraEffect::HandleModRating(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating)
if (GetMiscValue() & (1 << rating))
target->ToPlayer()->ApplyRatingMod(CombatRating(rating), GetAmount(), apply);
}
void AuraEffect::HandleModRatingFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Just recalculate ratings
for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating)
if (GetMiscValue() & (1 << rating))
target->ToPlayer()->ApplyRatingMod(CombatRating(rating), 0, apply);
}
/********************************/
/*** ATTACK POWER ***/
/********************************/
void AuraEffect::HandleAuraModAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModRangedAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if ((target->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
target->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
//UNIT_FIELD_ATTACK_POWER_MULTIPLIER = multiplier - 1
target->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModRangedAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if ((target->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
//UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER = multiplier - 1
target->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_PCT, float(GetAmount()), apply);
}
void AuraEffect::HandleAuraModRangedAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// Recalculate bonus
if (target->GetTypeId() == TYPEID_PLAYER && !(target->getClassMask() & CLASSMASK_WAND_USERS))
target->ToPlayer()->UpdateAttackPowerAndDamage(true);
}
void AuraEffect::HandleAuraModAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
HandleAuraModAttackPowerOfArmor(aurApp, mode, apply);
}
void AuraEffect::HandleAuraModAttackPowerOfArmor(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// Recalculate bonus
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->UpdateAttackPowerAndDamage(false);
}
/********************************/
/*** DAMAGE BONUS ***/
/********************************/
void AuraEffect::HandleModDamageDone(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
// apply item specific bonuses for already equipped weapon
if (target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = target->ToPlayer()->GetWeaponForAttack(WeaponAttackType(i), true))
target->ToPlayer()->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply);
}
// GetMiscValue() is bitmask of spell schools
// 1 (0-bit) - normal school damage (SPELL_SCHOOL_MASK_NORMAL)
// 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wands
// 127 - full bitmask any damages
//
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// GetMiscValue() comparison with item generated damage types
if ((GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) != 0)
{
// apply generic physical damage bonuses including wand case
if (GetSpellInfo()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER)
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(GetAmount()), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(GetAmount()), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(GetAmount()), apply);
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (GetAmount() > 0)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, GetAmount(), apply);
else
target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG, GetAmount(), apply);
}
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
}
// Skip non magic case for speedup
if ((GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) == 0)
return;
if (GetSpellInfo()->EquippedItemClass != -1 || GetSpellInfo()->EquippedItemInventoryTypeMask != 0)
{
// wand magic case (skip generic to all item spell bonuses)
// done in Player::_ApplyWeaponDependentAuraMods
// Skip item specific requirements for not wand magic damage
return;
}
// Magic damage modifiers implemented in Unit::SpellDamageBonus
// This information for client side use only
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (GetAmount() > 0)
{
for (uint32 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; i++)
{
if ((GetMiscValue() & (1<<i)) != 0)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, GetAmount(), apply);
}
}
else
{
for (uint32 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; i++)
{
if ((GetMiscValue() & (1<<i)) != 0)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, GetAmount(), apply);
}
}
if (Guardian* pet = target->ToPlayer()->GetGuardianPet())
pet->UpdateAttackPowerAndDamage();
}
}
void AuraEffect::HandleModDamagePercentDone(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
if (!target)
return;
if (target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* item = target->ToPlayer()->GetWeaponForAttack(WeaponAttackType(i), false))
target->ToPlayer()->_ApplyWeaponDependentAuraDamageMod(item, WeaponAttackType(i), this, apply);
}
if ((GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) && (GetSpellInfo()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER))
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_PCT, float(GetAmount()), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(GetAmount()), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_PCT, float(GetAmount()), apply);
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->ApplyPercentModFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT, float (GetAmount()), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods for SPELL_SCHOOL_MASK_NORMAL && EquippedItemClass != -1 and also for wand case
}
}
void AuraEffect::HandleModOffhandDamagePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(GetAmount()), apply);
}
void AuraEffect::HandleShieldBlockValue(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT)))
return;
Unit* target = aurApp->GetTarget();
BaseModType modType = FLAT_MOD;
if (GetAuraType() == SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT)
modType = PCT_MOD;
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->HandleBaseModValue(SHIELD_BLOCK_VALUE, modType, float(GetAmount()), apply);
}
/********************************/
/*** POWER COST ***/
/********************************/
void AuraEffect::HandleModPowerCostPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
float amount = CalculatePct(1.0f, GetAmount());
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (GetMiscValue() & (1 << i))
target->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, amount, apply);
}
void AuraEffect::HandleModPowerCost(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (GetMiscValue() & (1<<i))
target->ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i, GetAmount(), apply);
}
void AuraEffect::HandleArenaPreparation(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (apply)
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION);
else
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION);
}
}
void AuraEffect::HandleNoReagentUseAura(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
flag96 mask;
Unit::AuraEffectList const& noReagent = target->GetAuraEffectsByType(SPELL_AURA_NO_REAGENT_USE);
for (Unit::AuraEffectList::const_iterator i = noReagent.begin(); i != noReagent.end(); ++i)
mask |= (*i)->m_spellInfo->Effects[(*i)->m_effIndex].SpellClassMask;
target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1 , mask[0]);
target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1+1, mask[1]);
target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1+2, mask[2]);
}
void AuraEffect::HandleAuraRetainComboPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// combo points was added in SPELL_EFFECT_ADD_COMBO_POINTS handler
// remove only if aura expire by time (in case combo points amount change aura removed without combo points lost)
if (!(apply) && GetBase()->GetDuration() == 0 && target->ToPlayer()->GetComboTarget())
if (Unit* unit = ObjectAccessor::GetUnit(*target, target->ToPlayer()->GetComboTarget()))
target->ToPlayer()->AddComboPoints(unit, -GetAmount());
}
/*********************************************************/
/*** OTHERS ***/
/*********************************************************/
void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_REAPPLY)))
return;
Unit* target = aurApp->GetTarget();
Unit* caster = GetCaster();
if (mode & AURA_EFFECT_HANDLE_REAL)
{
// pet auras
if (PetAura const* petSpell = sSpellMgr->GetPetAura(GetId(), m_effIndex))
{
if (apply)
target->AddPetAura(petSpell);
else
target->RemovePetAura(petSpell);
}
}
if (mode & (AURA_EFFECT_HANDLE_REAL | AURA_EFFECT_HANDLE_REAPPLY))
{
// AT APPLY
if (apply)
{
switch (GetId())
{
case 1515: // Tame beast
// FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness
if (caster && target->CanHaveThreatList())
target->AddThreat(caster, 10.0f);
break;
case 13139: // net-o-matic
// root to self part of (root_target->charge->root_self sequence
if (caster)
caster->CastSpell(caster, 13138, true, NULL, this);
break;
case 34026: // kill command
{
Unit* pet = target->GetGuardianPet();
if (!pet)
break;
target->CastSpell(target, 34027, true, NULL, this);
// set 3 stacks and 3 charges (to make all auras not disappear at once)
Aura* owner_aura = target->GetAura(34027, GetCasterGUID());
Aura* pet_aura = pet->GetAura(58914, GetCasterGUID());
if (owner_aura)
{
owner_aura->SetCharges(0);
owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount);
if (pet_aura)
{
pet_aura->SetCharges(0);
pet_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount);
}
}
break;
}
case 37096: // Blood Elf Illusion
{
if (caster)
{
switch (caster->getGender())
{
case GENDER_FEMALE:
caster->CastSpell(target, 37095, true, NULL, this); // Blood Elf Disguise
break;
case GENDER_MALE:
caster->CastSpell(target, 37093, true, NULL, this);
break;
default:
break;
}
}
break;
}
case 55198: // Tidal Force
{
target->CastSpell(target, 55166, true);
if (Aura* owner_aura = target->GetAura(55166))
owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount);
return;
}
case 39850: // Rocket Blast
if (roll_chance_i(20)) // backfire stun
target->CastSpell(target, 51581, true, NULL, this);
break;
case 43873: // Headless Horseman Laugh
target->PlayDistanceSound(11965);
break;
case 46354: // Blood Elf Illusion
if (caster)
{
switch (caster->getGender())
{
case GENDER_FEMALE:
caster->CastSpell(target, 46356, true, NULL, this);
break;
case GENDER_MALE:
caster->CastSpell(target, 46355, true, NULL, this);
break;
}
}
break;
case 46361: // Reinforced Net
if (caster)
target->GetMotionMaster()->MoveFall();
break;
case 46699: // Requires No Ammo
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->RemoveAmmo(); // not use ammo and not allow use
break;
case 71563:
{
if (Aura* newAura = target->AddAura(71564, target))
newAura->SetStackAmount(newAura->GetSpellInfo()->StackAmount);
return;
}
}
}
// AT REMOVE
else
{
if ((GetSpellInfo()->IsQuestTame()) && caster && caster->IsAlive() && target->IsAlive())
{
uint32 finalSpelId = 0;
switch (GetId())
{
case 19548: finalSpelId = 19597; break;
case 19674: finalSpelId = 19677; break;
case 19687: finalSpelId = 19676; break;
case 19688: finalSpelId = 19678; break;
case 19689: finalSpelId = 19679; break;
case 19692: finalSpelId = 19680; break;
case 19693: finalSpelId = 19684; break;
case 19694: finalSpelId = 19681; break;
case 19696: finalSpelId = 19682; break;
case 19697: finalSpelId = 19683; break;
case 19699: finalSpelId = 19685; break;
case 19700: finalSpelId = 19686; break;
case 30646: finalSpelId = 30647; break;
case 30653: finalSpelId = 30648; break;
case 30654: finalSpelId = 30652; break;
case 30099: finalSpelId = 30100; break;
case 30102: finalSpelId = 30103; break;
case 30105: finalSpelId = 30104; break;
}
if (finalSpelId)
caster->CastSpell(target, finalSpelId, true, NULL, this);
}
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (GetId())
{
case 2584: // Waiting to Resurrect
break;
case 43681: // Inactive
{
if (target->GetTypeId() != TYPEID_PLAYER || aurApp->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE)
return;
break;
}
case 52172: // Coyote Spirit Despawn Aura
case 60244: // Blood Parrot Despawn Aura
target->CastSpell((Unit*)NULL, GetAmount(), true, NULL, this);
break;
// Halls of Lightning, Arc Lightning
case 52921:
{
if( aurApp->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE )
return;
Player* player = NULL;
Trinity::AnyPlayerInObjectRangeCheck checker(target, 10.0f);
Trinity::PlayerSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(target, player, checker);
target->VisitNearbyWorldObject(10.0f, searcher);
if( player && player->GetGUID() != target->GetGUID() )
target->CastSpell(player, 52921, true);
return;
}
case 58600: // Restricted Flight Area
case 58730: // Restricted Flight Area
if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 58601, true);
break;
case 46374: // quest The Power of the Elements (11893)
{
if (target->isDead() && GetBase() && target->GetTypeId() == TYPEID_UNIT && target->GetEntry() == 24601)
{
Unit* caster = GetBase()->GetCaster();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
caster->ToPlayer()->KilledMonsterCredit(25987, 0);
}
return;
}
}
break;
default:
break;
}
}
}
// AT APPLY & REMOVE
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
break;
switch (GetId())
{
// Recently Bandaged
case 11196:
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, GetMiscValue(), apply);
break;
// Unstable Power
case 24658:
{
uint32 spellId = 24659;
if (apply && caster)
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId);
for (uint32 i = 0; i < spell->StackAmount; ++i)
caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID());
break;
}
target->RemoveAurasDueToSpell(spellId);
break;
}
// Restless Strength
case 24661:
{
uint32 spellId = 24662;
if (apply && caster)
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId);
for (uint32 i = 0; i < spell->StackAmount; ++i)
caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID());
break;
}
target->RemoveAurasDueToSpell(spellId);
break;
}
// Tag Murloc
case 30877:
{
// Tag/untag Blacksilt Scout
target->SetEntry(apply ? 17654 : 17326);
break;
}
case 62061: // Festive Holiday Mount
if (target->HasAuraType(SPELL_AURA_MOUNTED))
{
uint32 creatureEntry = 0;
if (apply)
{
if (target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED))
creatureEntry = 24906;
else
creatureEntry = 15665;
}
else
creatureEntry = target->GetAuraEffectsByType(SPELL_AURA_MOUNTED).front()->GetMiscValue();
if (CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry))
{
uint32 displayID = ObjectMgr::ChooseDisplayId(creatureInfo);
sObjectMgr->GetCreatureModelRandomGender(&displayID);
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, displayID);
}
}
break;
}
break;
}
case SPELLFAMILY_MAGE:
{
//if (!(mode & AURA_EFFECT_HANDLE_REAL))
//break;
break;
}
case SPELLFAMILY_PRIEST:
{
//if (!(mode & AURA_EFFECT_HANDLE_REAL))
//break;
break;
}
case SPELLFAMILY_DRUID:
{
//if (!(mode & AURA_EFFECT_HANDLE_REAL))
// break;
break;
}
case SPELLFAMILY_SHAMAN:
{
//if (!(mode & AURA_EFFECT_HANDLE_REAL))
// break;
break;
}
}
}
void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
if (apply || aurApp->GetRemoveMode() != AURA_REMOVE_BY_DEATH)
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* plCaster = caster->ToPlayer();
Unit* target = aurApp->GetTarget();
// Item amount
if (GetAmount() <= 0)
return;
if (GetSpellInfo()->Effects[m_effIndex].ItemType == 0)
return;
// Soul Shard
if (GetSpellInfo()->Effects[m_effIndex].ItemType == 6265)
{
// Soul Shard only from units that grant XP or honor
if (!plCaster->isHonorOrXPTarget(target) ||
(target->GetTypeId() == TYPEID_UNIT && !target->ToCreature()->isTappedBy(plCaster)))
return;
// If this is Drain Soul, check for Glyph of Drain Soul
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARLOCK && (GetSpellInfo()->SpellFamilyFlags[0] & 0x00004000))
{
// Glyph of Drain Soul - chance to create an additional Soul Shard
if (AuraEffect* aur = caster->GetAuraEffect(58070, 0))
if (roll_chance_i(aur->GetMiscValue()))
caster->CastSpell(caster, 58068, true, 0, aur); // We _could_ simply do ++count here, but Blizz does it this way :)
}
}
//Adding items
uint32 noSpaceForCount = 0;
uint32 count = m_amount;
ItemPosCountVec dest;
InventoryResult msg = plCaster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, GetSpellInfo()->Effects[m_effIndex].ItemType, count, &noSpaceForCount);
if (msg != EQUIP_ERR_OK)
{
count-=noSpaceForCount;
plCaster->SendEquipError(msg, NULL, NULL, GetSpellInfo()->Effects[m_effIndex].ItemType);
if (count == 0)
return;
}
Item* newitem = plCaster->StoreNewItem(dest, GetSpellInfo()->Effects[m_effIndex].ItemType, true);
if (!newitem)
{
plCaster->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL);
return;
}
plCaster->SendNewItem(newitem, count, true, true);
}
void AuraEffect::HandleBindSight(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
caster->ToPlayer()->SetViewpoint(target, apply);
}
void AuraEffect::HandleForceReaction(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = target->ToPlayer();
uint32 faction_id = GetMiscValue();
ReputationRank faction_rank = ReputationRank(m_amount);
player->GetReputationMgr().ApplyForceReaction(faction_id, faction_rank, apply);
player->GetReputationMgr().SendForceReactions();
// stop fighting if at apply forced rank friendly or at remove real rank friendly
if ((apply && faction_rank >= REP_FRIENDLY) || (!apply && player->GetReputationRank(faction_id) >= REP_FRIENDLY))
player->StopAttackFaction(faction_id);
}
void AuraEffect::HandleAuraEmpathy(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (!apply)
{
// do not remove unit flag if there are more than this auraEffect of that kind on unit on unit
if (target->HasAuraType(GetAuraType()))
return;
}
if (target->GetCreatureType() == CREATURE_TYPE_BEAST)
target->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO, apply);
}
void AuraEffect::HandleAuraModFaction(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
target->setFaction(GetMiscValue());
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
else
{
target->RestoreFaction();
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
}
void AuraEffect::HandleComprehendLanguage(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
else
{
if (target->HasAuraType(GetAuraType()))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
}
}
void AuraEffect::HandleAuraConvertRune(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = target->ToPlayer();
if (player->getClass() != CLASS_DEATH_KNIGHT)
return;
uint32 runes = m_amount;
// convert number of runes specified in aura amount of rune type in miscvalue to runetype in miscvalueb
if (apply)
{
for (uint32 i = 0; i < MAX_RUNES && runes; ++i)
{
if (GetMiscValue() != player->GetCurrentRune(i))
continue;
if (!player->GetRuneCooldown(i))
{
player->AddRuneByAuraEffect(i, RuneType(GetMiscValueB()), this);
--runes;
}
}
}
else
player->RemoveRunesByAuraEffect(this);
}
void AuraEffect::HandleAuraLinked(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
Unit* target = aurApp->GetTarget();
uint32 triggeredSpellId = m_spellInfo->Effects[m_effIndex].TriggerSpell;
SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggeredSpellId);
if (!triggeredSpellInfo)
return;
if (mode & AURA_EFFECT_HANDLE_REAL)
{
if (apply)
{
Unit* caster = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo, GetEffIndex()) ? GetCaster() : target;
if (!caster)
return;
// If amount avalible cast with basepoints (Crypt Fever for example)
if (GetAmount())
caster->CastCustomSpell(target, triggeredSpellId, &m_amount, NULL, NULL, true, NULL, this);
else
caster->CastSpell(target, triggeredSpellId, true, NULL, this);
}
else
{
uint64 casterGUID = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo, GetEffIndex()) ? GetCasterGUID() : target->GetGUID();
target->RemoveAura(triggeredSpellId, casterGUID, 0, aurApp->GetRemoveMode());
}
}
else if (mode & AURA_EFFECT_HANDLE_REAPPLY && apply)
{
uint64 casterGUID = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo, GetEffIndex()) ? GetCasterGUID() : target->GetGUID();
// change the stack amount to be equal to stack amount of our aura
if (Aura* triggeredAura = target->GetAura(triggeredSpellId, casterGUID))
triggeredAura->ModStackAmount(GetBase()->GetStackAmount() - triggeredAura->GetStackAmount());
}
}
void AuraEffect::HandleAuraModFakeInebriation(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK))
return;
Unit* target = aurApp->GetTarget();
if (apply)
{
target->m_invisibilityDetect.AddFlag(INVISIBILITY_DRUNK);
target->m_invisibilityDetect.AddValue(INVISIBILITY_DRUNK, GetAmount());
if (target->GetTypeId() == TYPEID_PLAYER)
{
int32 oldval = target->ToPlayer()->GetInt32Value(PLAYER_FAKE_INEBRIATION);
target->ToPlayer()->SetInt32Value(PLAYER_FAKE_INEBRIATION, oldval + GetAmount());
}
}
else
{
bool removeDetect = !target->HasAuraType(SPELL_AURA_MOD_FAKE_INEBRIATE);
target->m_invisibilityDetect.AddValue(INVISIBILITY_DRUNK, -GetAmount());
if (target->GetTypeId() == TYPEID_PLAYER)
{
int32 oldval = target->ToPlayer()->GetInt32Value(PLAYER_FAKE_INEBRIATION);
target->ToPlayer()->SetInt32Value(PLAYER_FAKE_INEBRIATION, oldval - GetAmount());
if (removeDetect)
removeDetect = !target->ToPlayer()->GetDrunkValue();
}
if (removeDetect)
target->m_invisibilityDetect.DelFlag(INVISIBILITY_DRUNK);
}
// call functions which may have additional effects after chainging state of unit
target->UpdateObjectVisibility(false);
}
void AuraEffect::HandleAuraOverrideSpells(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Player* target = aurApp->GetTarget()->ToPlayer();
if (!target || !target->IsInWorld())
return;
uint32 overrideId = uint32(GetMiscValue());
if (apply)
{
target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, overrideId);
if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId))
for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i)
if (uint32 spellId = overrideSpells->spellId[i])
target->_addSpell(spellId, SPEC_MASK_ALL, true);
}
else
{
target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, 0);
if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId))
for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i)
if (uint32 spellId = overrideSpells->spellId[i])
target->removeSpell(spellId, SPEC_MASK_ALL, true);
}
}
void AuraEffect::HandleAuraSetVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
Unit* target = aurApp->GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER || !target->IsInWorld())
return;
uint32 vehicleId = GetMiscValue();
if (apply)
{
if (!target->CreateVehicleKit(vehicleId, 0))
return;
}
else if (target->GetVehicleKit())
target->RemoveVehicleKit();
WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, target->GetPackGUID().size()+4);
data.appendPackGUID(target->GetGUID());
data << uint32(apply ? vehicleId : 0);
target->SendMessageToSet(&data, true);
if (apply)
{
data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
target->ToPlayer()->GetSession()->SendPacket(&data);
}
}
void AuraEffect::HandlePreventResurrection(AuraApplication const* aurApp, uint8 mode, bool apply) const
{
if (!(mode & AURA_EFFECT_HANDLE_REAL))
return;
if (aurApp->GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
aurApp->GetTarget()->RemoveByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER);
else
aurApp->GetTarget()->SetByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER);
}
void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const
{
switch (GetSpellInfo()->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
{
switch (GetSpellInfo()->Id)
{
// Frenzied Regeneration
case 22842:
{
// Converts up to 10 rage per second into health for $d. Each point of rage is converted into ${$m2/10}.1% of max health.
// Should be manauser
if (target->getPowerType() != POWER_RAGE)
break;
uint32 rage = target->GetPower(POWER_RAGE);
// Nothing todo
if (rage == 0)
break;
int32 mod = (rage < 100) ? rage : 100;
int32 points = target->CalculateSpellDamage(target, GetSpellInfo(), 1);
int32 regen = target->GetMaxHealth() * (mod * points / 10) / 1000;
target->CastCustomSpell(target, 22845, ®en, 0, 0, true, 0, this);
target->SetPower(POWER_RAGE, rage-mod);
break;
}
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Explosive Shot
if (GetSpellInfo()->SpellFamilyFlags[1] & 0x80000000)
{
if (caster)
caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, NULL, this);
break;
}
switch (GetSpellInfo()->Id)
{
// Feeding Frenzy Rank 1
case 53511:
if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35))
target->CastSpell(target, 60096, true, 0, this);
return;
// Feeding Frenzy Rank 2
case 53512:
if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35))
target->CastSpell(target, 60097, true, 0, this);
return;
default:
break;
}
break;
}
case SPELLFAMILY_SHAMAN:
if (GetId() == 52179) // Astral Shift
{
// Periodic need for remove visual on stun/fear/silence lost
if (!(target->GetUInt32Value(UNIT_FIELD_FLAGS)&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED)))
target->RemoveAurasDueToSpell(52179);
break;
}
break;
case SPELLFAMILY_DEATHKNIGHT:
switch (GetId())
{
case 49016: // Hysteria
uint32 damage = uint32(target->CountPctFromMaxHealth(1));
Unit::DealDamage(target, target, damage, NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
break;
}
// Blood of the North
// Reaping
// Death Rune Mastery
if (GetSpellInfo()->SpellIconID == 3041 || GetSpellInfo()->SpellIconID == 22 || GetSpellInfo()->SpellIconID == 2622)
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (target->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT)
return;
// timer expired - remove death runes
target->ToPlayer()->RemoveRunesByAuraEffect(this);
}
break;
default:
break;
}
}
void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) const
{
// generic casting code with custom spells and target/caster customs
uint32 triggerSpellId = GetSpellInfo()->Effects[GetEffIndex()].TriggerSpell;
SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId);
SpellInfo const* auraSpellInfo = GetSpellInfo();
uint32 auraId = auraSpellInfo->Id;
// specific code for cases with no trigger spell provided in field
if (triggeredSpellInfo == NULL)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (auraId)
{
// Thaumaturgy Channel
case 9712:
triggerSpellId = 21029;
if (caster)
caster->CastSpell(caster, triggerSpellId, true);
return;
// Brood Affliction: Bronze
case 23170:
triggerSpellId = 23171;
break;
// Restoration
case 24379:
case 23493:
{
if (caster)
{
int32 heal = caster->CountPctFromMaxHealth(10);
caster->HealBySpell(target, auraSpellInfo, heal);
if (int32 mana = caster->GetMaxPower(POWER_MANA))
{
mana /= 10;
caster->EnergizeBySpell(caster, 23493, mana, POWER_MANA);
}
}
return;
}
// Nitrous Boost
case 27746:
if (caster && target->GetPower(POWER_MANA) >= 10)
{
target->ModifyPower(POWER_MANA, -10);
target->SendEnergizeSpellLog(caster, 27746, 10, POWER_MANA);
}
else
target->RemoveAurasDueToSpell(27746);
return;
// Frost Blast
case 27808:
if (caster)
{
caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, NULL, this);
if (GetTickNumber() == 1)
caster->CastSpell(target, 27808, true);
}
return;
// Inoculate Nestlewood Owlkin
case 29528:
if (target->GetTypeId() != TYPEID_UNIT) // prevent error reports in case ignored player target
return;
break;
// Feed Captured Animal
case 29917:
triggerSpellId = 29916;
break;
// Extract Gas
case 30427:
{
// move loot to player inventory and despawn target
if (caster && caster->GetTypeId() == TYPEID_PLAYER &&
target->GetTypeId() == TYPEID_UNIT &&
target->ToCreature()->GetCreatureTemplate()->type == CREATURE_TYPE_GAS_CLOUD)
{
Player* player = caster->ToPlayer();
Creature* creature = target->ToCreature();
// missing lootid has been reported on startup - just return
if (!creature->GetCreatureTemplate()->SkinLootId)
return;
player->AutoStoreLoot(creature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, true);
creature->DespawnOrUnsummon();
}
return;
}
// Quake
case 30576:
triggerSpellId = 30571;
break;
// Doom
// TODO: effect trigger spell may be independant on spell targets, and executed in spell finish phase
// so instakill will be naturally done before trigger spell
case 31347:
{
target->CastSpell(target, 31350, true, NULL, this);
Unit::Kill(target, target);
return;
}
// Spellcloth
case 31373:
{
// Summon Elemental after create item
target->SummonCreature(17870, 0, 0, 0, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
return;
}
// Eye of Grillok
case 38495:
triggerSpellId = 38530;
break;
// Absorb Eye of Grillok (Zezzak's Shard)
case 38554:
{
if (!caster || target->GetTypeId() != TYPEID_UNIT)
return;
caster->CastSpell(caster, 38495, true, NULL, this);
Creature* creatureTarget = target->ToCreature();
creatureTarget->DespawnOrUnsummon();
return;
}
// Tear of Azzinoth Summon Channel - it's not really supposed to do anything, and this only prevents the console spam
case 39857:
triggerSpellId = 39856;
break;
// Personalized Weather
case 46736:
triggerSpellId = 46737;
break;
// Shield Level 1
case 63130:
// Shield Level 2
case 63131:
// Shield Level 3
case 63132:
// Ball of Flames Visual
case 71706:
return;
// Oculus, Mage-Lord Urom, Time Bomb
case 51121:
case 59376:
{
const int32 dmg = target->GetMaxHealth()-target->GetHealth();
target->CastCustomSpell(target, 51132, &dmg, 0, 0, true);
return;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (auraId)
{
// Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield)
case 28820:
{
// Need remove self if Lightning Shield not active
if (!target->GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400))
target->RemoveAurasDueToSpell(28820);
return;
}
}
break;
}
default:
break;
}
}
else
{
// Spell exist but require custom code
switch (auraId)
{
// Mana Tide
case 16191:
target->CastCustomSpell(target, triggerSpellId, &m_amount, NULL, NULL, true, NULL, this);
return;
// Poison (Grobbulus)
case 28158:
case 54362:
// Slime Pool (Dreadscale & Acidmaw)
case 66882:
target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)((((float)m_tickNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3), NULL, true, NULL, this);
return;
// Eye of Eternity, Malygos, Arcane Overload
case 56432:
if (triggerSpellId==56438)
{
target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)(10000*(1.0f-0.02f*(m_tickNumber+1))), NULL, true, NULL, this);
return;
}
break;
// Beacon of Light
case 53563:
{
// area aura owner casts the spell
GetBase()->GetUnitOwner()->CastSpell(target, triggeredSpellInfo, true, 0, this, GetBase()->GetUnitOwner()->GetGUID());
return;
}
// Slime Spray - temporary here until preventing default effect works again
// added on 9.10.2010
case 69508:
{
if (caster)
caster->CastSpell(target, triggerSpellId, true, NULL, NULL, caster->GetGUID());
return;
}
// Trial of the Crusader, Jaraxxus, Spinning Pain Spike
case 66283:
{
const int32 dmg = target->GetMaxHealth()/2;
target->CastCustomSpell(target, 66316, &dmg, NULL, NULL, true);
return;
}
// Violet Hold, Moragg, Ray of Suffering, Ray of Pain
case 54442:
case 59524:
case 54438:
case 59523:
{
if (caster)
if (Unit* victim = caster->GetVictim())
if(victim->GetDistance(caster)<45.0f)
{
target = victim;
break;
}
return;
}
// quest A Tangled Skein (12555)
case 51165:
{
if( caster && caster->GetTypeId() == TYPEID_PLAYER )
caster->ToPlayer()->KilledMonsterCredit(28289, 0);
break;
}
case 24745: // Summon Templar, Trigger
case 24747: // Summon Templar Fire, Trigger
case 24757: // Summon Templar Air, Trigger
case 24759: // Summon Templar Earth, Trigger
case 24761: // Summon Templar Water, Trigger
case 24762: // Summon Duke, Trigger
case 24766: // Summon Duke Fire, Trigger
case 24769: // Summon Duke Air, Trigger
case 24771: // Summon Duke Earth, Trigger
case 24773: // Summon Duke Water, Trigger
case 24785: // Summon Royal, Trigger
case 24787: // Summon Royal Fire, Trigger
case 24791: // Summon Royal Air, Trigger
case 24792: // Summon Royal Earth, Trigger
case 24793: // Summon Royal Water, Trigger
{
// All this spells trigger a spell that requires reagents; if the
// triggered spell is cast as "triggered", reagents are not consumed
if (caster)
caster->CastSpell(target, triggerSpellId, false);
return;
}
// Hunter - Rapid Recuperation
case 56654:
case 58882:
int32 amount = int32(target->GetMaxPower(POWER_MANA) * GetAmount() / 100.0f);
target->CastCustomSpell(target, triggerSpellId, &amount, NULL, NULL, true);
return;
}
}
// Reget trigger spell proto
triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId);
if (triggeredSpellInfo)
{
if (Unit* triggerCaster = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo, GetEffIndex()) ? caster : target)
{
SpellCastTargets targets;
targets.SetUnitTarget(target);
if (triggeredSpellInfo->IsChannelCategorySpell() && m_channelData)
{
targets.SetDstChannel(m_channelData->spellDst);
targets.SetObjectTargetChannel(m_channelData->channelGUID);
}
// Xinef: do not skip reagent cost for entry casts
TriggerCastFlags triggerFlags = TRIGGERED_FULL_MASK;
if (GetSpellInfo()->Effects[GetEffIndex()].TargetA.GetCheckType() == TARGET_CHECK_ENTRY || GetSpellInfo()->Effects[GetEffIndex()].TargetB.GetCheckType() == TARGET_CHECK_ENTRY)
triggerFlags = TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST);
triggerCaster->CastSpell(targets, triggeredSpellInfo, NULL, triggerFlags, NULL, this);
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandlePeriodicTriggerSpellAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id);
}
}
}
void AuraEffect::HandlePeriodicTriggerSpellWithValueAuraTick(Unit* target, Unit* caster) const
{
uint32 triggerSpellId = GetSpellInfo()->Effects[m_effIndex].TriggerSpell;
if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId))
{
if (Unit* triggerCaster = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo, GetEffIndex()) ? caster : target)
{
SpellCastTargets targets;
targets.SetUnitTarget(target);
if (triggeredSpellInfo->IsChannelCategorySpell() && m_channelData)
{
targets.SetDstChannel(m_channelData->spellDst);
targets.SetObjectTargetChannel(m_channelData->channelGUID);
}
CustomSpellValues values;
values.AddSpellMod(SPELLVALUE_BASE_POINT0, GetAmount());
triggerCaster->CastSpell(targets, triggeredSpellInfo, &values, TRIGGERED_FULL_MASK, NULL, this);
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandlePeriodicTriggerSpellWithValueAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id);
}
}
else
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS,"AuraEffect::HandlePeriodicTriggerSpellWithValueAuraTick: Spell %u has non-existent spell %u in EffectTriggered[%d] and is therefor not triggered.", GetId(), triggerSpellId, GetEffIndex());
}
void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const
{
if (!target->IsAlive())
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED) || target->IsImmunedToDamageOrSchool(GetSpellInfo()) || target->IsTotem())
{
SendTickImmune(target, caster);
return;
}
// Consecrate ticks can miss and will not show up in the combat log
if (caster && GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE)
return;
// some auras remove at specific health level or more
if (GetAuraType() == SPELL_AURA_PERIODIC_DAMAGE)
{
switch (GetSpellInfo()->Id)
{
case 43093: case 31956: case 38801: // Grievous Wound
case 35321: case 38363: case 39215: // Gushing Wound
if (target->IsFullHealth())
{
target->RemoveAurasDueToSpell(GetSpellInfo()->Id);
return;
}
break;
case 38772: // Grievous Wound
{
uint32 percent = GetSpellInfo()->Effects[EFFECT_1].CalcValue(caster);
if (!target->HealthBelowPct(percent))
{
target->RemoveAurasDueToSpell(GetSpellInfo()->Id);
return;
}
break;
}
}
}
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
// ignore non positive values (can be result apply spellmods to aura damage
uint32 damage = std::max(GetAmount(), 0);
if (GetAuraType() == SPELL_AURA_PERIODIC_DAMAGE)
{
// xinef: leave only target depending bonuses, rest is handled in calculate amount
if (GetBase()->GetType() == DYNOBJ_AURA_TYPE)
damage = caster->SpellDamageBonusDone(target, GetSpellInfo(), damage, DOT, 0.0f, GetBase()->GetStackAmount());
damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount());
// Calculate armor mitigation
if (Unit::IsDamageReducedByArmor(GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), GetEffIndex()))
{
uint32 damageReductedArmor = Unit::CalcArmorReducedDamage(caster, target, damage, GetSpellInfo(), GetCasterLevel());
cleanDamage.mitigated_damage += damage - damageReductedArmor;
damage = damageReductedArmor;
}
// Curse of Agony damage-per-tick calculation
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARLOCK && (GetSpellInfo()->SpellFamilyFlags[0] & 0x400) && GetSpellInfo()->SpellIconID == 544)
{
uint32 totalTick = GetTotalTicks();
// 1..4 ticks, 1/2 from normal tick damage
if (m_tickNumber <= totalTick / 3)
damage = damage/2;
// 9..12 ticks, 3/2 from normal tick damage
else if (m_tickNumber > totalTick * 2 / 3)
damage += (damage+1)/2; // +1 prevent 0.5 damage possible lost at 1..4 ticks
// 5..8 ticks have normal tick damage
}
// There is a Chance to make a Soul Shard when Drain soul does damage
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARLOCK && (GetSpellInfo()->SpellFamilyFlags[0] & 0x00004000))
{
if (caster && caster->GetTypeId() == TYPEID_PLAYER && caster->ToPlayer()->isHonorOrXPTarget(target))
{
if (roll_chance_i(20))
{
caster->CastSpell(caster, 43836, true, 0, this);
// Glyph of Drain Soul - chance to create an additional Soul Shard
if (AuraEffect* aur = caster->GetAuraEffect(58070, 0))
if (roll_chance_i(aur->GetMiscValue()))
caster->CastSpell(caster, 58068, true, 0, aur);
}
}
}
}
else // xinef: ceil obtained value, it may happen that 10 ticks for 10% damage may not kill owner
damage = uint32(ceil(CalculatePct<float, float>(target->GetMaxHealth(), damage)));
// calculate crit chance
bool crit = false;
if (crit = roll_chance_f(GetCritChance()))
damage = Unit::SpellCriticalDamageBonus(caster, m_spellInfo, damage, target);
int32 dmg = damage;
if (CanApplyResilience())
Unit::ApplyResilience(target, NULL, &dmg, crit, CR_CRIT_TAKEN_SPELL);
damage = dmg;
Unit::CalcAbsorbResist(caster, target, GetSpellInfo()->GetSchoolMask(), DOT, damage, &absorb, &resist, GetSpellInfo());
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) attacked %u (TypeId: %u) for %u dmg inflicted by %u abs is %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb);
Unit::DealDamageMods(target, damage, &absorb);
// Auras reducing damage from AOE spells
if (GetSpellInfo()->Effects[GetEffIndex()].IsAreaAuraEffect() || GetSpellInfo()->Effects[GetEffIndex()].IsTargetingArea() || GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA) // some persistent area auras have targets like A=53 B=28
{
damage = target->CalculateAOEDamageReduction(damage, GetSpellInfo()->SchoolMask, caster);
}
// Set trigger flag
uint32 procAttacker = PROC_FLAG_DONE_PERIODIC;
uint32 procVictim = PROC_FLAG_TAKEN_PERIODIC;
uint32 procEx = (crit ? PROC_EX_CRITICAL_HIT : PROC_EX_NORMAL_HIT) | PROC_EX_INTERNAL_DOT;
if (absorb > 0)
procEx |= PROC_EX_ABSORB;
damage = (damage <= absorb+resist) ? 0 : (damage-absorb-resist);
if (damage)
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
int32 overkill = damage - target->GetHealth();
if (overkill < 0)
overkill = 0;
SpellPeriodicAuraLogInfo pInfo(this, damage, overkill, absorb, resist, 0.0f, crit);
target->SendPeriodicAuraLog(&pInfo);
Unit::DealDamage(caster, target, damage, &cleanDamage, DOT, GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), true);
// allow null caster to call this function
caster->ProcDamageAndSpell(target, caster ? procAttacker : 0, procVictim, procEx, damage, BASE_ATTACK, GetSpellInfo());
}
void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) const
{
if (!target->IsAlive())
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED) || target->IsImmunedToDamageOrSchool(GetSpellInfo()))
{
SendTickImmune(target, caster);
return;
}
if (caster && GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE)
return;
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
uint32 damage = std::max(GetAmount(), 0);
if (GetBase()->GetType() == DYNOBJ_AURA_TYPE)
damage = caster->SpellDamageBonusDone(target, GetSpellInfo(), damage, DOT, 0.0f, GetBase()->GetStackAmount());
damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount());
bool crit = false;
if (crit = roll_chance_f(GetCritChance()))
damage = Unit::SpellCriticalDamageBonus(caster, m_spellInfo, damage, target);
// Calculate armor mitigation
if (Unit::IsDamageReducedByArmor(GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), m_effIndex))
{
uint32 damageReductedArmor = Unit::CalcArmorReducedDamage(caster, target, damage, GetSpellInfo(), GetCasterLevel());
cleanDamage.mitigated_damage += damage - damageReductedArmor;
damage = damageReductedArmor;
}
int32 dmg = damage;
if (CanApplyResilience())
Unit::ApplyResilience(target, NULL, &dmg, crit, CR_CRIT_TAKEN_SPELL);
damage = dmg;
Unit::CalcAbsorbResist(caster, target, GetSpellInfo()->GetSchoolMask(), DOT, damage, &absorb, &resist, m_spellInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_DONE_PERIODIC;
uint32 procVictim = PROC_FLAG_TAKEN_PERIODIC;
uint32 procEx = (crit ? PROC_EX_CRITICAL_HIT : PROC_EX_NORMAL_HIT) | PROC_EX_INTERNAL_DOT;
if (absorb > 0)
procEx |= PROC_EX_ABSORB;
damage = (damage <= absorb+resist) ? 0 : (damage-absorb-resist);
if (damage)
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
if (target->GetHealth() < damage)
damage = target->GetHealth();
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) health leech of %u (TypeId: %u) for %u dmg inflicted by %u abs is %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb);
if (caster)
caster->SendSpellNonMeleeDamageLog(target, GetId(), damage+absorb+resist, GetSpellInfo()->GetSchoolMask(), absorb, resist, false, 0, crit);
int32 new_damage;
new_damage = Unit::DealDamage(caster, target, damage, &cleanDamage, DOT, GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), false);
// allow null caster to call this function
caster->ProcDamageAndSpell(target, caster ? procAttacker : 0, procVictim, procEx, damage, BASE_ATTACK, GetSpellInfo());
if (!caster || !caster->IsAlive())
return;
float gainMultiplier = GetSpellInfo()->Effects[GetEffIndex()].CalcValueMultiplier(caster);
uint32 heal = uint32(caster->SpellHealingBonusDone(caster, GetSpellInfo(), uint32(new_damage * gainMultiplier), DOT, 0.0f, GetBase()->GetStackAmount()));
heal = uint32(caster->SpellHealingBonusTaken(caster, GetSpellInfo(), heal, DOT, GetBase()->GetStackAmount()));
int32 gain = caster->HealBySpell(caster, GetSpellInfo(), heal);
caster->getHostileRefManager().threatAssist(caster, gain * 0.5f, GetSpellInfo());
}
void AuraEffect::HandlePeriodicHealthFunnelAuraTick(Unit* target, Unit* caster) const
{
if (!caster || !caster->IsAlive() || !target->IsAlive())
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED))
{
SendTickImmune(target, caster);
return;
}
uint32 damage = std::max(GetAmount(), 0);
// do not kill health donator
if (caster->GetHealth() < damage)
damage = caster->GetHealth() - 1;
if (!damage)
return;
caster->ModifyHealth(-(int32)damage);
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "PeriodicTick: donator %u target %u damage %u.", caster->GetEntry(), target->GetEntry(), damage);
float gainMultiplier = GetSpellInfo()->Effects[GetEffIndex()].CalcValueMultiplier(caster);
damage = int32(damage * gainMultiplier);
caster->HealBySpell(target, GetSpellInfo(), damage);
}
void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const
{
if (!target->IsAlive())
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED))
{
SendTickImmune(target, caster);
return;
}
// heal for caster damage (must be alive)
if (target != caster && GetSpellInfo()->HasAttribute(SPELL_ATTR2_HEALTH_FUNNEL) && (!caster || !caster->IsAlive()))
return;
// don't regen when permanent aura target has full power
if (GetBase()->IsPermanent() && target->IsFullHealth())
return;
// ignore negative values (can be result apply spellmods to aura damage
int32 damage = std::max(m_amount, 0);
if (GetAuraType() == SPELL_AURA_OBS_MOD_HEALTH)
{
// Taken mods
float TakenTotalMod = 1.0f;
// Tenacity increase healing % taken
if (AuraEffect const* Tenacity = target->GetAuraEffect(58549, 0))
AddPct(TakenTotalMod, Tenacity->GetAmount());
// Healing taken percent
float minval = (float)target->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
if (minval)
AddPct(TakenTotalMod, minval);
float maxval = (float)target->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
if (maxval)
AddPct(TakenTotalMod, maxval);
// Healing over time taken percent
float minval_hot = (float)target->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT);
if (minval_hot)
AddPct(TakenTotalMod, minval_hot);
float maxval_hot = (float)target->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT);
if (maxval_hot)
AddPct(TakenTotalMod, maxval_hot);
// Arena / BG Dampening
float minval_pct = (float)target->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
if (minval_pct)
AddPct(TakenTotalMod, minval_pct);
TakenTotalMod = std::max(TakenTotalMod, 0.0f);
// the most ugly hack i made :P the other option is to change all spellvalues to float...
// demonic aegis
if (caster && GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARLOCK && (GetSpellInfo()->SpellFamilyFlags[1] & 0x20000000))
if (AuraEffect *aurEff = caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_WARLOCK, 89, 0))
AddPct(TakenTotalMod, aurEff->GetAmount());
damage = uint32(target->CountPctFromMaxHealth(damage));
damage = uint32(damage * TakenTotalMod);
}
else
{
// Wild Growth = amount + (6 - 2*doneTicks) * ticks* amount / 100
if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID && GetSpellInfo()->SpellIconID == 2864)
{
uint32 tickNumber = GetTickNumber()-1;
int32 tempAmount = m_spellInfo->Effects[m_effIndex].CalcValue(caster, &m_baseAmount, NULL);
float drop = 2.0f;
// Item - Druid T10 Restoration 2P Bonus
if (caster)
if (AuraEffect* aurEff = caster->GetAuraEffect(70658, 0))
AddPct(drop, -aurEff->GetAmount());
damage += GetTotalTicks() * tempAmount * (6-(drop*tickNumber)) * 0.01f;
}
if (GetBase()->GetType() == DYNOBJ_AURA_TYPE)
damage = caster->SpellHealingBonusDone(target, GetSpellInfo(), damage, DOT, 0.0f, GetBase()->GetStackAmount());
damage = target->SpellHealingBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount());
}
bool crit = false;
if (crit = roll_chance_f(GetCritChance()))
damage = Unit::SpellCriticalHealingBonus(caster, GetSpellInfo(), damage, target);
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) heal of %u (TypeId: %u) for %u health inflicted by %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId());
uint32 absorb = 0;
uint32 heal = uint32(damage);
Unit::CalcHealAbsorb(target, GetSpellInfo(), heal, absorb);
int32 gain = Unit::DealHeal(caster, target, heal);
SpellPeriodicAuraLogInfo pInfo(this, heal, heal - gain, absorb, 0, 0.0f, crit);
target->SendPeriodicAuraLog(&pInfo);
if (caster)
target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, GetSpellInfo());
bool haveCastItem = GetBase()->GetCastItemGUID() != 0;
// Health Funnel
// damage caster for heal amount
// xinef: caster is available, checked earlier
if (target != caster && GetSpellInfo()->HasAttribute(SPELL_ATTR2_HEALTH_FUNNEL))
{
uint32 damage = GetSpellInfo()->ManaPerSecond;
if ((int32)damage > gain && gain > 0)
damage = gain;
uint32 absorb = 0;
Unit::DealDamageMods(caster, damage, &absorb);
CleanDamage cleanDamage = CleanDamage(0, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
Unit::DealDamage(caster, caster, damage, &cleanDamage, SELF_DAMAGE, GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), true);
}
uint32 procAttacker = PROC_FLAG_DONE_PERIODIC;
uint32 procVictim = PROC_FLAG_TAKEN_PERIODIC;
uint32 procEx = (crit ? PROC_EX_CRITICAL_HIT : PROC_EX_NORMAL_HIT) | PROC_EX_INTERNAL_HOT;
if (absorb > 0)
procEx |= PROC_EX_ABSORB;
// ignore item heals
if (!haveCastItem && GetAuraType() != SPELL_AURA_OBS_MOD_HEALTH) // xinef: dont allow obs_mod_health to proc spells, this is passive regeneration and not hot
// xinef: allow null caster to proc
caster->ProcDamageAndSpell(target, caster ? procAttacker : 0, procVictim, procEx, damage, BASE_ATTACK, GetSpellInfo());
}
void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) const
{
Powers powerType = Powers(GetMiscValue());
if (!caster || !caster->IsAlive() || !target->IsAlive() || target->getPowerType() != powerType)
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED) || target->IsImmunedToDamageOrSchool(GetSpellInfo()))
{
SendTickImmune(target, caster);
return;
}
if (GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE)
return;
// ignore negative values (can be result apply spellmods to aura damage
int32 drainAmount = std::max(m_amount, 0);
// Special case: draining x% of mana (up to a maximum of 2*x% of the caster's maximum mana)
// It's mana percent cost spells, m_amount is percent drain from target
if (m_spellInfo->ManaCostPercentage)
{
// max value
int32 maxmana = CalculatePct(caster->GetMaxPower(powerType), drainAmount * 2.0f);
ApplyPct(drainAmount, target->GetMaxPower(powerType));
if (drainAmount > maxmana)
drainAmount = maxmana;
}
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) power leech of %u (TypeId: %u) for %u dmg inflicted by %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), drainAmount, GetId());
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (powerType == POWER_MANA)
drainAmount -= target->GetSpellCritDamageReduction(drainAmount);
int32 drainedAmount = -target->ModifyPower(powerType, -drainAmount);
float gainMultiplier = GetSpellInfo()->Effects[GetEffIndex()].CalcValueMultiplier(caster);
SpellPeriodicAuraLogInfo pInfo(this, drainedAmount, 0, 0, 0, gainMultiplier, false);
target->SendPeriodicAuraLog(&pInfo);
int32 gainAmount = int32(drainedAmount * gainMultiplier);
int32 gainedAmount = 0;
if (gainAmount)
{
gainedAmount = caster->ModifyPower(powerType, gainAmount);
target->AddThreat(caster, float(gainedAmount) * 0.5f, GetSpellInfo()->GetSchoolMask(), GetSpellInfo());
}
target->AddThreat(caster, float(gainedAmount) * 0.5f, GetSpellInfo()->GetSchoolMask(), GetSpellInfo());
// remove CC auras
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE);
// Drain Mana
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK
&& m_spellInfo->SpellFamilyFlags[0] & 0x00000010)
{
int32 manaFeedVal = 0;
if (AuraEffect const* aurEff = GetBase()->GetEffect(1))
manaFeedVal = aurEff->GetAmount();
// Mana Feed - Drain Mana
if (manaFeedVal > 0)
{
int32 feedAmount = CalculatePct(gainedAmount, manaFeedVal);
caster->CastCustomSpell(caster, 32554, &feedAmount, NULL, NULL, true, NULL, this);
}
}
}
void AuraEffect::HandleObsModPowerAuraTick(Unit* target, Unit* caster) const
{
Powers powerType;
if (GetMiscValue() == POWER_ALL)
powerType = target->getPowerType();
else
powerType = Powers(GetMiscValue());
if (!target->IsAlive() || !target->GetMaxPower(powerType))
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED))
{
SendTickImmune(target, caster);
return;
}
// don't regen when permanent aura target has full power
if (GetBase()->IsPermanent() && target->GetPower(powerType) == target->GetMaxPower(powerType))
return;
// ignore negative values (can be result apply spellmods to aura damage
uint32 amount = std::max(m_amount, 0) * target->GetMaxPower(powerType) /100;
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) energize %u (TypeId: %u) for %u dmg inflicted by %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId());
SpellPeriodicAuraLogInfo pInfo(this, amount, 0, 0, 0, 0.0f, false);
target->SendPeriodicAuraLog(&pInfo);
int32 gain = target->ModifyPower(powerType, amount);
if (caster)
target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, GetSpellInfo());
}
void AuraEffect::HandlePeriodicEnergizeAuraTick(Unit* target, Unit* caster) const
{
Powers powerType = Powers(GetMiscValue());
if (target->GetTypeId() == TYPEID_PLAYER && target->getPowerType() != powerType && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER))
return;
if (!target->IsAlive() || !target->GetMaxPower(powerType))
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED))
{
SendTickImmune(target, caster);
return;
}
// don't regen when permanent aura target has full power
if (GetBase()->IsPermanent() && target->GetPower(powerType) == target->GetMaxPower(powerType))
return;
// ignore negative values (can be result apply spellmods to aura damage
int32 amount = std::max(m_amount, 0);
SpellPeriodicAuraLogInfo pInfo(this, amount, 0, 0, 0, 0.0f, false);
target->SendPeriodicAuraLog(&pInfo);
;//sLog->outDetail("PeriodicTick: %u (TypeId: %u) energize %u (TypeId: %u) for %u dmg inflicted by %u",
// GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId());
int32 gain = target->ModifyPower(powerType, amount);
if (caster)
target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, GetSpellInfo());
}
void AuraEffect::HandlePeriodicPowerBurnAuraTick(Unit* target, Unit* caster) const
{
Powers powerType = Powers(GetMiscValue());
if (!caster || !target->IsAlive() || target->getPowerType() != powerType)
return;
if (target->HasUnitState(UNIT_STATE_ISOLATED) || target->IsImmunedToDamageOrSchool(GetSpellInfo()))
{
SendTickImmune(target, caster);
return;
}
// ignore negative values (can be result apply spellmods to aura damage
int32 damage = std::max(m_amount, 0);
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (powerType == POWER_MANA)
damage -= target->GetSpellCritDamageReduction(damage);
uint32 gain = uint32(-target->ModifyPower(powerType, -damage));
float dmgMultiplier = GetSpellInfo()->Effects[GetEffIndex()].CalcValueMultiplier(caster);
SpellInfo const* spellProto = GetSpellInfo();
// maybe has to be sent different to client, but not by SMSG_PERIODICAURALOG
SpellNonMeleeDamage damageInfo(caster, target, spellProto->Id, spellProto->SchoolMask);
// no SpellDamageBonus for burn mana
caster->CalculateSpellDamageTaken(&damageInfo, int32(gain * dmgMultiplier), spellProto);
Unit::DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
caster->SendSpellNonMeleeDamageLog(&damageInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_DONE_PERIODIC;
uint32 procVictim = PROC_FLAG_TAKEN_PERIODIC;
uint32 procEx = createProcExtendMask(&damageInfo, SPELL_MISS_NONE) | PROC_EX_INTERNAL_DOT;
if (damageInfo.damage)
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
caster->DealSpellDamage(&damageInfo, true);
caster->ProcDamageAndSpell(damageInfo.target, procAttacker, procVictim, procEx, damageInfo.damage, BASE_ATTACK, spellProto);
}
void AuraEffect::HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo)
{
Unit* triggerCaster = aurApp->GetTarget();
Unit* triggerTarget = eventInfo.GetProcTarget();
uint32 triggerSpellId = GetSpellInfo()->Effects[GetEffIndex()].TriggerSpell;
if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId))
{
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleProcTriggerSpellAuraProc: Triggering spell %u from aura %u proc", triggeredSpellInfo->Id, GetId());
triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this);
}
else
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS,"AuraEffect::HandleProcTriggerSpellAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId());
}
void AuraEffect::HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo)
{
Unit* triggerCaster = aurApp->GetTarget();
Unit* triggerTarget = eventInfo.GetProcTarget();
uint32 triggerSpellId = GetSpellInfo()->Effects[m_effIndex].TriggerSpell;
if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId))
{
int32 basepoints0 = GetAmount();
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Triggering spell %u with value %d from aura %u proc", triggeredSpellInfo->Id, basepoints0, GetId());
triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, NULL, NULL, true, NULL, this);
}
else
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS,"AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId());
}
void AuraEffect::HandleProcTriggerDamageAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo)
{
Unit* target = aurApp->GetTarget();
Unit* triggerTarget = eventInfo.GetProcTarget();
SpellNonMeleeDamage damageInfo(target, triggerTarget, GetId(), GetSpellInfo()->SchoolMask);
uint32 damage = target->SpellDamageBonusDone(triggerTarget, GetSpellInfo(), GetAmount(), SPELL_DIRECT_DAMAGE);
damage = triggerTarget->SpellDamageBonusTaken(target, GetSpellInfo(), damage, SPELL_DIRECT_DAMAGE);
target->CalculateSpellDamageTaken(&damageInfo, damage, GetSpellInfo());
Unit::DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
target->SendSpellNonMeleeDamageLog(&damageInfo);
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleProcTriggerDamageAuraProc: Triggering %u spell damage from aura %u proc", damage, GetId());
target->DealSpellDamage(&damageInfo, true);
}
void AuraEffect::HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcEventInfo& /*eventInfo*/)
{
Unit* target = aurApp->GetTarget();
uint32 triggerSpellId;
switch (GetId())
{
case 57949: // Shiver
triggerSpellId = 57952;
//animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637)
break;
case 59978: // Shiver
triggerSpellId = 59979;
break;
case 43593: // Cold Stare
triggerSpellId = 43594;
break;
default:
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleRaidProcFromChargeAuraProc: received not handled spell: %u", GetId());
return;
}
int32 jumps = GetBase()->GetCharges();
// current aura expire on proc finish
GetBase()->SetCharges(0);
GetBase()->SetUsingCharges(true);
// next target selection
if (jumps > 0)
{
if (Unit* caster = GetCaster())
{
float radius = GetSpellInfo()->Effects[GetEffIndex()].CalcRadius(caster);
if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius))
{
target->CastSpell(triggerTarget, GetSpellInfo(), true, NULL, this, GetCasterGUID());
if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID()))
aura->SetCharges(jumps);
}
}
}
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleRaidProcFromChargeAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId());
target->CastSpell(target, triggerSpellId, true, NULL, this, GetCasterGUID());
}
void AuraEffect::HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& /*eventInfo*/)
{
Unit* target = aurApp->GetTarget();
// Currently only Prayer of Mending
if (!(GetSpellInfo()->SpellFamilyName == SPELLFAMILY_PRIEST && GetSpellInfo()->SpellFamilyFlags[1] & 0x20))
{
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleRaidProcFromChargeWithValueAuraProc: received not handled spell: %u", GetId());
return;
}
uint32 triggerSpellId = 33110;
int32 value = GetAmount();
int32 jumps = GetBase()->GetCharges();
// current aura expire on proc finish
GetBase()->SetCharges(0);
GetBase()->SetUsingCharges(true);
// next target selection
if (jumps > 0)
{
if (Unit* caster = GetCaster())
{
float radius = GetSpellInfo()->Effects[GetEffIndex()].CalcRadius(caster);
if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius))
{
target->CastCustomSpell(triggerTarget, GetId(), &value, NULL, NULL, true, NULL, this, GetCasterGUID());
if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID()))
aura->SetCharges(jumps);
}
}
}
;//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleRaidProcFromChargeWithValueAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId());
target->CastCustomSpell(target, triggerSpellId, &value, NULL, NULL, true, NULL, this, GetCasterGUID());
}
| [
"maczugapl@gmail.com"
] | maczugapl@gmail.com |
ff5834611fc19eb6547757772eb5c0d55f2e433f | a6daa0878f8003298a4fe6d07d16c838f27c1881 | /Dynamic Programming/Ladders Problem/Bottom Up Approach.cpp | aadf6500c654212d57eccce72e610c87c6def438 | [
"MIT"
] | permissive | NikhilRajPandey/Fork_CPP | e3f812f1a3a889dfbd7dbafa9cc49c9813944909 | 898877598e796c33266ea54a29ce6a220eb6b268 | refs/heads/main | 2023-08-12T09:12:37.534894 | 2021-10-18T10:45:43 | 2021-10-18T10:45:43 | 418,815,923 | 1 | 0 | MIT | 2021-10-19T07:26:25 | 2021-10-19T07:26:24 | null | UTF-8 | C++ | false | false | 432 | cpp | #include<iostream>
using namespace std;
// ladder bottom up
int ladders_bottomup(int n, int k){
int dp[100] = {0};
dp[0] = 1; // start case
for(int i = 1; i<=n; i++){
dp[i]=0;
for(int j=1;j<=k;j++){
if(i-j>=0){
dp[i] += dp[i-j];
}
}
}
return dp[n];
}
int main(){
int n,k;
cin>>n>>k;
cout<<ladders_bottomup(n,k)<<endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
dee97aa693013c4a1461aa09534a3a87a184f969 | 4256d6baeb1cb20185cf7bced1fd6217d025f0f6 | /Graph/Floyd_BitSet.cpp | a0af281ba9a6ccbdc97db8bc6971af7e89b350db | [] | no_license | SKYSCRAPERS1999/ACM-Templates | a026206d574bcf5725794a659b51ca36783241a3 | fbaf73f947ddf7e6a2ca44a6cb383cdffef7c1bd | refs/heads/master | 2020-03-31T17:23:56.151340 | 2018-11-22T04:43:02 | 2018-11-22T04:43:02 | 152,172,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | cpp | const int maxn = 2016 + 1;
int N, M, T;
bitset<maxn> bit[maxn];
void floyd(){
for (int k = 0; k < N; k++){
for (int i = 0; i < N; i++){
if (bit[i][k]) bit[i] = bit[i] | bit[k];
}
}
}
| [
"386333667@qq.com"
] | 386333667@qq.com |
e3d16f19253ecc5c4c311b9e7a724a5f5de494c2 | 162fe1fb4322a6337ab8a0b40d53de400c3a6fda | /deck.h | 161803dee297092185111aa7a46de33f2a954b68 | [] | no_license | leevictor81/sorcery | bc92e55a19a127cb9169368c41c29f5a27f59563 | be68d2939684949260a8f6852e33fcd5429e9709 | refs/heads/master | 2020-03-28T13:40:06.373636 | 2019-05-13T05:08:11 | 2019-05-13T05:09:30 | 148,416,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | h | #ifndef __DECK_H__
#define __DECK_H__
#include <string>
#include <vector>
class Deck {
std::vector<std::string> deck;
int numOfCards;
public:
Deck();
~Deck();
std::string draw();
void shuffle();
void putToBottom(std::string cardName);
int size() const;
};
#endif
| [
"leevictor81@hotmail.com"
] | leevictor81@hotmail.com |
b5a75290248ca2b0f6d1f4257306dc34617cc295 | 7f1c89b14e5023e02d71584254af3f872889a239 | /grader/same_tree_package/tree.h | dd2c3fa1480c426a2ae7806d45b7d9c30b98a435 | [] | no_license | karnkittik/cplusplus | e863e645533ad0a65cdc1030dd8a0d6ec6b5afd8 | f5c4ad7fbca6e1f88bfdaab841e6f2b0046911df | refs/heads/master | 2020-03-29T06:49:22.317706 | 2018-12-12T14:32:18 | 2018-12-12T14:32:18 | 149,639,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,016 | h | #ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
#define NULL __null
class Tree
{
class Node
{
public:
friend class Tree;
Node()
{
data = -1;
left = NULL;
right = NULL;
}
Node(const int x, Node *left, Node *right) : data(x), left(left), right(right) {}
protected:
int data;
Node *left;
Node *right;
};
public:
Tree()
{
mRoot = NULL;
mSize = 0;
}
~Tree()
{
clear(mRoot);
}
void clear(Node *&r)
{
if (!r)
return;
clear(r->left);
clear(r->right);
delete r;
}
void insert(int x)
{
insertAt(mRoot, x);
}
int num(Node *&n)
{
//none 0 left 1 right 2 both 3
if (n->left == NULL && n->right == NULL)
return 0;
if (n->left != NULL && n->right != NULL)
return 3;
if (n->left != NULL && n->right == NULL)
return 1;
if (n->left == NULL && n->right != NULL)
return 2;
}
bool isSameBinaryTree(Tree &t)
{
return recursive(mRoot, t.mRoot);
}
bool recursive(Node *&s, Node *&t)
{
if (s == NULL && t == NULL)
return true;
if (s == NULL || t == NULL)
return false;
if (s->data != t->data)
return false;
return recursive(s->left, t->left) && recursive(s->right, t->right);
}
protected:
void insertAt(Node *&r, int x)
{
if (!r)
{
r = new Node(x, NULL, NULL);
mSize++;
return;
}
if (r->data == x)
return; // Do nothing
if (x < r->data)
insertAt(r->left, x);
else
insertAt(r->right, x);
}
Node *mRoot;
int mSize;
};
#endif // TREE_H_INCLUDED
| [
"karnkitti_tang@hotmail.com"
] | karnkitti_tang@hotmail.com |
951b8d30086df454271b4e7e8422f288ab88b0b2 | 16a3507ec06282ef028bac1d971314c1a330631d | /include/ellipsoids_markers.hpp | a418402e13f9bf757aff346d4a2c0f40591e3891 | [] | no_license | jmainpri/octomap_to_ellipsoids | 04f866b600da25e93b8d2d22b79b0920cb1d39a6 | 0ac286bdd2705b1ff8fabcf7c765c47a88b9f6d9 | refs/heads/master | 2016-09-06T02:23:17.558304 | 2015-03-26T10:23:46 | 2015-03-26T10:23:46 | 32,920,451 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,197 | hpp | /*
* Copyright (c) 2010-2014 LAAS/CNRS, WPI
* 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 and this list of conditions.
* 2. Redistributions in binary form must reproduce the above copyright
* notice and this list of conditions in the documentation and/or
* other materials provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Siméon, T., Laumond, J. P., & Lamiraux, F. (2001).
* Move3d: A generic platform for path planning. In in 4th Int. Symp.
* on Assembly and Task Planning.
*
* Jim Mainprice Tue 27 May 2014
*/
#ifndef ELLIPSOIDS_MARKERS_HPP
#define ELLIPSOIDS_MARKERS_HPP
// Warning
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
#include <Eigen/Core>
#include <visualization_msgs/Marker.h>
#include <string>
class EllipsoidsToMarkers
{
public:
EllipsoidsToMarkers();
~EllipsoidsToMarkers();
visualization_msgs::Marker pointcloudMarker(int id, const pcl::PointCloud<pcl::PointXYZ>& cloud );
visualization_msgs::Marker vectorMarker( int id, const Eigen::Vector3d& vector, const Eigen::Vector3d& position );
visualization_msgs::Marker ellipsoidMarker( int& id, const Eigen::Vector3d& mean, const Eigen::Matrix3d& covariance, std::vector<visualization_msgs::Marker>& eigen_vectors );
std::string frame_id_;
tf::TransformBroadcaster br_;
};
#endif
| [
"jmainpri@Mondrian.(none)"
] | jmainpri@Mondrian.(none) |
e1f3bbd412721690e0141a9c6dd17329457b7593 | 25a8d2cbaff5bca2a2389206628ec3a8ea5edfa4 | /DP/1025 - The Specials Menu [Ways of making palindrome].cpp | 30e6f33f63765cde9886189cdb892e27b8a2a410 | [] | no_license | Fazle-Rabby-Sourav/Light-Online-Judge-Solutions | 2d46a7bc119e89430e48b484b2d6d1c302f0c173 | f4a6ec42b3924bc0a78725ed9b2b3cf551899337 | refs/heads/master | 2020-04-02T07:52:48.381578 | 2019-08-14T11:16:05 | 2019-08-14T11:16:05 | 154,218,678 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | cpp | #include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <list>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define clean(a,b) memset(a,b,sizeof(a))
#define oo 1<<20
#define dd double
#define ll long long
#define ull unsigned long long
#define ff float
#define EPS 10E-5
#define fr first
#define sc second
#define MAXX 100000
#define PRIME_N 1000000
#define PI (2*acos(0))
#define INFI 1<<30
#define SZ(a) ((int)a.size())
#define all(a) a.begin(),a.end()
//int rx[] = {0,-1,0,1,1,-1,-1,0,1}; //four direction x
//int ry[] = {0,1,1,1,0,0,-1,-1,-1 //four direction y
//int rep[] = {1,1,4,4,2,1,1,4,4,2}; //repet cycle for mod
//void ullpr(){printf("range unsigned long long : %llu\n",-1U);} //for ull
//void ulpr(){printf("range unsigned long : %lu\n",-1U);} //for ull
//void upr(){printf("range unsigned : %u\n",-1U);} //for ull
ll dp[70][70][3];
char str[1000];
ll rec(ll st,ll ed,ll state)
{
if(st>ed) return state;
if(dp[st][ed][state]!=-1) return dp[st][ed][state];
dp[st][ed][state]= 0;
if(str[st]==str[ed])
{
dp[st][ed][state] += rec(st+1,ed-1,1);
}
dp[st][ed][state] += rec(st+1,ed,state);
dp[st][ed][state] += rec(st,ed-1,state);
dp[st][ed][state] -= rec(st+1,ed-1,state);
return dp[st][ed][state];
}
int main()
{
ll tcase,cas=1;
scanf(" %lld",&tcase);
while(tcase--)
{
scanf(" %s",str);
clean(dp,-1);
ll ans = rec(0,strlen(str)-1,0);
printf("Case %lld: %lld\n",cas++,ans);
}
return 0;
}
| [
"sourav.sust.cse.10@gmail.com"
] | sourav.sust.cse.10@gmail.com |
ab15e92d568ae54ff64c7513842e880caaaedf2c | bd84d3479fe53e36c920eab6737ee910992adf16 | /31_final_project/src/node.h | 87ef823328ec0dcdcc3e0d452de5e093893ffb6f | [] | no_license | bao-eng/cpp_yellow_belt | 85e7603eb45bb530fcb4a0f3c541137a14011ca8 | d01d3c77dd245f796fb99d2d543fd8931cc075a2 | refs/heads/master | 2020-09-03T21:50:28.324369 | 2019-12-22T20:14:17 | 2019-12-22T20:14:17 | 219,579,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | h | #pragma once
#include <string>
#include <memory>
#include "date.h"
using namespace std;
enum class Comparison {
Less,
LessOrEqual,
Greater,
GreaterOrEqual,
Equal,
NotEqual,
};
enum class LogicalOperation{
And,
Or,
};
class Node{
public:
virtual bool Evaluate(const Date& date, const string& str) const=0;
};
class EmptyNode : public Node{
public:
bool Evaluate(const Date& date, const string& str) const override;
};
class DateComparisonNode : public Node{
public:
DateComparisonNode(const Comparison& cmp, const Date& date);
bool Evaluate(const Date& date, const string& str) const override;
private:
Comparison cmp_;
Date date_;
};
class EventComparisonNode : public Node{
public:
EventComparisonNode(const Comparison& cmp, string str);
bool Evaluate(const Date& date, const string& str) const override;
private:
Comparison cmp_;
string str_;
};
class LogicalOperationNode : public Node{
public:
LogicalOperationNode(const LogicalOperation& operation, shared_ptr<Node> left, shared_ptr<Node> right);
bool Evaluate(const Date& date, const string& str) const override;
private:
LogicalOperation operation_;
shared_ptr<Node> left_;
shared_ptr<Node> right_;
};
| [
"engineer.basov@gmail.com"
] | engineer.basov@gmail.com |
f0642eb41d982cf378546b39f48310c985bf9584 | 919a732592a070878017021eee890ac412077be4 | /uva/uva11559.cpp | 732eb1060f4c239c49da5da97e27e9ee98e1a4ae | [] | no_license | abdallahmahran10/programming_problems | 77adb7e928bc8925de158e0109e86a79c4d863ae | 3a3dcf564ae8c9b771314be12c472e2f66d6a95a | refs/heads/master | 2020-05-21T23:59:52.101382 | 2019-03-12T04:13:40 | 2019-03-12T04:14:58 | 59,847,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | #include "common.h" // my defined macros
int uva11559()
{
int N, budget, H, w, k,bedPrice,bedCount,price;
//scanf("%d", &k);
const int max = 200 * 500000;
int minCost;
while (scanf("%d %d %d %d", &N, &budget, &H, &w) != EOF)
{
minCost = max;
for(int hotelIdx=0; hotelIdx < H; hotelIdx++)
{
scanf("%d", &bedPrice );
for(int weekIdx = 0; weekIdx < w; weekIdx++)
{
scanf("%d", &bedCount);
if(bedCount>=N)
{
price = N*bedPrice;
if(price< minCost)
minCost = price;
}
}
}
if (minCost != max && minCost <= budget)
printf("%d\n", minCost);
else
printf("stay home\n");
}
return 0;
}
| [
"eng.abdallah.mahran@gmail.com"
] | eng.abdallah.mahran@gmail.com |
4da536d6a0b9aaeff4377d50bf4d43af11b01bb9 | 40d1aa62d5391715b599acd9d05c419d55cd140e | /pointer/aliasing_effect.cpp | ef21c9b3bff2a2c1eff7c2ff90c5e10063204fa7 | [] | no_license | winnygold/cpluspractise | 6cf068d1a9cbc660455140a2cf5a8fa0c953020e | e89ace81e416af1f339ce9776007ab6a659fdca8 | refs/heads/main | 2023-07-04T05:31:18.977706 | 2021-07-19T15:44:37 | 2021-07-19T15:44:37 | 379,003,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | #include<iostream>
int main()
{
double y;
double* p_x;
y = 3.0;
p_x = &y; // copying the address of y to pointer p_x
std::cout << "y= " << y << std::endl;
*p_x = 1.0; // storing the value 1.0 to the p_x pointer address
std::cout << "y= " << y << std::endl;
}
| [
"winnypine@gmail.com"
] | winnypine@gmail.com |
b1e0e811151a7ee66fbeb86b5e53cd12c674fd45 | 365913bcc02bfdf6b6f6c246855144663f7e052b | /Code/GraphMol/testPicklerGlobalSettings.cpp | edd8bb2b2396228bfc8f2dcdee062f27141c6f2c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | UnixJunkie/rdkit | d8458eadca78ba1714be5c55ba75c8e164fc1479 | 3ddb54aeef0666aeaa2200d2137884ec05cb6451 | refs/heads/master | 2021-06-01T22:26:53.201525 | 2017-08-15T17:00:30 | 2017-08-15T17:00:30 | 100,572,461 | 2 | 0 | NOASSERTION | 2019-05-29T00:58:25 | 2017-08-17T07:03:53 | C++ | UTF-8 | C++ | false | false | 8,865 | cpp | //
// Copyright (c) 2017, Novartis Institutes for BioMedical Research 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 Novartis Institutes for BioMedical Research Inc.
// nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <RDGeneral/utils.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/RDKitQueries.h>
#include <GraphMol/MolPickler.h>
#include <GraphMol/MonomerInfo.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/SmilesParse/SmartsWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <RDGeneral/RDLog.h>
#include <stdlib.h>
#include <ctime>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
using namespace RDKit;
void testGlobalPickleProps() {
BOOST_LOG(rdInfoLog) << "-----------------------\n";
BOOST_LOG(rdInfoLog) << "Testing pickling of properties"
<< std::endl;
std::vector<double> v;
v.push_back(1234.);
v.push_back(444.);
v.push_back(1123.);
ROMol *m = SmilesToMol("CC");
m->setProp("double", 1.0);
m->setProp("int", 100);
m->setProp("bool", true);
m->setProp("boolfalse", false);
m->setProp("dvec", v);
Atom *a = m->getAtomWithIdx(0);
a->setProp("double", 1.0);
a->setProp("int", 100);
a->setProp("bool", true);
a->setProp("boolfalse", false);
a->setProp("dvec", v);
a->setProp("_private", true);
Bond *b = m->getBondWithIdx(0);
b->setProp("double", 1.0);
b->setProp("int", 100);
b->setProp("bool", true);
b->setProp("boolfalse", false);
b->setProp("dvec", v);
b->setProp("_private", true);
std::string pkl;
{
MolPickler::setDefaultPickleProperties(PicklerOps::AllProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(m2->getProp<double>("double") == 1.0);
TEST_ASSERT(m2->getProp<int>("int") == 100);
TEST_ASSERT(m2->getProp<bool>("bool") == true);
TEST_ASSERT(m2->getProp<bool>("boolfalse") == false);
a = m2->getAtomWithIdx(0);
TEST_ASSERT(a->getProp<double>("double") == 1.0);
TEST_ASSERT(a->getProp<int>("int") == 100);
TEST_ASSERT(a->getProp<bool>("bool") == true);
TEST_ASSERT(a->getProp<bool>("boolfalse") == false);
TEST_ASSERT(a->getProp<bool>("_private") == true);
b = m2->getBondWithIdx(0);
TEST_ASSERT(b->getProp<double>("double") == 1.0);
TEST_ASSERT(b->getProp<int>("int") == 100);
TEST_ASSERT(b->getProp<bool>("bool") == true);
TEST_ASSERT(b->getProp<bool>("boolfalse") == false);
TEST_ASSERT(b->getProp<bool>("_private") == true);
//TEST_ASSERT(b->getProp<std::vector<double> >("dvec") == v);
delete m2;
}
{
MolPickler::setDefaultPickleProperties(PicklerOps::MolProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(m2->getProp<double>("double") == 1.0);
TEST_ASSERT(m2->getProp<int>("int") == 100);
TEST_ASSERT(m2->getProp<bool>("bool") == true);
TEST_ASSERT(m2->getProp<bool>("boolfalse") == false);
a = m2->getAtomWithIdx(0);
TEST_ASSERT(!a->hasProp("double"));
TEST_ASSERT(!a->hasProp("int"));
TEST_ASSERT(!a->hasProp("bool"));
TEST_ASSERT(!a->hasProp("boolfalse"));
TEST_ASSERT(!a->hasProp("_private"));
b = m2->getBondWithIdx(0);
TEST_ASSERT(!b->hasProp("double"));
TEST_ASSERT(!b->hasProp("int"));
TEST_ASSERT(!b->hasProp("bool"));
TEST_ASSERT(!b->hasProp("boolfalse"));
TEST_ASSERT(!b->hasProp("_private"));
delete m2;
}
{
MolPickler::setDefaultPickleProperties(PicklerOps::AtomProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(!m2->hasProp("double"));
TEST_ASSERT(!m2->hasProp("int"));
TEST_ASSERT(!m2->hasProp("bool"));
TEST_ASSERT(!m2->hasProp("boolfalse"));
a = m2->getAtomWithIdx(0);
TEST_ASSERT(a->getProp<double>("double") == 1.0);
TEST_ASSERT(a->getProp<int>("int") == 100);
TEST_ASSERT(a->getProp<bool>("bool") == true);
TEST_ASSERT(a->getProp<bool>("boolfalse") == false);
TEST_ASSERT(!a->hasProp("_private"));
b = m2->getBondWithIdx(0);
TEST_ASSERT(!b->hasProp("double"));
TEST_ASSERT(!b->hasProp("int"));
TEST_ASSERT(!b->hasProp("bool"));
TEST_ASSERT(!b->hasProp("boolfalse"));
TEST_ASSERT(!b->hasProp("_private"));
delete m2;
}
{
MolPickler::setDefaultPickleProperties(PicklerOps::AtomProps |
PicklerOps::PrivateProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(!m2->hasProp("double"));
TEST_ASSERT(!m2->hasProp("int"));
TEST_ASSERT(!m2->hasProp("bool"));
TEST_ASSERT(!m2->hasProp("boolfalse"));
a = m2->getAtomWithIdx(0);
TEST_ASSERT(a->getProp<double>("double") == 1.0);
TEST_ASSERT(a->getProp<int>("int") == 100);
TEST_ASSERT(a->getProp<bool>("bool") == true);
TEST_ASSERT(a->getProp<bool>("boolfalse") == false);
TEST_ASSERT(a->getProp<bool>("_private") == true);
b = m2->getBondWithIdx(0);
TEST_ASSERT(!b->hasProp("double"));
TEST_ASSERT(!b->hasProp("int"));
TEST_ASSERT(!b->hasProp("bool"));
TEST_ASSERT(!b->hasProp("boolfalse"));
TEST_ASSERT(!b->hasProp("_private"));
delete m2;
}
{
MolPickler::setDefaultPickleProperties(PicklerOps::BondProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(!m2->hasProp("double"));
TEST_ASSERT(!m2->hasProp("int"));
TEST_ASSERT(!m2->hasProp("bool"));
TEST_ASSERT(!m2->hasProp("boolfalse"));
a = m2->getAtomWithIdx(0);
TEST_ASSERT(!a->hasProp("double"));
TEST_ASSERT(!a->hasProp("int"));
TEST_ASSERT(!a->hasProp("bool"));
TEST_ASSERT(!a->hasProp("boolfalse"));
TEST_ASSERT(!a->hasProp("_private"));
b = m2->getBondWithIdx(0);
TEST_ASSERT(b->getProp<double>("double") == 1.0);
TEST_ASSERT(b->getProp<int>("int") == 100);
TEST_ASSERT(b->getProp<bool>("bool") == true);
TEST_ASSERT(b->getProp<bool>("boolfalse") == false);
TEST_ASSERT(!b->hasProp("_private"));
delete m2;
}
{
MolPickler::setDefaultPickleProperties(PicklerOps::BondProps |
PicklerOps::PrivateProps);
MolPickler::pickleMol(*m, pkl);
RWMol *m2 = new RWMol(pkl);
TEST_ASSERT(m2);
TEST_ASSERT(!m2->hasProp("double"));
TEST_ASSERT(!m2->hasProp("int"));
TEST_ASSERT(!m2->hasProp("bool"));
TEST_ASSERT(!m2->hasProp("boolfalse"));
a = m2->getAtomWithIdx(0);
TEST_ASSERT(!a->hasProp("double"));
TEST_ASSERT(!a->hasProp("int"));
TEST_ASSERT(!a->hasProp("bool"));
TEST_ASSERT(!a->hasProp("boolfalse"));
TEST_ASSERT(!a->hasProp("_private"));
b = m2->getBondWithIdx(0);
TEST_ASSERT(b->getProp<double>("double") == 1.0);
TEST_ASSERT(b->getProp<int>("int") == 100);
TEST_ASSERT(b->getProp<bool>("bool") == true);
TEST_ASSERT(b->getProp<bool>("boolfalse") == false);
TEST_ASSERT(b->getProp<bool>("_private") == true);
delete m2;
}
delete m;
BOOST_LOG(rdErrorLog) << "\tdone" << std::endl;
}
int main(int argc, char *argv[]) {
RDLog::InitLogs();
testGlobalPickleProps();
}
| [
"greg.landrum@gmail.com"
] | greg.landrum@gmail.com |
5840851b00a08abf2590493261f6b940d0f93cd9 | fc09f165a0616536338d6cc717d79ed70bd8bdf6 | /dos/cm_util/BIT_STRE/WORKING/GET_BIT2.CPP | 94ec5e8e5c7c972484f94e82f4e52ed16ccccee3 | [] | no_license | doug16rogers/oldstuff | 9c80c2834260891d9d26f839f8250e56261606a2 | 756080797c6a34eb92929bab5ac55c3647df000f | refs/heads/master | 2020-05-18T14:22:35.790669 | 2017-03-07T21:32:32 | 2017-03-07T21:32:32 | 84,244,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | /*****************************************************************************
*
* TITLE: Get_Bit_Back
*
* DESCRIPTION: The class method "Get_Bit_Back"
* of class BIT_STREAM
* gets a single bit from the head
* of the stream. That is, it gets
* the bit most recently put.
*
* *k "%n"
* FILE NAME: "GET_BIT2.CPP"
*
* *k "%v"
* VERSION: "1"
*
* REFERENCE: None.
*
*****************************************************************************/
#include "bit_stre.h"
UINT8 BIT_STREAM :: Get_Bit_Back()
{
if (count > 0)
{
count--;
if (head == 0)
{
head = size - 1;
}
else
{
head--;
}
UINT head_byte = head / 8;
UINT8 bit_mask = ((UINT8) 1) << ((UINT8) (head % 8));
return (base[head_byte] & bit_mask) != 0;
}
return 0;
} // BIT_STREAM :: Get_Bit_Back
| [
"none@none.com"
] | none@none.com |
79a19663c90735df4c6380ca126a60642be50c8b | f48d5e72bd34dfd599c1687ae53aa4fc86384eaf | /hg_interact/T2lFilter.h | f68036952f49219b3b23d2e97780956672b7a074 | [] | no_license | ta2la/hg | f3c08fac5686a51f6529410a976e1bc9ae765508 | 937008bfa3bff78754099bae4c5473951b5ee7ee | refs/heads/master | 2021-06-28T01:44:42.045458 | 2020-12-14T21:15:47 | 2020-12-14T21:15:47 | 190,577,067 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | //
// Copyright (C) 2015 Petr Talla. [petr.talla@gmail.com]
//
// 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.
//=============================================================================
#pragma once
#include <string>
class TcObject;
namespace T2l
{
//=============================================================================
class Filter {
//=============================================================================
public:
//<CONSTRUCTION>
Filter() {}
virtual ~Filter() {}
//<METHODS>
virtual bool pass(TcObject* object) { return true; }
virtual std::string print() { return "BASIC FILTER"; }
//=============================================================================
};
} // namespace T2l
| [
"petr.talla@honeywell.com"
] | petr.talla@honeywell.com |
bd7118f62b611fd1030436b876bbaa8343bcf9c8 | 30ad231c47db74e4cce9d11024d0c187d1a91175 | /day13/day13.cpp | cbad57334f46a39a8cd9be2700da10b0ad23ba35 | [
"Unlicense"
] | permissive | wuggy-ianw/AoC2017 | afa36502238232956299b4baa6b5bd149667591f | 138c66bdd407e76f6ad71c9d68df50e0afa2251a | refs/heads/master | 2021-09-01T18:06:13.445410 | 2017-12-28T06:15:40 | 2017-12-28T06:15:40 | 112,793,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,445 | cpp | //
// Created by wuggy on 22/12/2017.
//
#include <cassert>
#include <algorithm>
#include <array>
#include "day13.h"
#include "../utils/aocutils.h"
void Day13::sentry::reset()
{
sentry_pos = 0;
sentry_dir = 1;
}
void Day13::sentry::next_tick()
{
// move the sentry to the next position
// if that would over/under-flow, invert the orientation and do it again
int newpos = sentry_pos + sentry_dir;
if (newpos<0 || newpos>=range)
{
sentry_dir *= -1;
newpos = sentry_pos + sentry_dir;
}
assert(newpos>=0);
assert(newpos<range);
sentry_pos = newpos;
}
void Day13::state::init(const std::vector<sentry> &sentries)
{
max_depth = -1;
for (const Day13::sentry &sentry : sentries)
{
firewall[sentry.depth] = sentry;
max_depth = std::max(max_depth, sentry.depth);
}
}
bool Day13::state::next_tick()
{
// ordering is important: out packet moves FIRST, then sentries move AFTER
// move time and our packet forward
tick++;
packet_depth++;
// if our packet depth matches a sentry at the zeroth position, then we've been detected
bool detected = false;
try
{
detected = (firewall.at(packet_depth).sentry_pos == 0);
}
catch(std::out_of_range& x)
{
// ignore... just means there's no sentry on the firewall depth that out packet is on
}
// move all our sentries forward one position
for (auto& pr : firewall) pr.second.next_tick();
return detected;
}
void Day13::state::reset()
{
tick = -1;
packet_depth = -1;
for (auto& pr : firewall) pr.second.reset();
}
std::vector<Day13::sentry> Day13::parse_sentries(std::istream& stream)
{
return AOCUtils::parseByLines<sentry>(stream,
[](const std::string& s) -> sentry
{
std::istringstream iss(s);
int layer = -1, depth = -1;
iss >> layer >> AOCUtils::literal(":") >> depth;
assert(iss);
return sentry(layer, depth);
});
}
namespace
{
std::pair<bool, int> run_simulation(Day13::state& state, bool stop_on_detected = false)
{
// run the state until our pos is past the end
int trip_severity = 0;
bool was_detected = false;
while (state.packet_depth < state.max_depth)
{
bool detected = state.next_tick();
if (detected)
{
was_detected = true; // we were detected at least once
const int severity = state.packet_depth * state.firewall.at(state.packet_depth).range;
trip_severity += severity;
if (stop_on_detected) break;
}
}
return std::make_pair(was_detected, trip_severity);
}
} // anonymous namespace
int Day13::solve_part1(const std::vector<sentry> &sentries)
{
Day13::state state;
state.init(sentries);
return run_simulation(state).second;
}
int Day13::solve_part2(const std::vector<sentry> &sentries)
{
// keep running the simulation with a larger delay until we find one that succeeds
Day13::state state;
state.init(sentries);
int delay = 0;
while(true)
{
state.packet_depth -= delay;
bool detected = run_simulation(state, true).first;
if (!detected) break; // found a successful way through the firewall
delay++;
state.reset();
if ((delay % 1000) == 0) std::cout << delay << std::endl;
}
return delay;
}
long Day13::solve_part2_sensibly(const std::vector<sentry>& sentries)
{
// instead of brute-forcing, work through the periods
// period = 2 * (range - 1)
// we want to find a delay such that all sentries are 'off-period' when the packet reaches them
// for a delay 'd', this reaches 'sentry.depth' after 'd + sentry.depth' ticks
// a delay 'd' is bad if '(d + sentry.depth) % period == 0'
// sort sentries by their period (noddy improvement on performance)
std::vector<sentry> sorted_sentries = sentries;
std::sort(sorted_sentries.begin(), sorted_sentries.end(), [](const sentry& a, const sentry& b) -> bool {return a.range < b.range; });
for (int delay = 0; true; delay++)
{
bool bad = false;
for (const sentry& s : sorted_sentries)
{
const int period = 2 * (s.range - 1);
bad = (((delay + s.depth) % period) == 0);
if (bad) break;
}
if (!bad) return delay;
}
}
| [
"github@wuggy.org"
] | github@wuggy.org |
39dd60b713f84490b06cd2bcf4628166a47a4286 | 78f0044cab0c14205c7fe2a00067fe7aebe9eba3 | /cyborg_ros_k2_client/src/startRGB.cpp | 184af80b52b77864aacb506a17da16095d7118fe | [
"BSD-3-Clause"
] | permissive | thentnucyborg/CyborgRobot_v1_archive | 7ad8959b2e5f5cb5418699b9d93c2b41f962613c | fc1419d229f379063668684c51faaeb6cb6ba447 | refs/heads/master | 2021-01-16T05:14:51.804599 | 2020-02-25T11:51:39 | 2020-02-25T11:51:39 | 242,987,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,407 | cpp | /*************************************************************************************
Copyright (c) 2013, Carnegie Mellon University
All rights reserved.
Authors: Anurag Jakhotia<ajakhoti@andrew.cmu.edu>, Prasanna Velagapudi<pkv@cs.cmu.edu>
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 Carnegie Mellon University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************************/
#include "k2_client/k2_client.h"
int imageSize = 6220800;
int streamSize = imageSize + sizeof(double);
std::string cameraName = "rgb";
std::string imageTopicSubName = "image_color";
std::string cameraFrame = "";
int main(int argC,char **argV)
{
ros::init(argC,argV,"startRGB");
ros::NodeHandle n(cameraName);
image_transport::ImageTransport imT(n);
std::string serverAddress;
n.getParam("/serverNameOrIP",serverAddress);
n.getParam(ros::this_node::getNamespace().substr(1,std::string::npos) +
"/rgb_frame", cameraFrame);
Socket mySocket(serverAddress.c_str(),"9000",streamSize);
image_transport::CameraPublisher cameraPublisher = imT.advertiseCamera(
imageTopicSubName, 1);
camera_info_manager::CameraInfoManager camInfoMgr(n,cameraName);
camInfoMgr.loadCameraInfo("");
cv::Mat frame;
cv_bridge::CvImage cvImage;
sensor_msgs::Image rosImage;
while(ros::ok())
{
printf("Got a frame.\n");
mySocket.readData();
printf("Creating mat.\n");
frame = cv::Mat(cv::Size(1920,1080), CV_8UC3, mySocket.mBuffer);
cv::flip(frame,frame,1);
printf("Getting time.\n");
double utcTime;
memcpy(&utcTime,&mySocket.mBuffer[imageSize],sizeof(double));
cvImage.header.frame_id = cameraFrame.c_str();
cvImage.encoding = "bgr8";
cvImage.image = frame;
cvImage.toImageMsg(rosImage);
sensor_msgs::CameraInfo camInfo = camInfoMgr.getCameraInfo();
camInfo.header.frame_id = cvImage.header.frame_id;
printf("Updating.\n");
//cameraPublisher.publish(rosImage, camInfo, ros::Time(utcTime));
ros::spinOnce();
}
return 0;
}
| [
"martinius.knudsen@ntnu.no"
] | martinius.knudsen@ntnu.no |
5aea00fd5095189cb82a9eae938a0afe90fcc97a | b6900c5fecb6f8004170d9b51873b997b679cefa | /src/AlsIOHandler.h | aa7dc464d6c53875eef030b831e68fcbf89c8371 | [] | no_license | Onizuka1117/avc | c6c8124e8680430e669fe3f98f66f9b3ea754e84 | ac291f1565fc0ab914f284277882d0b7315068ed | refs/heads/main | 2023-04-17T04:28:21.055468 | 2021-04-21T01:51:20 | 2021-04-21T01:51:20 | 360,300,218 | 1 | 0 | null | 2021-04-21T20:39:02 | 2021-04-21T20:39:01 | null | UTF-8 | C++ | false | false | 936 | h | #pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include "../deps/tinyxml2/tinyxml2.h"
#include "AbletonLiveSet.h"
namespace avc {
using namespace tinyxml2;
using namespace ableton_data_types;
class AlsIOHandler
{
public:
AlsIOHandler(std::string ip, std::string xmlPath);
~AlsIOHandler();
void decompress();
void storeXmlData();
void writeToXml();
void writeToAls();
private:
void getValues(XMLNode* node);
void getTracks(XMLElement* node);
void getTrackInfo(std::shared_ptr<Track>& track, XMLNode* node);
void getMasterTrack(XMLElement* node);
const std::string inputPath, outputPath;
std::string setName;
std::unique_ptr<AbletonLiveSet> abletonLiveSet;
}; // class AlsIOHandler
} // namespace avc
| [
"ryandjeffares@gmail.com"
] | ryandjeffares@gmail.com |
c49cdcae2a664320456094a5893ff6488c154fb8 | 7aadc9eae2869b2dd296088b9b9436f60dfe7920 | /Skeleton Crew/Skeleton Crew/Vector3f.cpp | 8784713917845ceeee07e2c9458b7fd624ec174d | [] | no_license | MichaelPortfolio/Skeleton-Crew | fed2c7491c16dda85e77861ff4f86207a17ac6d7 | 9bb600b3b1b5645a5c837aab116df5850243e2fb | refs/heads/master | 2020-06-24T20:35:00.733198 | 2016-11-23T23:44:37 | 2016-11-23T23:44:37 | 74,622,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 162 | cpp | #include "Vector3f.h"
Vector3f::Vector3f(float X, float Y,float Z):x(X),y(Y),z(Z)
{
}
Vector3f::Vector3f():x(0),y(0),z(0)
{
}
Vector3f::~Vector3f(void)
{
}
| [
"michael.h.whelan93@gmail.com"
] | michael.h.whelan93@gmail.com |
fd943d70931a6cb5cc0ba16bf7e36d30b50efa63 | 608919a5b53cf3950cd8849ff30dca3eb94b4ad8 | /templet/半平面交.cpp | 6e09288f74f581ab340e78487205455fe6c433b4 | [] | no_license | demerzel1/ACM-code | 302c693fbd9f4d40071e13e674ec3c9b8dc15a24 | 42e3f59a585832b0fc4556d130be4c158b3bd2ec | refs/heads/master | 2021-04-26T22:21:09.891295 | 2018-03-31T08:16:54 | 2018-03-31T08:16:54 | 124,077,438 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,071 | cpp | #include<bits/stdc++.h>
using namespace std;
const int maxn=10000;
const double pi=acos(-1.0);
const double eps=1e-8;
//double类型的数,判断符号
int cmp(double x){
if(fabs(x)<eps) return 0;
if(x>0) return 1;
return -1;
}
//二维点类,可进行向量运算
//计算平方
inline double sqr(double x){
return x*x;
}
struct point{
double x,y;
point(){}
point(double a,double b):x(a),y(b){}
void input(){
scanf("%lf%lf",&x,&y);
}
friend point operator + (const point &a,const point &b){
return point(a.x+b.x,a.y+b.y);
}
friend point operator - (const point &a,const point &b){
return point(a.x-b.x,a.y-b.y);
}
friend bool operator == (const point &a,const point &b){
return cmp(a.x-b.x)==0&&cmp(a.y-b.y)==0;
}
friend point operator * (const point &a,const double &b){
return point(a.x*b,a.y*b);
}
friend point operator * (const double &a,const point &b){
return point(a*b.x,a*b.y);
}
friend point operator / (const point &a,const double &b){
return point(a.x/b,a.y/b);
}
double norm(){
return sqrt(sqr(x)+sqr(y));
}
};
//计算向量叉积
double det(const point &a,const point &b){
return a.x*b.y-a.y*b.x;
}
//计算向量点积
double dot(const point &a,const point &b){
return a.x*b.x+a.y*b.y;
}
//计算两点距离
double dist(const point &a,const point &b){
return (a-b).norm();
}
//op绕原点逆时针旋转A弧度
point rotate_point(const point &p,double A){
double tx=p.x,ty=p.y;
return point(tx*cos(A)-ty*sin(A),tx*sin(A)+ty*cos(A));
}
struct polygon_convex{
vector<point> P;
polygon_convex(int Size=0){
P.resize(Size);
}
double area(){
double sum=0;
for(int i=0;i<P.size()-1;i++)
sum+=det(P[i+1],P[i]);
sum+=det(P[0],P[P.size()-1]);
return sum/2.;
}
};
bool comp_less(const point &a,const point &b){
return cmp(a.x-b.x)<0||cmp(a.x-b.x)==0&&cmp(a.y-b.y)<0;
}
polygon_convex convex_hull(vector<point> a){
polygon_convex res(2*a.size()+5);
sort(a.begin(),a.end(),comp_less);
a.erase(unique(a.begin(),a.end()),a.end());
int m=0;
for(int i=0;i<a.size();i++){
while(m>1&&cmp(det(res.P[m-1]-res.P[m-2],a[i]-res.P[m-2]))<=0) --m;
res.P[m++]=a[i];
}
int k=m;
for(int i=int(a.size())-2;i>=0;--i){
while(m>k&&cmp(det(res.P[m-1]-res.P[m-2],a[i]-res.P[m-2]))<=0) --m;
res.P[m++]=a[i];
}
res.P.resize(m);
if(a.size()>1) res.P.resize(m-1);
return res;
}
typedef complex<double> Point;
typedef pair<Point,Point> Halfplane;
const double EPS=1e-10;
const double INF=10000;
inline int sgn(double n){
return fabs(n)<EPS ? 0 : (n<0 ? -1 : 1);
}
inline double cross(Point a,Point b){
return (conj(a)*b).imag();
}
inline double dot(Point a,Point b){
return (conj(a)*b).real();
}
inline double satisfy(Point a,Halfplane p){
return sgn(cross(a-p.first,p.second-p.first))<=0;
}
Point crosspoint(const Halfplane &a,const Halfplane &b){
double k=cross(b.first-b.second,a.first-b.second);
k=k/(k-cross(b.first-b.second,a.second-b.second));
return a.first+(a.second-a.first)*k;
}
bool cmp1(const Halfplane &a,const Halfplane &b){
int res=sgn(arg(a.second-a.first)-arg(b.second-b.first));
return res==0 ? satisfy(a.first,b):res<0;
}
vector<Point> halfplaneIntersection(vector<Halfplane> v){
sort(v.begin(),v.end(),cmp1);
deque<Halfplane> q;
deque<Point> ans;
q.push_back(v[0]);
for(int i=1;i<int(v.size());i++){
if(sgn(arg(v[i].second-v[i].first)-arg(v[i-1].second-v[i-1].first))==0)
continue;
while(ans.size()>0&&!satisfy(ans.back(),v[i])){
ans.pop_back();
q.pop_back();
}
while(ans.size()>0&&!satisfy(ans.front(),v[i])){
ans.pop_front();
q.pop_front();
}
ans.push_back(crosspoint(q.back(),v[i]));
q.push_back(v[i]);
}
while(ans.size()>0&&!satisfy(ans.back(),q.front())){
ans.pop_back();
q.pop_back();
}
while(ans.size()>0&&!satisfy(ans.front(),q.back())){
ans.pop_front();
q.pop_front();
}
ans.push_back(crosspoint(q.back(),q.front()));
return vector<Point>(ans.begin(),ans.end());
}
struct polygon{
int n;
point a[maxn];
polygon(){}
};
struct halfplane{
double a,b,c;
halfplane(point p,point q){
a=p.y-q.y;
b=q.x-p.x;
c=det(p,q);
}
halfplane (double aa,double bb,double cc){
a=aa;
b=bb;
c=cc;
}
};
double calc(halfplane &L,point &a){
return a.x*L.a+a.y*L.b+L.c;
}
point Intersect(point &a,point &b,halfplane &L){
point res;
double t1=calc(L,a),t2=calc(L,b);
res.x=(t2*a.x-t1*b.x)/(t2-t1);
res.y=(t2*a.y-t1*b.y)/(t2-t1);
return res;
}
polygon_convex cut(polygon_convex &a,halfplane &L){
int n=a.P.size();
polygon_convex res;
for(int i=0;i<n;i++){
if(calc(L,a.P[i])<-eps)
res.P.push_back(a.P[i]);
else{
int j;
j=i-1;
if(j<0)
j=n-1;
if(calc(L,a.P[j])>-eps){
res.P.push_back(Intersect(a.P[j],a.P[i],L));
}
j=i+1;
if(j==n)
j=0;
if(calc(L,a.P[j])<-eps)
res.P.push_back(Intersect(a.P[i],a.P[j],L));
}
}
return res;
}
polygon_convex core(polygon &a){
polygon_convex res;
res.P.push_back(point(-INF,-INF));
res.P.push_back(point(INF,-INF));
res.P.push_back(point(INF,INF));
res.P.push_back(point(-INF,INF));
int n=a.n;
for(int i=0;i<n;i++){
halfplane L(a.a[i],a.a[(i+1)%n]);
res=cut(res,L);
}
return res;
}
| [
"mengzhaoxin@hotmail.com"
] | mengzhaoxin@hotmail.com |
c19e8737daaf31ff5f06d62a2bae9710e9d37305 | 20a899fde0c449737d5e156ce86e391743e719ad | /laba 3/Korabl.h | 86b8b9574f243d5fc151b594990ca44fa0e89ba5 | [] | no_license | Akhremenko/Lab_5 | 2a4fe468443275f6758b966fe0dfd181837def3e | 2046a48f7cc884b36a30cc747dd8956adcbc3d82 | refs/heads/master | 2021-01-13T00:46:04.068250 | 2015-10-21T17:26:18 | 2015-10-21T17:26:18 | 44,263,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | h | #pragma once
#include "Transportnoe_sredstvo.h"
class Korabl :public Transportnoe_sredstvo
{
int kolPushek_;
public:
Korabl();
int getKolPushek();
void setKolPushek(int);
void print();
}; | [
"nancybrown@bk.ru"
] | nancybrown@bk.ru |
eceb7661c3c48ff93e20c1c50580b1d8a86a5596 | 552c39141dab7cbc0c34245000291a46cdb41495 | /lte_enb/src/tenb_commonplatform/software/apps/fap/ntp-client/Ver2/StateMachine.cpp | 4ff4163958669e7f1afeb8528b80e7985e49f8ba | [] | no_license | cmjeong/rashmi_oai_epc | a0d6c19d12b292e4da5d34b409c63e3dec28bd20 | 6ec1784eb786ab6faa4f7c4f1c76cc23438c5b90 | refs/heads/master | 2021-04-06T01:48:10.060300 | 2017-08-10T02:04:34 | 2017-08-10T02:04:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,454 | cpp | ///////////////////////////////////////////////////////////////////////////////
//
// StateMachine.cpp
//
// See header file for documentation.
//
// Copyright Radisys Limited
//
///////////////////////////////////////////////////////////////////////////////
#include "StateMachine.h"
#include <string.h>
#include <system/Trace.h>
#include <assert.h>
namespace threeway
{
State::~State()
{
std::vector<Action*>::iterator iter;
for (iter = m_actions.begin(); iter != m_actions.end(); iter++)
{
delete *iter;
}
m_actions.clear();
delete (m_entry);
delete (m_exit);
}
Action* State::GetAction(int eventId)
{
ENTER();
//TRACE_PRINTF("Getting action for eventid %d",eventId);
std::vector<Action*>::iterator iter;
for (iter = m_actions.begin(); iter != m_actions.end(); iter++)
{
if (((*iter)->GetEventId()) == eventId)
{
//TRACE_PRINTF("Action Found....");
RETURN(*iter);
}
}
RETURN(NULL);
}
void State::AddAction(int eventId, CallbackBase* eventCallback, State *newState)
{
if(newState == NULL)
TRACE_PRINTF("State::AddAction (newState == NULL)");
if (GetAction(eventId) != NULL)
{
TRACE_PRINTF("Action for this event already exists");
}
else
{
Action* theAction = new Action(eventId, eventCallback, newState);
m_actions.push_back(theAction);
}
}
State* State::EventHappened(int* eventId)
{
Action* theAction;
State* resultantState;
//TRACE_PRINTF("event (%d) in state %s",*eventId,GetName());
if ((theAction = GetAction(*eventId)) == NULL)
{
//if (m_debugOn)
//{
TRACE_PRINTF(" No handler for this event (%d) in state %s",*eventId,GetName());
//}
//No handler for this event so pass up the action and do nothing. Resultant state is our state as nothing has changed. Do not change eventid as it has not been consumed
resultantState = this;
}
else
{
if((resultantState = theAction->m_newState) != NULL) //if the action has a resultant state, it is not an internal event i.e. it leaves the state and enters another (possibly the same state it left)
{
TRACE_PRINTF("~~~~~~~~~~~~ Exiting state %s\n",GetName());
if (m_exit)
{
DoExit();
}
if (theAction->m_callback)
{
(theAction->m_callback)->Call();
}
TRACE_PRINTF("~~~~~~~~~~~~ Entering state %s\n",resultantState->GetName());
if (resultantState->m_entry)
{
resultantState->DoEntry();
}
}
else //action is an internal event handler, so don't do entry/exit functions
{
if (theAction->m_callback)
{
TRACE_PRINTF("////////////////actioning internal event handler, eventid = %d\n",*eventId);
(theAction->m_callback)->Call();
}
}
}
*eventId = 0; //set eventId to 0 as it has been 'consumed'
//return the state we are now in
return resultantState;
}
void StateMachine::Reset(void)
{
std::vector<State*>::iterator iter;
for (iter = m_states.begin(); iter != m_states.end(); iter++)
{
delete *iter;
}
m_states.clear();
if(m_parallelStateMachine != NULL)
{
delete(m_parallelStateMachine);
m_parallelStateMachine = NULL;
}
}
void StateMachine::InsertSimpleState(const char* stateName, CallbackBase* entry, CallbackBase* exit)
{
State* newState;
//TRACE_PRINTF(" Inserting state %s, callback 1 = %p, callback 2 = %p",stateName,entry,exit);
if (GetState(stateName) == NULL)
{
newState = new State(stateName, entry, exit, m_numStates);
RSYS_ASSERT((newState!=NULL));
if (m_states.empty())
{
m_currentState = newState;
}
m_states.push_back((newState));
m_numStates++;
}
else
{
TRACE_PRINTF(" %s: State %s already exists",m_stateMachineName,stateName);
}
}
StateMachine* StateMachine::InsertCompositeState(const char* stateName, CallbackBase* entry, CallbackBase* exit)
{
State* newState;
StateMachine* newSM = NULL;
TRACE_PRINTF(" Inserting composite state %s",stateName);
if (GetState(stateName) == NULL)
{
newSM = new StateMachine(stateName, entry, exit, m_numStates);
RSYS_ASSERT(newSM != NULL);
newState = (State*) newSM;
if (m_states.empty())
{
m_currentState = newState;
}
m_states.push_back((newState));
m_numStates++;
}
else
{
TRACE_PRINTF(" %s: State %s already exists",m_stateMachineName,stateName);
RSYS_ASSERT(false);
}
return newSM;
}
StateMachine* StateMachine::InsertOrthogonalStateMachine(const char* stateName)
{
TRACE_PRINTF("Adding orthogonal state machine %s",stateName);
RSYS_ASSERT(m_parallelStateMachine == NULL);
m_parallelStateMachine = new StateMachine(stateName);
RSYS_ASSERT(m_parallelStateMachine != NULL);
return m_parallelStateMachine;
}
bool StateMachine::InsertEventHandler(int eventId, const char * stateName, CallbackBase* actionCallback,const char* resultantState)
{
bool retVal;
State* theState;
if ((theState = GetState(stateName)) == NULL)
{
retVal = false;
TRACE_PRINTF(" %s: No state of this name: %s",m_stateMachineName,stateName);
}
else
{
/* State* theResultantState;
if ((theResultantState = GetState(resultantState)) == NULL)
{
retVal = false;
TRACE_PRINTF(" %s: No resultant state of this name: %s",m_stateMachineName,resultantState);
}
else
{
theState->AddAction(eventId, actionCallback, theResultantState);
retVal = true;
}*/
State* theResultantState;
theResultantState = GetState(resultantState);
theState->AddAction(eventId, actionCallback, theResultantState);
retVal = true;
}
return retVal;
}
void StateMachine::EventHappened(int eventId)
{
//TRACE_PRINTF(" StateMachine::EventHappened int");
if (!(m_states.empty()))
{
if(m_constructed)
{
EventHappened(&eventId);
}
else
{
TRACE_PRINTF("Help! State machine %s not yet fully constructed",GetName());
}
}
else
{
TRACE_PRINTF("State machine not initialised event id = %d",eventId);
}
}
State* StateMachine::EventHappened(int* eventId)
{
int theEvent = 0;
State* newState = this;
// TRACE_PRINTF(" StateMachine::EventHappened int*");
if(m_parallelStateMachine != NULL)
{
//hand the event on to any orthogonal state machines
TRACE_PRINTF("handing event (%d) to parallel (orthogonal) sm %s",*eventId,m_parallelStateMachine->GetName());
m_parallelStateMachine->EventHappened(*eventId);
}
//TRACE_PRINTF("event (%d) in state %s",*eventId,GetName());
// Check that current state is known, i.e. InsertSimpleState() has been called
if (m_currentState == NULL)
{
TRACE_PRINTF("StateMachine::EventHappened(): m_currentState==NULL. Using NULL as storage event (%d) in state %s",(int)eventId,GetName());
}
else
{
TRACE_PRINTF(" %s: Event happened entry Event = %d, in state %s",m_stateMachineName,*eventId,(m_currentState->GetName()));
m_events.push(*eventId);
//TRACE_PRINTF(" %s: Event queue size (pre check) = %zu",m_stateMachineName,m_events.size());
if (m_events.size() == 1) //only start processing if the size of the queue is 1. This avoids re-entrance problems if this method is called by one of the callbacks below.
{
while (!(m_events.empty()))
{
//TRACE_PRINTF("Event queue size = %d",m_events.size());
theEvent = m_events.front(); //get the queued event...
//...send the event to the State.
//toss toss toss
m_currentState = m_currentState->EventHappened(&theEvent);
//if the event has not been 'consumed' try our own State behaviour i.e
if (theEvent != 0)
{
newState = m_currentState->State::EventHappened(&theEvent);
}
else
{
newState = this;
}
m_events.pop();
}
}
else
{
//if (m_debugOn)
//{
//TRACE_PRINTF(" %s: More than one event Event queue size = %zu",m_stateMachineName,m_events.size());
//}
}
}
*eventId = theEvent;
return newState;
}
State* StateMachine::GetState(const char *stateName)
{
ENTER();
if(stateName == NULL)
{
TRACE_PRINTF("StateMachine::GetState (stateName == NULL)");
RETURN(NULL);
}
else
{
std::vector<State*>::iterator iter;
for (iter = m_states.begin(); iter != m_states.end(); iter++)
{
if (strcmp((*iter)->GetName(), stateName) == 0)
{
RETURN(*iter);
}
}
}
RETURN(NULL);
}
}
| [
"sriprasads@gmail.com"
] | sriprasads@gmail.com |
26e3c48a8fe5be057c43a1ffbf37a1d6e66081d0 | 97c2a634d660310cae25db65900ba9cab0748923 | /L3/S1/TOO/TP6_CPP/Devise.cpp | 20ad6e4d85d6c87bdd19914c8661fc2e867e48a9 | [
"MIT"
] | permissive | ZeCroque/study-uppa | 7a100db6efc30650fa1cbb0915837331b06fa98f | 94b902eaeb6ffe78a28a2bab3581ce017f51bc92 | refs/heads/master | 2021-04-26T22:32:00.275041 | 2019-03-06T14:35:06 | 2019-03-06T14:35:06 | 124,108,256 | 1 | 0 | MIT | 2018-05-18T13:13:51 | 2018-03-06T16:43:31 | C++ | UTF-8 | C++ | false | false | 1,323 | cpp | #include <iostream>
#include <string>
#include "Devise.h"
const double Devise::Taux_de_conversion[3][2] = { // Taux valides le 11 octobre 2017
{0.845534, 0.151725}, // Dollar -> Euro, Dollar -> Yuan
{1.18268, 0.128320}, // Euro -> Dollar, Euro -> Yuan
{6.59169, 7.79636} // Yuan -> Dollar, Yuan -> Euro
};
Devise::Devise(Type_de_devise type_de_devise, const std::string& symbole) : _type_de_devise(type_de_devise), _symbole(symbole) {
}
std::string Devise::conversion(double montant, const Devise& devise) const {
double resultat = montant * Taux_de_conversion[(int) this->_type_de_devise][(int) devise._type_de_devise];
return std::to_string(resultat) + _symbole;
}
std::string Devise::conversion(double montant, Type_de_devise type_de_devise) const {
double resultat = montant * Taux_de_conversion[(int) this->_type_de_devise][(int) type_de_devise];
return std::to_string(resultat) + _symbole;
}
int main(int argc, char** argv) {
Devise dollar(Devise::Type_de_devise::Dollar, "$");
Devise euro(Devise::Type_de_devise::Euro, "€");
std::cout << euro.conversion(1.0, dollar) << '\n'; // '1.182680€' est affiché...
std::cout << euro.conversion(1.0, Devise::Type_de_devise::Dollar) << '\n'; // '1.182680€' est affiché...
return 0;
}
| [
"gcroquefer@scinfe146.univ-pau.fr"
] | gcroquefer@scinfe146.univ-pau.fr |
3b8cab95ef554c04bb18e125de75cb5cd368dc3c | 10fb503da20f4883f9d8ce4046c02e79daf04a64 | /bonus/sources/PMethod.cpp | fac953440c967965fbd6cecd4d073fe6b68822ee | [] | no_license | SagotG/UML_epitech | 436a701770dae3002233269515443721836f7813 | a15f275cce2d35ff5ae79a93bf4cf9fabfd28b5f | refs/heads/master | 2021-03-24T10:01:10.967319 | 2018-02-17T12:09:18 | 2018-02-17T12:09:18 | 121,852,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | /*
** PMethod.cpp for in /home/sagotg/rendu/UML/sources
**
** Made by sagotg
** Login <sagotg@epitech.net>
**
** Started on Thu Sep 21 23:11:26 2017 sagotg
** Last update Thu Sep 21 23:17:38 2017 Guillaume SAGOT
*/
PMethod::PMethod() {
}
PMethod::~PMethod () {
}
void PMethod::setPrices(Method) const {
}
double PMethod::getPrices() {
return (0);
}
std::string PMethod::selectMethod() {
return ("");
}
bool PMethod::Payment() {
return (true);
}
| [
"guillaume.sagot@epitech.eu"
] | guillaume.sagot@epitech.eu |
7a17eaf897b45e902efb089a166709d170dc47bd | 1884b52d923717d7a406ff5dbf860a431692de81 | /C-LeetCode/Problem0046.cpp | 7cf954a92131de22d100bb860c6d6a9e846d2282 | [] | no_license | ShijieQ/C- | da7de3adf71581597b987aee04a28c49fbd9d24e | 4b3f363a5e5d836d8c84f0ccc2e121078a8f6fa7 | refs/heads/master | 2021-06-11T17:38:52.054092 | 2021-03-24T15:23:30 | 2021-03-24T15:23:30 | 159,472,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | class Solution {
public:
void dfs(vector<vector<int>>& ans, vector<int>& nums, int now) {
if (now == nums.size()) {
ans.push_back(nums);
return ;
}
int length = nums.size();
for (int i = now; i < length; i++) {
swap(nums[now], nums[i]);
dfs(ans, nums, now+1);
swap(nums[now], nums[i]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
dfs(ans, nums, 0);
return ans;
}
}; | [
"ShijieQ@outlook.com"
] | ShijieQ@outlook.com |
0bd35818443316ffa9ff1397bdc8d867aa9a633e | d9b635d1976cd7039ba6e61e5dffc01bbc0452f0 | /Practicums/Week03-IFstatement/zad2.cpp | d5fd66895662fa72661ccd92fca48bc69c0e27c3 | [] | no_license | pvarna/UP | 9c84225e52e96ca4835449403265f0cd1aae0490 | a9a5748d462a4b0e38e5b40ed55405e02c69bb40 | refs/heads/main | 2023-07-02T14:35:33.199819 | 2021-08-12T13:29:07 | 2021-08-12T13:29:07 | 319,069,586 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | #include <iostream>
int main ()
{
int number, firstDigit, secondDigit, thirdDigit, fourthDigit;
std::cout << "Enter a number: ";
std::cin >> number;
fourthDigit = number % 10;
thirdDigit = number / 10 % 10;
secondDigit = number / 100 % 10;
firstDigit = number / 1000;
if(fourthDigit == 0)
{
std::cout << "There isn't a symmetric number" << std::endl;
}
else
{
if (firstDigit == fourthDigit && secondDigit == thirdDigit)
{
std::cout << "The number is symmetric" << std::endl;
}
else
{
std::cout << "The number isn't symmetric" << std::endl;
}
}
return 0;
} | [
"peter.kolev2001@gmail.com"
] | peter.kolev2001@gmail.com |
dfe52efb0c5785bcf9950459c0e4a1ce4dc919d6 | 3e70eda6819fec5bf5ba2299573b333a3a610131 | /gf/db/ser/src/Cgf_other_info.h | 9a8ee03829ddcf5ed21a811df8b8f6ef7e83bb37 | [] | no_license | dawnbreaks/taomee | cdd4f9cecaf659d134d207ae8c9dd2247bef97a1 | f21b3633680456b09a40036d919bf9f58c9cd6d7 | refs/heads/master | 2021-01-17T10:45:31.240038 | 2013-03-14T08:10:27 | 2013-03-14T08:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | h | #ifndef _CGF_OTHER_INFO_H_
#define _CGF_OTHER_INFO_H_
#include "CtableRoute.h"
#include "proto.h"
#include "benchapi.h"
class Cgf_other_info: public CtableRoute
{
public:
Cgf_other_info(mysql_interface * db);
int get_other_info_list(userid_t userid, uint32_t role_regtime, gf_get_other_info_list_out_item** pData, uint32_t* count);
int replace_other_info(userid_t userid, uint32_t role_regtime, uint32_t type, uint32_t value);
int clear_role_info(userid_t userid,uint32_t role_regtime);
};
#endif
| [
"smyang.ustc@gmail.com"
] | smyang.ustc@gmail.com |
6b6caabbe34e6d36354fd2f58811e3e99a795ade | 50f353f22b82529ad7b7399849c6f947b2ed3483 | /270.cpp | 9f20bf0d0711427cc49ca771eea0c174bee30f2b | [] | no_license | bapinney/project-euler | 3ecae6ebb5b15b035969b9fb1abbf07fb1abc2de | a8114812ff7ec2d4c5d9d23d13ae85bf35b073bf | refs/heads/master | 2021-09-15T05:27:06.182063 | 2018-05-26T20:37:11 | 2018-05-26T20:37:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,001 | cpp | #include "fmt/format.h"
#include "fmt/ostream.h"
#include <map>
#include <NTL/ZZ.h>
using namespace fmt;
using namespace std;
using namespace NTL;
const int MOD = 1000000087, M = 128, N = 33;
long inv[M];
map<long, ZZ> f;
int cnt = 0, ptr = 0;
void preprocess(int *v, int n, long *buf) {
// if (n == 7)
// print("{} {}\n", i, j);
int last = -1, cnt = 0;
long ret = 0;
for (int i = 0; i < n; ++i) {
if (last != v[i]) {
last = v[i];
ret = ret << 8 | cnt;
cnt = 0;
}
++cnt;
last = v[i];
buf[i] = ret << 16 | cnt << 8 | 1;
}
}
long min_rep(long S) {
long ret = S, T = S;
int u[10], n = 0;
for (; S; ++n) {
u[n] = S & 0xff;
S >>= 8;
}
for (int i = 0; i < n; ++i) {
ret = min(ret, T);
T = (long) u[i] << (8 * (n - 1)) | T >> 8;
}
return ret;
}
ZZ dp(long S) {
if (S == 0x10101) return ZZ(1);
S = min_rep(S);
long T = S;
if (!f.count(S)) {
int v[M * 2], u[M * 2];
long bv[M], bu[M];
int offset = 0;
for (int i = 0; T; ++i) {
int t = T & 0xff;
for (int j = 0; j < t; ++j) {
v[offset++] = i;
// print("{} ", i);
}
T = T >> 8;
}
for (int i = 0; i < offset; ++i)
v[offset + i] = v[i];
for (int i = 0; i < offset * 2; ++i)
u[offset * 2 - 1 - i] = v[i];
ZZ ans{0};
for (int i = 0; i < offset; ++i) {
preprocess(v + i, offset, bv);
preprocess(u + (offset - i) % offset, offset, bu);
for (int j = i + 1; j < offset; ++j) {
if (v[i] != v[j] && j - i <= offset - 1) {
// long X = encode(v, i, j, offset);
// long Y = encode(v, j, i, offset);
long X = bv[j - i - 1];
long Y = bu[offset - 1 - (j - i)];
if (X < 0x10000 || Y < 0x10000)
continue;
// print("{:x} ({}, {}) => {:x} {:x}\n", S, i, j, X, Y);
ans += dp(X) * dp(Y);
}
}
}
if (cnt % 1000 == 0) {
print("{:x}: {} offset = {}\n", S, ans, offset);
assert(ans % (offset - 3) == 0);
}
++cnt;
f[S] = ans / (offset - 3);
}
return f[S];
}
int main() {
// inv[1] = 1;
// for (int i = 2; i < M; ++i) {
// inv[i] = (long) (MOD / i) * (MOD - inv[MOD % i]) % MOD;
// // print("{}\n", i * inv[i] % MOD);
// }
long n = 30;
// print("{:x}\n", min_rep(1ll << 0 | 2ll << 8 | 3ll << 16));
print("ans = {}\n", dp(n << 0 | n << 8 | n << 16 | n << 24));
return 0;
}
// 1000000007: 938106376
// 1000000009: 253059321
// 1000000021: 43879285
// 1000000033: 136731062
// 1000000087:
// 1000000093:
// 1000000097:
// 1000000103:
// 1000000123:
// 1000000181:
| [
"roosephu@gmail.com"
] | roosephu@gmail.com |
702cbf71166ac9b60caaa61c279a5586c819aa03 | 2cdee9148d16ed981958a01c12be561bd6094318 | /PythonDll/pyhelper.h | 820e228c3d65bf137a0cd9ce50c222ea13f83ee2 | [] | no_license | coolsnake/pythondll | 7fa03a9914255805e8051ffdb63dc5e7fa522876 | 0fe18ce85576e7d30c2a069259f0918e799be324 | refs/heads/master | 2020-03-26T16:53:35.022928 | 2018-04-16T21:04:53 | 2018-04-16T21:04:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | h | #ifndef PYHELPER_HPP
#define PYHELPER_HPP
#pragma once
#include <Python.h>
class CPyInstance
{
public:
CPyInstance()
{
Py_Initialize();
}
~CPyInstance()
{
Py_Finalize();
}
};
class CPyObject
{
private:
PyObject * p;
public:
CPyObject() : p(NULL)
{}
CPyObject(PyObject* _p) : p(_p)
{}
~CPyObject()
{
Release();
}
PyObject* getObject()
{
return p;
}
PyObject* setObject(PyObject* _p)
{
return (p = _p);
}
PyObject* AddRef()
{
if (p)
{
Py_INCREF(p);
}
return p;
}
void Release()
{
if (p)
{
Py_DECREF(p);
}
p = NULL;
}
PyObject* operator ->()
{
return p;
}
bool is()
{
return p ? true : false;
}
operator PyObject*()
{
return p;
}
PyObject* operator = (PyObject* pp)
{
p = pp;
return p;
}
operator bool()
{
return p ? true : false;
}
};
#endif | [
"lookstephenup@gmail.com"
] | lookstephenup@gmail.com |
1b515bfc062b96009782c122287ce59651ca6152 | 7092ff8d7cf0289e17da2ecc9c622fe21581addf | /sg_agent/thrid_party/cthrift/include/cthrift/util/cthrift_ns_interface.h | 0d13fa9146dbf635b1ea29f33c1fa17b33681e33 | [
"Apache-2.0"
] | permissive | fan2008shuai/octo-ns | e37eaf400d96e8a66dc894781574e2b5c275f43a | 06827e97dc0a9c957e44520b69a042d3fb6954af | refs/heads/master | 2020-05-27T19:40:42.233869 | 2019-06-09T15:09:48 | 2019-06-09T15:09:48 | 188,765,162 | 0 | 0 | Apache-2.0 | 2019-05-27T03:30:23 | 2019-05-27T03:30:21 | null | UTF-8 | C++ | false | false | 3,764 | h | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef CTHRIFT_SRC_CTHRIFT_UTIL_CTHRIFT_NS_INTERFACE_H_
#define CTHRIFT_SRC_CTHRIFT_UTIL_CTHRIFT_NS_INTERFACE_H_
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/make_shared.hpp>
#include <pthread.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Atomic.h>
#include "cthrift_common.h"
#include "cthrift_zk_client.h"
#include "log4cplus.h"
namespace meituan_cthrift {
typedef boost::shared_ptr<meituan_mns::getservice_res_param_t> ServicePtr;
typedef boost::function<void()> DestroyFunction;
typedef boost::function<int()> InitFunction;
typedef boost::function<int(ServicePtr service,
const long rcv_watcher_time)> GetFunction;
typedef boost::function<int(const meituan_mns::SGService &oservice,
meituan_mns::RegistCmd::type regCmd,
int uptCmd)> RegFunction;
class CthriftNsInterface {
public:
void SetRegFunction(RegFunction reg) {
reg_ = reg;
}
void SetInitFunction(InitFunction init) {
init_ = init;
}
void SetDesFunction(DestroyFunction des) {
destroy_ = des;
}
void SetGetFunction(GetFunction get) {
get_ = get;
}
CthriftNsInterface() {
init_ = boost::bind(&CthriftNsInterface::OnInit, this);
destroy_ = boost::bind(&CthriftNsInterface::OnDestory, this);
reg_ = boost::bind(&CthriftNsInterface::OnRegisterService,
this, _1, _2, _3);
get_ = boost::bind(&CthriftNsInterface::OnGetSrvList,
this, _1, _2);
}
virtual ~CthriftNsInterface() {
}
int32_t Init() {
return init_();
}
void Destory() {
destroy_();
}
int32_t GetSrvList(ServicePtr service,
const int64_t rcv_watcher_time = -1) {
return get_(service, rcv_watcher_time);
}
int32_t RegisterService(const meituan_mns::SGService &oservice,
meituan_mns::RegistCmd::type regCmd = meituan_mns::RegistCmd::REGIST,
int32_t uptCmd = meituan_mns::UptCmd::RESET) {
return reg_(oservice, regCmd, uptCmd);
}
private:
int32_t OnRegisterService(const meituan_mns::SGService &oservice,
meituan_mns::RegistCmd::type regCmd,
int32_t uptCmd) {
CTHRIFT_LOG_WARN("OnRegisterService default.");
return -1;
}
int32_t OnGetSrvList(ServicePtr service, const int64_t rcv_watcher_time) {
CTHRIFT_LOG_WARN("OnGetSrvList default.");
return -1;
}
void OnDestory() {
CTHRIFT_LOG_WARN("OnDestory default.");
return;
}
int32_t OnInit() {
CTHRIFT_LOG_WARN("OnInit default.");
return -1;
}
DestroyFunction destroy_;
InitFunction init_;
RegFunction reg_;
GetFunction get_;
};
} // namespace meituan_cthrift
#endif // CTHRIFT_SRC_CTHRIFT_UTIL_CTHRIFT_NS_INTERFACE_H_
| [
"huixiangbo@meituan.com"
] | huixiangbo@meituan.com |
35d89c0d8128078db87106184c2780cc859632f3 | 96eaebd467794284f338a56b123bdfa5b98dd4d1 | /core/test/lib/boost/boost/geometry/srs/projections/impl/geocent.hpp | cafa064f5a08c792e9bf59cd813b68c0da2990d0 | [
"MIT"
] | permissive | KhalilBellakrid/lib-ledger-core | d80dc1fe0c4e3843eabe373f53df210307895364 | 639f89a64958ee642a2fdb0baf22d2f9da091cc3 | refs/heads/develop | 2021-05-14T07:19:17.424487 | 2019-05-20T20:33:05 | 2019-05-20T20:33:05 | 116,260,592 | 0 | 3 | MIT | 2019-06-26T08:07:16 | 2018-01-04T13:01:57 | C++ | UTF-8 | C++ | false | false | 16,877 | hpp | // Boost.Geometry
// This file is manually converted from PROJ4
// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to 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 file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// This file was converted to Geometry Library by Adam Wulkiewicz
// Original copyright notice:
/***************************************************************************/
/* RSC IDENTIFIER: GEOCENTRIC
*
* ABSTRACT
*
* This component provides conversions between Geodetic coordinates (latitude,
* longitude in radians and height in meters) and Geocentric coordinates
* (X, Y, Z) in meters.
*
* ERROR HANDLING
*
* This component checks parameters for valid values. If an invalid value
* is found, the error code is combined with the current error code using
* the bitwise or. This combining allows multiple error codes to be
* returned. The possible error codes are:
*
* GEOCENT_NO_ERROR : No errors occurred in function
* GEOCENT_LAT_ERROR : Latitude out of valid range
* (-90 to 90 degrees)
* GEOCENT_LON_ERROR : Longitude out of valid range
* (-180 to 360 degrees)
* GEOCENT_A_ERROR : Semi-major axis lessthan or equal to zero
* GEOCENT_B_ERROR : Semi-minor axis lessthan or equal to zero
* GEOCENT_A_LESS_B_ERROR : Semi-major axis less than semi-minor axis
*
*
* REUSE NOTES
*
* GEOCENTRIC is intended for reuse by any application that performs
* coordinate conversions between geodetic coordinates and geocentric
* coordinates.
*
*
* REFERENCES
*
* An Improved Algorithm for Geocentric to Geodetic Coordinate Conversion,
* Ralph Toms, February 1996 UCRL-JC-123138.
*
* Further information on GEOCENTRIC can be found in the Reuse Manual.
*
* GEOCENTRIC originated from : U.S. Army Topographic Engineering Center
* Geospatial Information Division
* 7701 Telegraph Road
* Alexandria, VA 22310-3864
*
* LICENSES
*
* None apply to this component.
*
* RESTRICTIONS
*
* GEOCENTRIC has no restrictions.
*
* ENVIRONMENT
*
* GEOCENTRIC was tested and certified in the following environments:
*
* 1. Solaris 2.5 with GCC version 2.8.1
* 2. Windows 95 with MS Visual C++ version 6
*
* MODIFICATIONS
*
* Date Description
* ---- -----------
* 25-02-97 Original Code
*
*/
#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP
#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP
#include <boost/geometry/util/math.hpp>
namespace boost { namespace geometry { namespace projections
{
namespace detail
{
/***************************************************************************/
/*
* DEFINES
*/
static const long GEOCENT_NO_ERROR = 0x0000;
static const long GEOCENT_LAT_ERROR = 0x0001;
static const long GEOCENT_LON_ERROR = 0x0002;
static const long GEOCENT_A_ERROR = 0x0004;
static const long GEOCENT_B_ERROR = 0x0008;
static const long GEOCENT_A_LESS_B_ERROR = 0x0010;
template <typename T>
struct GeocentricInfo
{
T Geocent_a; /* Semi-major axis of ellipsoid in meters */
T Geocent_b; /* Semi-minor axis of ellipsoid */
T Geocent_a2; /* Square of semi-major axis */
T Geocent_b2; /* Square of semi-minor axis */
T Geocent_e2; /* Eccentricity squared */
T Geocent_ep2; /* 2nd eccentricity squared */
};
template <typename T>
inline T COS_67P5()
{
/*return 0.38268343236508977*/;
return cos(T(67.5) * math::d2r<T>()); /* cosine of 67.5 degrees */
}
template <typename T>
inline T AD_C()
{
return 1.0026000; /* Toms region 1 constant */
}
/***************************************************************************/
/*
* FUNCTIONS
*/
template <typename T>
inline long pj_Set_Geocentric_Parameters (GeocentricInfo<T> & gi, T const& a, T const& b)
{ /* BEGIN Set_Geocentric_Parameters */
/*
* The function Set_Geocentric_Parameters receives the ellipsoid parameters
* as inputs and sets the corresponding state variables.
*
* a : Semi-major axis, in meters. (input)
* b : Semi-minor axis, in meters. (input)
*/
long Error_Code = GEOCENT_NO_ERROR;
if (a <= 0.0)
Error_Code |= GEOCENT_A_ERROR;
if (b <= 0.0)
Error_Code |= GEOCENT_B_ERROR;
if (a < b)
Error_Code |= GEOCENT_A_LESS_B_ERROR;
if (!Error_Code)
{
gi.Geocent_a = a;
gi.Geocent_b = b;
gi.Geocent_a2 = a * a;
gi.Geocent_b2 = b * b;
gi.Geocent_e2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_a2;
gi.Geocent_ep2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_b2;
}
return (Error_Code);
} /* END OF Set_Geocentric_Parameters */
template <typename T>
inline void pj_Get_Geocentric_Parameters (GeocentricInfo<T> const& gi,
T & a,
T & b)
{ /* BEGIN Get_Geocentric_Parameters */
/*
* The function Get_Geocentric_Parameters returns the ellipsoid parameters
* to be used in geocentric coordinate conversions.
*
* a : Semi-major axis, in meters. (output)
* b : Semi-minor axis, in meters. (output)
*/
a = gi.Geocent_a;
b = gi.Geocent_b;
} /* END OF Get_Geocentric_Parameters */
template <typename T>
inline long pj_Convert_Geodetic_To_Geocentric (GeocentricInfo<T> const& gi,
T Longitude, T Latitude, T Height,
T & X, T & Y, T & Z)
{ /* BEGIN Convert_Geodetic_To_Geocentric */
/*
* The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
* (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
* according to the current ellipsoid parameters.
*
* Latitude : Geodetic latitude in radians (input)
* Longitude : Geodetic longitude in radians (input)
* Height : Geodetic height, in meters (input)
* X : Calculated Geocentric X coordinate, in meters (output)
* Y : Calculated Geocentric Y coordinate, in meters (output)
* Z : Calculated Geocentric Z coordinate, in meters (output)
*
*/
long Error_Code = GEOCENT_NO_ERROR;
T Rn; /* Earth radius at location */
T Sin_Lat; /* sin(Latitude) */
T Sin2_Lat; /* Square of sin(Latitude) */
T Cos_Lat; /* cos(Latitude) */
static const T PI = math::pi<T>();
static const T PI_OVER_2 = math::half_pi<T>();
/*
** Don't blow up if Latitude is just a little out of the value
** range as it may just be a rounding issue. Also removed longitude
** test, it should be wrapped by cos() and sin(). NFW for PROJ.4, Sep/2001.
*/
if( Latitude < -PI_OVER_2 && Latitude > -1.001 * PI_OVER_2 )
Latitude = -PI_OVER_2;
else if( Latitude > PI_OVER_2 && Latitude < 1.001 * PI_OVER_2 )
Latitude = PI_OVER_2;
else if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2))
{ /* Latitude out of range */
Error_Code |= GEOCENT_LAT_ERROR;
}
if (!Error_Code)
{ /* no errors */
if (Longitude > PI)
Longitude -= (2*PI);
Sin_Lat = sin(Latitude);
Cos_Lat = cos(Latitude);
Sin2_Lat = Sin_Lat * Sin_Lat;
Rn = gi.Geocent_a / (sqrt(1.0e0 - gi.Geocent_e2 * Sin2_Lat));
X = (Rn + Height) * Cos_Lat * cos(Longitude);
Y = (Rn + Height) * Cos_Lat * sin(Longitude);
Z = ((Rn * (1 - gi.Geocent_e2)) + Height) * Sin_Lat;
}
return (Error_Code);
} /* END OF Convert_Geodetic_To_Geocentric */
/*
* The function Convert_Geocentric_To_Geodetic converts geocentric
* coordinates (X, Y, Z) to geodetic coordinates (latitude, longitude,
* and height), according to the current ellipsoid parameters.
*
* X : Geocentric X coordinate, in meters. (input)
* Y : Geocentric Y coordinate, in meters. (input)
* Z : Geocentric Z coordinate, in meters. (input)
* Latitude : Calculated latitude value in radians. (output)
* Longitude : Calculated longitude value in radians. (output)
* Height : Calculated height value, in meters. (output)
*/
#define BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD
template <typename T>
inline void pj_Convert_Geocentric_To_Geodetic (GeocentricInfo<T> const& gi,
T X, T Y, T Z,
T & Longitude, T & Latitude, T & Height)
{ /* BEGIN Convert_Geocentric_To_Geodetic */
static const T PI_OVER_2 = math::half_pi<T>();
#if !defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD)
static const T COS_67P5 = detail::COS_67P5<T>();
static const T AD_C = detail::AD_C<T>();
/*
* The method used here is derived from 'An Improved Algorithm for
* Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
*/
/* Note: Variable names follow the notation used in Toms, Feb 1996 */
T W; /* distance from Z axis */
T W2; /* square of distance from Z axis */
T T0; /* initial estimate of vertical component */
T T1; /* corrected estimate of vertical component */
T S0; /* initial estimate of horizontal component */
T S1; /* corrected estimate of horizontal component */
T Sin_B0; /* sin(B0), B0 is estimate of Bowring aux variable */
T Sin3_B0; /* cube of sin(B0) */
T Cos_B0; /* cos(B0) */
T Sin_p1; /* sin(phi1), phi1 is estimated latitude */
T Cos_p1; /* cos(phi1) */
T Rn; /* Earth radius at location */
T Sum; /* numerator of cos(phi1) */
bool At_Pole; /* indicates location is in polar region */
At_Pole = false;
if (X != 0.0)
{
Longitude = atan2(Y,X);
}
else
{
if (Y > 0)
{
Longitude = PI_OVER_2;
}
else if (Y < 0)
{
Longitude = -PI_OVER_2;
}
else
{
At_Pole = true;
Longitude = 0.0;
if (Z > 0.0)
{ /* north pole */
Latitude = PI_OVER_2;
}
else if (Z < 0.0)
{ /* south pole */
Latitude = -PI_OVER_2;
}
else
{ /* center of earth */
Latitude = PI_OVER_2;
Height = -Geocent_b;
return;
}
}
}
W2 = X*X + Y*Y;
W = sqrt(W2);
T0 = Z * AD_C;
S0 = sqrt(T0 * T0 + W2);
Sin_B0 = T0 / S0;
Cos_B0 = W / S0;
Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;
T1 = Z + gi.Geocent_b * gi.Geocent_ep2 * Sin3_B0;
Sum = W - gi.Geocent_a * gi.Geocent_e2 * Cos_B0 * Cos_B0 * Cos_B0;
S1 = sqrt(T1*T1 + Sum * Sum);
Sin_p1 = T1 / S1;
Cos_p1 = Sum / S1;
Rn = gi.Geocent_a / sqrt(1.0 - gi.Geocent_e2 * Sin_p1 * Sin_p1);
if (Cos_p1 >= COS_67P5)
{
Height = W / Cos_p1 - Rn;
}
else if (Cos_p1 <= -COS_67P5)
{
Height = W / -Cos_p1 - Rn;
}
else
{
Height = Z / Sin_p1 + Rn * (gi.Geocent_e2 - 1.0);
}
if (At_Pole == false)
{
Latitude = atan(Sin_p1 / Cos_p1);
}
#else /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */
/*
* Reference...
* ============
* Wenzel, H.-G.(1985): Hochauflösende Kugelfunktionsmodelle für
* das Gravitationspotential der Erde. Wiss. Arb. Univ. Hannover
* Nr. 137, p. 130-131.
* Programmed by GGA- Leibniz-Institute of Applied Geophysics
* Stilleweg 2
* D-30655 Hannover
* Federal Republic of Germany
* Internet: www.gga-hannover.de
*
* Hannover, March 1999, April 2004.
* see also: comments in statements
* remarks:
* Mathematically exact and because of symmetry of rotation-ellipsoid,
* each point (X,Y,Z) has at least two solutions (Latitude1,Longitude1,Height1) and
* (Latitude2,Longitude2,Height2). Is point=(0.,0.,Z) (P=0.), so you get even
* four solutions, every two symmetrical to the semi-minor axis.
* Here Height1 and Height2 have at least a difference in order of
* radius of curvature (e.g. (0,0,b)=> (90.,0.,0.) or (-90.,0.,-2b);
* (a+100.)*(sqrt(2.)/2.,sqrt(2.)/2.,0.) => (0.,45.,100.) or
* (0.,225.,-(2a+100.))).
* The algorithm always computes (Latitude,Longitude) with smallest |Height|.
* For normal computations, that means |Height|<10000.m, algorithm normally
* converges after to 2-3 steps!!!
* But if |Height| has the amount of length of ellipsoid's axis
* (e.g. -6300000.m), algorithm needs about 15 steps.
*/
/* local definitions and variables */
/* end-criterium of loop, accuracy of sin(Latitude) */
static const T genau = 1.E-12;
static const T genau2 = (genau*genau);
static const int maxiter = 30;
T P; /* distance between semi-minor axis and location */
T RR; /* distance between center and location */
T CT; /* sin of geocentric latitude */
T ST; /* cos of geocentric latitude */
T RX;
T RK;
T RN; /* Earth radius at location */
T CPHI0; /* cos of start or old geodetic latitude in iterations */
T SPHI0; /* sin of start or old geodetic latitude in iterations */
T CPHI; /* cos of searched geodetic latitude */
T SPHI; /* sin of searched geodetic latitude */
T SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
int iter; /* # of continuous iteration, max. 30 is always enough (s.a.) */
P = sqrt(X*X+Y*Y);
RR = sqrt(X*X+Y*Y+Z*Z);
/* special cases for latitude and longitude */
if (P/gi.Geocent_a < genau) {
/* special case, if P=0. (X=0., Y=0.) */
Longitude = 0.;
/* if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
* of ellipsoid (=center of mass), Latitude becomes PI/2 */
if (RR/gi.Geocent_a < genau) {
Latitude = PI_OVER_2;
Height = -gi.Geocent_b;
return ;
}
}
else {
/* ellipsoidal (geodetic) longitude
* interval: -PI < Longitude <= +PI */
Longitude=atan2(Y,X);
}
/* --------------------------------------------------------------
* Following iterative algorithm was developed by
* "Institut für Erdmessung", University of Hannover, July 1988.
* Internet: www.ife.uni-hannover.de
* Iterative computation of CPHI,SPHI and Height.
* Iteration of CPHI and SPHI to 10**-12 radian resp.
* 2*10**-7 arcsec.
* --------------------------------------------------------------
*/
CT = Z/RR;
ST = P/RR;
RX = 1.0/sqrt(1.0-gi.Geocent_e2*(2.0-gi.Geocent_e2)*ST*ST);
CPHI0 = ST*(1.0-gi.Geocent_e2)*RX;
SPHI0 = CT*RX;
iter = 0;
/* loop to find sin(Latitude) resp. Latitude
* until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
do
{
iter++;
RN = gi.Geocent_a/sqrt(1.0-gi.Geocent_e2*SPHI0*SPHI0);
/* ellipsoidal (geodetic) height */
Height = P*CPHI0+Z*SPHI0-RN*(1.0-gi.Geocent_e2*SPHI0*SPHI0);
RK = gi.Geocent_e2*RN/(RN+Height);
RX = 1.0/sqrt(1.0-RK*(2.0-RK)*ST*ST);
CPHI = ST*(1.0-RK)*RX;
SPHI = CT*RX;
SDPHI = SPHI*CPHI0-CPHI*SPHI0;
CPHI0 = CPHI;
SPHI0 = SPHI;
}
while (SDPHI*SDPHI > genau2 && iter < maxiter);
/* ellipsoidal (geodetic) latitude */
Latitude=atan(SPHI/fabs(CPHI));
return;
#endif /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */
} /* END OF Convert_Geocentric_To_Geodetic */
} // namespace detail
}}} // namespace boost::geometry::projections
#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP
| [
"andrii.korol@ledger.fr"
] | andrii.korol@ledger.fr |
01369255b05c85713969aa9afa52b4604697d031 | d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9 | /testcases/CWE190_Integer_Overflow/s01/CWE190_Integer_Overflow__int64_t_fscanf_multiply_43.cpp | ef20517bd1d8d24e1414a3fb37191c47a0fefe6b | [] | no_license | arichardson/juliet-test-suite-c | cb71a729716c6aa8f4b987752272b66b1916fdaa | e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9 | refs/heads/master | 2022-12-10T12:05:51.179384 | 2022-11-17T15:41:30 | 2022-12-01T15:25:16 | 179,281,349 | 34 | 34 | null | 2022-12-01T15:25:18 | 2019-04-03T12:03:21 | null | UTF-8 | C++ | false | false | 3,455 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_fscanf_multiply_43.cpp
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-43.tmpl.cpp
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: multiply
* GoodSink: Ensure there will not be an overflow before multiplying data by 2
* BadSink : If data is positive, multiply by 2, which can cause an overflow
* Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
*
* */
#include <inttypes.h>
#include "std_testcase.h"
namespace CWE190_Integer_Overflow__int64_t_fscanf_multiply_43
{
#ifndef OMITBAD
static void badSource(int64_t &data)
{
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
}
void bad()
{
int64_t data;
data = 0LL;
badSource(data);
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > LLONG_MAX, this will overflow */
int64_t result = data * 2;
printLongLongLine(result);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(int64_t &data)
{
/* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
data = 2;
}
static void goodG2B()
{
int64_t data;
data = 0LL;
goodG2BSource(data);
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > LLONG_MAX, this will overflow */
int64_t result = data * 2;
printLongLongLine(result);
}
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSource(int64_t &data)
{
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
}
static void goodB2G()
{
int64_t data;
data = 0LL;
goodB2GSource(data);
if(data > 0) /* ensure we won't have an underflow */
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < (LLONG_MAX/2))
{
int64_t result = data * 2;
printLongLongLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
void good()
{
goodG2B();
goodB2G();
}
#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 CWE190_Integer_Overflow__int64_t_fscanf_multiply_43; /* 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
| [
"Alexander.Richardson@cl.cam.ac.uk"
] | Alexander.Richardson@cl.cam.ac.uk |
e27789c0e8848718abda957663bb207dd2bdedb4 | 4a18656e5e113c2a684830c8466d4f4ceccc43eb | /WebKit/ea/Api/EAWebKit/source/internal/source/EAWebKitDll.cpp | bc03283bbd4048cf3cd0d5856b29b000ef20b8df | [
"BSD-2-Clause"
] | permissive | ychin/EAWebKit | a0159b005427946e54b3faf4c4295859f8e4e7d5 | f8b5c9ba619eb80a2a06a073e2aaa08f039a2954 | refs/heads/master | 2023-03-08T14:28:53.888399 | 2023-02-28T23:58:53 | 2023-02-28T23:59:42 | 67,105,099 | 47 | 16 | null | 2019-11-04T03:54:24 | 2016-09-01T06:38:31 | Objective-C | UTF-8 | C++ | false | false | 3,990 | cpp | /*
Copyright (C) 2013 Electronic Arts, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
////////////////////////////////////////////////////////////////////
// EAWebKitDll.cpp
// By Arpit Baldeva
// Maintained by EAWebKit Team
//
// The purpose of this file is isolate dll export related code.
///////////////////////////////////////////////////////////////////
#include "config.h"
#include <EAWebKit/EAWebKitDll.h>
#include <EAWebKit/EAWebKit.h>
#if defined(EA_PLATFORM_MICROSOFT)
#pragma warning(push)
#pragma warning(disable: 4255)
#include EAWEBKIT_PLATFORM_HEADER
#pragma warning(pop)
#endif
#if BUILDING_EAWEBKIT_DLL
extern "C" EA::WebKit::EAWebKitLib* CreateEAWebkitInstance(void)
{
//Note by Arpit Baldeva: WTF::fastNew calls EAWebkit allocator under the hood. Since the first thing we do after loading the relocatable module is to
//create an instance, the application does not have a chance to setup the allocator. So if we use EAWebkit's default allocator for creating the
//concrete instance and later the application swaps out the allocator with a its own supplied allocator, we would end up freeing the ConcreteInstance
//from an allocator that did not create it. The solution is to either use a global new/delete operator or create a static EAWebkitConcrete instance.
//I chose to make a static in case we decide to overrride global new/delete for the relocatable module in the future. Then, we would avoid inadvertently
//creating the instance from one allocator and freeing it using another.
static EA::WebKit::EAWebKitLib concreteInstance;
return &concreteInstance;
}
extern "C" int EAWebKitDllStart(size_t /*argc*/, const void* /*argp*/)
{
return PLATFORM_DLL_START_SUCCESS;
}
extern "C" int EAWebKitDllStop(size_t /*argc*/, const void* /*argp*/)
{
return PLATFORM_DLL_STOP_SUCCESS;
}
PLATFORM_DLL_START(EAWebKitDllStart);
PLATFORM_DLL_STOP(EAWebKitDllStop);
#if defined(EA_PLATFORM_MICROSOFT)
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
);
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
BOOL returnValue = TRUE;
switch( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH:
if(platform_dll_start_func() != PLATFORM_DLL_START_SUCCESS)
returnValue = FALSE;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
if(platform_dll_stop_func() != PLATFORM_DLL_STOP_SUCCESS)
returnValue = FALSE;
break;
}
return returnValue;
}
#endif
#endif //BUILDING_EAWEBKIT_DLL
| [
"ychin.git@gmail.com"
] | ychin.git@gmail.com |
ece779e0b82ef9d54f7c778d3e77aa03cdf909ff | e5208879e4425f382207aa3de8c248b84e221e3a | /ECS/TransformComponent.hpp | c907350aeca739b69b5c2b4f08e34053f6075529 | [] | no_license | MaximKalani/LauEngine | a709b87aa9215c31150319a5299ddffd361d1e44 | ead426ddaf6a8369a727cb5b154855fb65933d06 | refs/heads/master | 2020-04-22T00:07:24.153632 | 2019-03-26T19:24:33 | 2019-03-26T19:24:33 | 169,968,459 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | hpp | #ifndef TRANSFORMCOMPONENT_HPP_INCLUDED
#define TRANSFORMCOMPONENT_HPP_INCLUDED
#include "Components.hpp"
#include "../Vector2D.hpp"
#include "../engine.hpp"
class TransformComponent : public Component
{
public:
Vector2D position;
Vector2D lastPosition;
Vector2D velocity;
Vector2D lastDirection;
int height = 16;
int width = 16;
int scale = 1;
int speed = 3;
bool isInverted = false;
TransformComponent()
{
position.x = 0.0f;
position.y = 0.0f;
}
TransformComponent(int sc)
{
position.x = 0.0f;
position.y = 0.0f;
scale = sc;
}
TransformComponent(float x, float y)
{
position.x = x;
position.y = y;
}
TransformComponent(float x, float y, int h, int w, int sc)
{
position.x = x;
position.y = y;
height = h;
width = w;
scale = sc;
}
void init() override
{
velocity.x = 0;
velocity.y = 0;
lastDirection.x = 1;
lastDirection.y = 0;
}
void update() override
{
lastPosition = position;
if(velocity.x != 0 || velocity.y != 0)
lastDirection = velocity;
position.x += static_cast<int>(velocity.x * speed);
position.y += static_cast<int>(velocity.y * speed);
}
};
#endif | [
"kalanimaxim@gmail.com"
] | kalanimaxim@gmail.com |
6708082fd29fd6261a3d13b87619047a1b4cf25d | 1d757454ff3655b90949ec7478e8e741d154c8cf | /uva/11475.cpp | 1149121df9d1e2649795e7fdfa9ce98f550eeae1 | [] | no_license | manoj9april/cp-solutions | 193b588e0f4690719fe292ac404a8c1f592b8c78 | 41141298600c1e7b9ccb6e26174f797744ed6ac1 | refs/heads/master | 2021-07-12T17:52:21.578577 | 2021-06-20T16:23:05 | 2021-06-20T16:23:05 | 249,103,555 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,499 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ini(arr, val) memset(arr, (val), sizeof(arr))
#define loop(i,n) for(ll i=0; i<n; i++)
#define loop1(i,n) for(ll i=1; i<=n; i++)
#define all(a) (a).begin(),(a).end()
#define exist(s,e) (s.find(e)!=s.end())
#define dbg(x) cout << #x << " is " << x << endl
#define pt(x) cout<<x<<"\n"
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define inf (int)1e9
#define infll 1e18
#define eps 1e-9
#define PI 3.1415926535897932384626433832795
#define mod 1000000007
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define test int t; cin>>t; while(t--)
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<vi> vvi;
typedef map<int,int> mii;
typedef set<int> si;
typedef pair<ll, ll> pll;
typedef vector<ll> vl;
typedef vector<string> vs;
typedef vector<pll> vpll;
typedef vector<vl> vvl;
typedef map<ll,ll> mll;
typedef set<ll> sl;
int dirx[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int diry[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
//////////////////////////////////////////////////////////////////////////////////////////
// main starts
//////////////////////////////////////////////////////////////////////////////////////////
int const lmt=1e5+5;
int d1[lmt], d2[lmt];
string s;
void manacher(){
int l=0,r=-1,n=s.length();
for(int i=0; i<n; i++){
int k = (i>r?1:min(d1[l+r-i], r-i+1));
while(i-k>=0 && i+k<n && s[i-k]==s[i+k]) k++;
d1[i]=k--;
if(i+k>r){
r = i+k;
l = i-k;
}
}
l=0,r=-1,n=s.length();
for(int i=0; i<n; i++){
int k = (i>r?0:min(d2[l+r-i+1], r-i+1));
while(i-k-1>=0 && i+k<n && s[i-k-1]==s[i+k]) k++;
d2[i]=k--;
if(i+k>r){
r = i+k;
l = i-k-1;
}
}
}
int main(){
// #ifndef ONLINE_JUDGE
// freopen("../input.txt", "r", stdin);
// freopen("../output.txt", "w", stdout);
// #endif
fast
while(cin>>s){
manacher();
int n = s.length();
int lo=n-1;
for(int i=n-1; i>=0; i--){
if(i+d1[i]==n) lo = min(lo,i-d1[i]+1);
if(i+d2[i]==n) lo = min(lo,i-d2[i]);
// cout<<d1[i]<<" ";
}
// pt("");
string ans = s.substr(0,lo);
reverse(all(ans));
pt(s+ans);
}
}
/*
//
*/
| [
"manoj9april@gmail.com"
] | manoj9april@gmail.com |
c510a32feffeb395c54b28a38fbf82424e31eda5 | 8391bd7a9e822543057c65796e865fc6c716332e | /qCC/moc_ccPlaneEditDlg.cpp | 86013949773cea30ae7df05aa67ecae51c38de69 | [] | no_license | chaoxs0820/LearnCC | 79f38171699d0a162161fb7ccbb1e0568a509080 | d57471d6067282df5c9bc81464641b9b1e2c1909 | refs/heads/master | 2020-12-03T01:39:47.873466 | 2017-06-30T05:14:34 | 2017-06-30T05:14:34 | 95,851,670 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,944 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'ccPlaneEditDlg.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../CloudCompare-master/qCC/ccPlaneEditDlg.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ccPlaneEditDlg.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_ccPlaneEditDlg_t {
QByteArrayData data[4];
char stringdata0[54];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ccPlaneEditDlg_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ccPlaneEditDlg_t qt_meta_stringdata_ccPlaneEditDlg = {
{
QT_MOC_LITERAL(0, 0, 14), // "ccPlaneEditDlg"
QT_MOC_LITERAL(1, 15, 17), // "pickPointAsCenter"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 19) // "saveParamsAndAccept"
},
"ccPlaneEditDlg\0pickPointAsCenter\0\0"
"saveParamsAndAccept"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ccPlaneEditDlg[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x0a /* Public */,
3, 0, 27, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void,
0 // eod
};
void ccPlaneEditDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
ccPlaneEditDlg *_t = static_cast<ccPlaneEditDlg *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->pickPointAsCenter((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 1: _t->saveParamsAndAccept(); break;
default: ;
}
}
}
const QMetaObject ccPlaneEditDlg::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_ccPlaneEditDlg.data,
qt_meta_data_ccPlaneEditDlg, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *ccPlaneEditDlg::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ccPlaneEditDlg::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_ccPlaneEditDlg.stringdata0))
return static_cast<void*>(const_cast< ccPlaneEditDlg*>(this));
if (!strcmp(_clname, "ccPickingListener"))
return static_cast< ccPickingListener*>(const_cast< ccPlaneEditDlg*>(this));
if (!strcmp(_clname, "Ui::PlaneEditDlg"))
return static_cast< Ui::PlaneEditDlg*>(const_cast< ccPlaneEditDlg*>(this));
return QDialog::qt_metacast(_clname);
}
int ccPlaneEditDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"1529822217@qq.com"
] | 1529822217@qq.com |
e730990f26fbb10c572a75a33f0d93293f85e270 | 97702ef80284eb8403e42a94573630b260d86c0e | /include/Costume.h | b43c6127357e45b022ed3728b9d5d33856ff7f48 | [
"MIT"
] | permissive | neuromancer/engge | dcd8e35faa5634d4835d77335cfe8709b0b80e20 | 54d8b6a51d504353c20333bc7ab2c93c0fb77448 | refs/heads/master | 2020-05-01T13:05:11.784449 | 2019-03-24T23:30:08 | 2019-03-24T23:30:08 | 175,086,395 | 0 | 0 | MIT | 2019-03-11T21:27:26 | 2019-03-11T21:27:26 | null | UTF-8 | C++ | false | false | 1,815 | h | #pragma once
#include <sstream>
#include <set>
#include "SFML/Graphics.hpp"
#include "NonCopyable.h"
#include "EngineSettings.h"
#include "TextureManager.h"
#include "CostumeAnimation.h"
namespace ng
{
enum class Facing
{
FACE_FRONT,
FACE_BACK,
FACE_LEFT,
FACE_RIGHT
};
class Actor;
class Costume : public sf::Drawable
{
public:
explicit Costume(TextureManager &textureManager);
~Costume();
void loadCostume(const std::string &name, const std::string &sheet = "");
void lockFacing(Facing facing);
void setFacing(Facing facing);
Facing getFacing() const { return _facing; }
void setState(const std::string &name);
bool setAnimation(const std::string &name);
const std::string &getAnimationName() const { return _animation; }
const CostumeAnimation *getAnimation() const { return _pCurrentAnimation.get(); }
CostumeAnimation *getAnimation() { return _pCurrentAnimation.get(); }
void setLayerVisible(const std::string &name, bool isVisible);
void setHeadIndex(int index);
void setAnimationNames(const std::string &headAnim, const std::string &standAnim, const std::string &walkAnim, const std::string &reachAnim);
void setActor(Actor *pActor) { _pActor = pActor; }
void update(const sf::Time &elapsed);
private:
void draw(sf::RenderTarget &target, sf::RenderStates states) const override;
void updateAnimation();
private:
EngineSettings &_settings;
TextureManager &_textureManager;
std::string _path;
std::string _sheet;
std::unique_ptr<CostumeAnimation> _pCurrentAnimation;
sf::Texture _texture;
Facing _facing;
std::string _animation;
std::set<std::string> _hiddenLayers;
std::string _headAnimName;
std::string _standAnimName;
std::string _walkAnimName;
std::string _reachAnimName;
int _headIndex;
Actor *_pActor;
};
} // namespace ng | [
"scemino74@gmail.com"
] | scemino74@gmail.com |
97cffd0a7ef3737bb28554d5ee55094380633dce | 93b24e6296dade8306b88395648377e1b2a7bc8c | /client/OGRE/PlatformManagers/GLX/include/OgreGLXInput.h | 8cedc73cb79daae89322167d9c5ef6e85a440315 | [] | no_license | dahahua/pap_wclinet | 79c5ac068cd93cbacca5b3d0b92e6c9cba11a893 | d0cde48be4d63df4c4072d4fde2e3ded28c5040f | refs/heads/master | 2022-01-19T21:41:22.000190 | 2013-10-12T04:27:59 | 2013-10-12T04:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,834 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
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, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __GLXInputReader_H__
#define __GLXInputReader_H__
#include "OgreInput.h"
#include "OgreInputEvent.h"
#include "OgreRenderWindow.h"
#include <map>
#include <set>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/Xproto.h>
namespace Ogre {
class GLXInput : public InputReader {
public:
GLXInput();
virtual ~GLXInput();
void initialise( RenderWindow* pWindow, bool useKeyboard = true, bool useMouse = true, bool useGameController = false );
void capture();
/*
* Mouse getters
*/
virtual long getMouseRelX() const;
virtual long getMouseRelY() const;
virtual long getMouseRelZ() const;
virtual long getMouseAbsX() const;
virtual long getMouseAbsY() const;
virtual long getMouseAbsZ() const;
virtual void getMouseState( MouseState& state ) const;
virtual bool getMouseButton( uchar button ) const;
private:
CARD32 mHiddenCursor;
// Map of X keys -> Ogre keys
typedef std::map<KeySym, KeyCode> InputKeyMap;
InputKeyMap _key_map;
// Map of currently pressed keys
typedef std::set<KeyCode> KeyPressedSet;
KeyPressedSet _key_pressed_set;
// Does the ogre input system want to capture the mouse (set with useMouse flag
// on initialise)
bool captureMouse;
// Is mouse currently warped (captured within window?)
bool warpMouse;
int mouseLastX, mouseLastY;
// Display and window, for event pumping
Display *mDisplay;
Window mWindow;
RenderWindow *mRenderWindow;
bool mMouseWarped;
static const unsigned int mWheelStep = 100;
void GrabCursor(bool grab);
bool isKeyDownImmediate( KeyCode kc ) const;
};
}; // Namespace
#endif
| [
"viticm@126.com"
] | viticm@126.com |
966f244ad39a565d7b584cf4d02ad157a700d13e | 4dfa10de8e96fa8f11129d8865e8b0dda0878d20 | /haptic_bridge/Tool/log.h | 7bf3e3b61dd6201ee3a6d48817be1c8f0c94f962 | [] | no_license | tjh-flash/WokeRepository | 8d137f252cde4d849ad7095b9eee4c9d16a3fb41 | d1bc8498d27887e597f9539901b8fd8ecee5e165 | refs/heads/master | 2023-03-27T07:39:53.815869 | 2021-03-31T07:42:02 | 2021-03-31T07:42:02 | 353,265,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | #pragma once
#include <iostream>
#include <vector>
using namespace std;
class Log
{
public:
~Log();
static Log* getInstance()
{
if (ptr == nullptr)
ptr = new Log();
return ptr;
}
template<class T>
static void debug( const vector<T> &data) {
for (auto it : data)
cout << it << " ";
cout << endl;
}
template<class T>
static void debug(const char* tille, const vector<T> &data) {
cout << "#Debug :" << tille<<" " ;
debug(data);
//for (auto it : data)
// cout << it << " ";
//cout << endl;
}
template<class T>
static void Erron(const vector<T> &data) {
for (auto it : data)
cerr << it << " ";
cerr << endl;
}
private:
Log();
private:
static Log* ptr;
};
| [
"fshs@163.com"
] | fshs@163.com |
c72a2ffee1c4606fb4f4a51099af881ca62738d1 | 927c2b11739dccab27a44d5c1c76bbbc38add8f1 | /Summber Camp/ZUCC Summer Camp 2017/Contest1/HDU 6033 Add More Zero(水题).cpp | c1f095495fd106bc46e33db4a5338be6e59604c6 | [] | 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 | 571 | cpp | #include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define lson l, mid, rt << 1
#define rson mid+1, r, rt << 1 | 1
#define ls rt << 1
#define rs rt << 1 | 1
#define MS(x, y) memset(x, y, sizeof(x))
using namespace std;
typedef long long LL;
int main() {
int kase = 0;
int x;
while (scanf("%d",&x) == 1) {
int res = x * log(2) / log(10);
printf("Case #%d: %d\n",++kase, res);
}
return 0;
}
| [
"31501293@stu.zucc.edu.cn"
] | 31501293@stu.zucc.edu.cn |
f9dbab42a3b46aefc042a23d5e1f24e2df4b1a09 | 562aaeeb36128a12f31245b49b52584409ac9e79 | /10.0.15063.0/winrt/internal/Windows.Devices.WiFiDirect.Services.2.h | 58f86cec6b1f4db17e56dd43312954ac7907e27f | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | PlainRubbish/cppwinrt | af6b2fde4bb56a8c310f338b440e8db7943e2f2e | 532b09e3796bd883394f510ce7b4c35a2fc75743 | refs/heads/master | 2021-01-19T05:06:17.990730 | 2017-03-31T20:03:28 | 2017-03-31T20:03:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,238 | h | // C++ for the Windows Runtime v1.0.170331.7
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.WiFiDirect.Services.1.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_8780a851_6d48_5006_9288_81f3d7045a96
#define WINRT_GENERIC_8780a851_6d48_5006_9288_81f3d7045a96
template <> struct __declspec(uuid("8780a851-6d48-5006-9288-81f3d7045a96")) __declspec(novtable) IVectorView<Windows::Networking::EndpointPair> : impl_IVectorView<Windows::Networking::EndpointPair> {};
#endif
#ifndef WINRT_GENERIC_d7ec83c4_a17b_51bf_8997_aa33b9102dc9
#define WINRT_GENERIC_d7ec83c4_a17b_51bf_8997_aa33b9102dc9
template <> struct __declspec(uuid("d7ec83c4-a17b-51bf-8997-aa33b9102dc9")) __declspec(novtable) IIterable<Windows::Networking::EndpointPair> : impl_IIterable<Windows::Networking::EndpointPair> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_f6a6f91c_0579_565d_be07_4538a55690be
#define WINRT_GENERIC_f6a6f91c_0579_565d_be07_4538a55690be
template <> struct __declspec(uuid("f6a6f91c-0579-565d-be07-4538a55690be")) __declspec(novtable) IVector<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> : impl_IVector<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_cb98fd74_871d_5730_91fe_81ef947fe78f
#define WINRT_GENERIC_cb98fd74_871d_5730_91fe_81ef947fe78f
template <> struct __declspec(uuid("cb98fd74-871d-5730-91fe-81ef947fe78f")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequestedEventArgs> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequestedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_3be2d508_a856_5c09_9998_522597b44b07
#define WINRT_GENERIC_3be2d508_a856_5c09_9998_522597b44b07
template <> struct __declspec(uuid("3be2d508-a856-5c09-9998-522597b44b07")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAutoAcceptSessionConnectedEventArgs> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAutoAcceptSessionConnectedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_67fc3121_c1a0_5c23_af58_ecb7f2a7d773
#define WINRT_GENERIC_67fc3121_c1a0_5c23_af58_ecb7f2a7d773
template <> struct __declspec(uuid("67fc3121-c1a0-5c23-af58-ecb7f2a7d773")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_c2da4e97_728b_5401_a9d9_3a0185450af2
#define WINRT_GENERIC_c2da4e97_728b_5401_a9d9_3a0185450af2
template <> struct __declspec(uuid("c2da4e97-728b-5401-a9d9-3a0185450af2")) __declspec(novtable) IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession> : impl_IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession> {};
#endif
#ifndef WINRT_GENERIC_c4fa2ae8_4ff7_5aa0_af97_ed85ea66f9ae
#define WINRT_GENERIC_c4fa2ae8_4ff7_5aa0_af97_ed85ea66f9ae
template <> struct __declspec(uuid("c4fa2ae8-4ff7-5aa0-af97-ed85ea66f9ae")) __declspec(novtable) IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectService> : impl_IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectService> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_dc710fe1_7f04_515b_8ac1_1c5d3c0d2b28
#define WINRT_GENERIC_dc710fe1_7f04_515b_8ac1_1c5d3c0d2b28
template <> struct __declspec(uuid("dc710fe1-7f04-515b-8ac1-1c5d3c0d2b28")) __declspec(novtable) IVectorView<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> : impl_IVectorView<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_fc3dfc2c_9cfa_5822_ba3f_ff3afb65777e
#define WINRT_GENERIC_fc3dfc2c_9cfa_5822_ba3f_ff3afb65777e
template <> struct __declspec(uuid("fc3dfc2c-9cfa-5822-ba3f-ff3afb65777e")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectService, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionDeferredEventArgs> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectService, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionDeferredEventArgs> {};
#endif
#ifndef WINRT_GENERIC_d7fa4dc4_4730_506e_bff0_801eb4a831a8
#define WINRT_GENERIC_d7fa4dc4_4730_506e_bff0_801eb4a831a8
template <> struct __declspec(uuid("d7fa4dc4-4730-506e-bff0-801eb4a831a8")) __declspec(novtable) IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo> : impl_IAsyncOperation<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo> {};
#endif
#ifndef WINRT_GENERIC_10c33301_e31c_5cce_b2a0_c1dc2d8d0e13
#define WINRT_GENERIC_10c33301_e31c_5cce_b2a0_c1dc2d8d0e13
template <> struct __declspec(uuid("10c33301-e31c-5cce-b2a0-c1dc2d8d0e13")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_8326a337_3c19_57a7_80ec_cca2ea62ef12
#define WINRT_GENERIC_8326a337_3c19_57a7_80ec_cca2ea62ef12
template <> struct __declspec(uuid("8326a337-3c19-57a7-80ec-cca2ea62ef12")) __declspec(novtable) TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceRemotePortAddedEventArgs> : impl_TypedEventHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession, Windows::Devices::WiFiDirect::Services::WiFiDirectServiceRemotePortAddedEventArgs> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_f996138f_a866_5ca4_ba46_09fcb2de7013
#define WINRT_GENERIC_f996138f_a866_5ca4_ba46_09fcb2de7013
template <> struct __declspec(uuid("f996138f-a866-5ca4-ba46-09fcb2de7013")) __declspec(novtable) IVector<Windows::Networking::EndpointPair> : impl_IVector<Windows::Networking::EndpointPair> {};
#endif
#ifndef WINRT_GENERIC_c899ff9f_e6f5_5673_810c_04e2ff98704f
#define WINRT_GENERIC_c899ff9f_e6f5_5673_810c_04e2ff98704f
template <> struct __declspec(uuid("c899ff9f-e6f5-5673-810c-04e2ff98704f")) __declspec(novtable) IIterator<Windows::Networking::EndpointPair> : impl_IIterator<Windows::Networking::EndpointPair> {};
#endif
#ifndef WINRT_GENERIC_19889f5e_49ae_5e31_b059_083f9f1532c3
#define WINRT_GENERIC_19889f5e_49ae_5e31_b059_083f9f1532c3
template <> struct __declspec(uuid("19889f5e-49ae-5e31-b059-083f9f1532c3")) __declspec(novtable) IIterator<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> : impl_IIterator<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> {};
#endif
#ifndef WINRT_GENERIC_d9773b1a_a148_58bf_9c4b_afeac9be3ab4
#define WINRT_GENERIC_d9773b1a_a148_58bf_9c4b_afeac9be3ab4
template <> struct __declspec(uuid("d9773b1a-a148-58bf-9c4b-afeac9be3ab4")) __declspec(novtable) IIterable<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> : impl_IIterable<winrt::Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_b29de711_60b8_59da_8f4d_fc79d8ccd422
#define WINRT_GENERIC_b29de711_60b8_59da_8f4d_fc79d8ccd422
template <> struct __declspec(uuid("b29de711-60b8-59da-8f4d-fc79d8ccd422")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession> : impl_AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession> {};
#endif
#ifndef WINRT_GENERIC_f505a3c8_4837_5e0e_8a4d_1e2af5477e5c
#define WINRT_GENERIC_f505a3c8_4837_5e0e_8a4d_1e2af5477e5c
template <> struct __declspec(uuid("f505a3c8-4837-5e0e-8a4d-1e2af5477e5c")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectService> : impl_AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectService> {};
#endif
#ifndef WINRT_GENERIC_94cb9568_040a_5186_a3c9_52680ee17984
#define WINRT_GENERIC_94cb9568_040a_5186_a3c9_52680ee17984
template <> struct __declspec(uuid("94cb9568-040a-5186-a3c9-52680ee17984")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo> : impl_AsyncOperationCompletedHandler<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo> {};
#endif
}
namespace Windows::Devices::WiFiDirect::Services {
struct IWiFiDirectService :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectService>
{
IWiFiDirectService(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceAdvertiser :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceAdvertiser>
{
IWiFiDirectServiceAdvertiser(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceAdvertiserFactory :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceAdvertiserFactory>
{
IWiFiDirectServiceAdvertiserFactory(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceAutoAcceptSessionConnectedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceAutoAcceptSessionConnectedEventArgs>
{
IWiFiDirectServiceAutoAcceptSessionConnectedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceProvisioningInfo :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceProvisioningInfo>
{
IWiFiDirectServiceProvisioningInfo(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceRemotePortAddedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceRemotePortAddedEventArgs>
{
IWiFiDirectServiceRemotePortAddedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceSession :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceSession>,
impl::require<IWiFiDirectServiceSession, Windows::Foundation::IClosable>
{
IWiFiDirectServiceSession(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceSessionDeferredEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceSessionDeferredEventArgs>
{
IWiFiDirectServiceSessionDeferredEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceSessionRequest :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceSessionRequest>,
impl::require<IWiFiDirectServiceSessionRequest, Windows::Foundation::IClosable>
{
IWiFiDirectServiceSessionRequest(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceSessionRequestedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceSessionRequestedEventArgs>
{
IWiFiDirectServiceSessionRequestedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWiFiDirectServiceStatics :
Windows::Foundation::IInspectable,
impl::consume<IWiFiDirectServiceStatics>
{
IWiFiDirectServiceStatics(std::nullptr_t = nullptr) noexcept {}
};
}
}
| [
"kwelton@microsoft.com"
] | kwelton@microsoft.com |
c492db4f8d86bbdeac1cacde94ad2c1432692075 | b5d6bef867559a53ac6cd82b65624458dd20214f | /baekjoon/BOJ10825.cpp | 64ff29ac442befb713598de79c980a2d99656a49 | [] | no_license | jingnee/algorithm | cfb33ab5c5243c2d7752746aadfa9d3017f63072 | 3c99db64c3840a3696bd188b5fbb6b54990303c4 | refs/heads/master | 2022-06-22T22:15:36.838947 | 2022-06-09T09:22:04 | 2022-06-09T09:22:04 | 231,215,092 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | cpp | /*국영수*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int N;
struct Student {
string name;
int kor;
int eng;
int mat;
};
vector<Student> stu;
bool compare(Student &a, Student &b) {
if (a.kor == b.kor) {
if (a.eng == b.eng) {
if (a.mat == b.mat)
return a.name < b.name;
return a.mat > b.mat;
}
return a.eng < b.eng;
}
return a.kor > b.kor;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
for (int i = 0; i < N; i++) {
string name;
int kor, eng, mat;
cin >> name >> kor >> eng >> mat;
stu.push_back({ name,kor,eng,mat });
}
sort(stu.begin(), stu.end(), compare);
for (auto s : stu) {
cout << s.name << "\n";
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b017985556dd223981f523ff144affa394fac142 | 3ef8dadde047804e5b7deaf1976e6ed84124dc66 | /src/main.cpp | 30a36736c01bcff9c3bad5e8743fd9552562214f | [] | no_license | DrPity/hardware-template | f82a412bb23aadab9db7728ad834b1167118d4e5 | f0cbe79a4e69143b5523c78c0b2636255aa01942 | refs/heads/master | 2021-03-29T08:08:03.194596 | 2020-03-17T11:15:32 | 2020-03-17T11:15:32 | 247,935,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | cpp | #include <main.h>
#include <ArduinoJson.h>
#include <stdio.h>
// keep up here; debug define needs to be before the network include
#define DEBUG
#include "debug.h"
#include "helpers.h"
#include "network.h"
#include "config.h"
Network net;
DynamicJsonDocument doc(2048);
long publishTime = 0;
void mqttMessage(String &topic, String &payload)
{
//Handle MQTT messages
Serial.println("incoming: " + topic + " - " + payload);
}
void subscribe()
{
net.subscribeMQTT("/in");
}
void setup()
{
Serial.begin(115200);
net.setup();
net.receiveMessageMQTT(mqttMessage);
doc["Key"] = "Value - Hello from feather";
}
void loop()
{
#ifdef MQTT
if(net.updateMQTT()){
subscribe();
}
if (millis() - publishTime >= 5000){
net.publishMQTT("/out", doc);
publishTime = millis();
}
#endif
}
| [
"schade.mich@gmail.com"
] | schade.mich@gmail.com |
ddd08b7cd97b7b3bcc57028a0f5a33a62451528d | e086a76ea7d5a54f60bf0140063570bfcf097148 | /problemset/stones-on-the-table/main.cpp | 7da14dedaea4918f64e908facff8f83831ce05a7 | [] | no_license | erhemdiputra/codeforces | 476114c5abe1876cad0f6bfc0703626030fab676 | e7e8da616b4bd508f587da6c5be34dcf28744a17 | refs/heads/master | 2020-05-31T23:02:29.235622 | 2019-07-21T07:53:38 | 2019-07-21T07:53:38 | 190,530,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
char arr[100];
int n, counter;
cin>>n;
for (int i = 0; i < n; i++) {
cin>>arr[i];
}
counter = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] == arr[i+1]) {
counter++;
}
}
cout<<counter<<endl;
} | [
"erhem.diputra@tokopedia.com"
] | erhem.diputra@tokopedia.com |
8c952ffd8db93ae7503f96db9a25582aec085ea1 | ed26e4b990a614534f2ee3d4b736ff98e09d2333 | /DirectXFramework/DirectXFramework/FBXLoader.h | b3f5488cd30c863058acecad5241e14b81a6ec90 | [] | no_license | wnddpd01/InhaDirectXTeam | f0b629a055b87fe0d9c14f7ba524ae9ee5a367c9 | 07a8e10d608e51e0f5f352e9878152a8639b427a | refs/heads/master | 2023-03-09T04:51:27.880194 | 2021-03-04T08:43:38 | 2021-03-04T08:43:38 | 298,210,936 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,901 | h | #pragma once
#include "Singleton.h"
#include <fbxsdk.h>
#pragma comment(lib, "libfbxsdk-mt.lib")
#pragma comment(lib, "libxml2-mt.lib")
#pragma comment(lib, "zlib-mt.lib")
#define gFbxLoader FBXLoader::GetInstance()
struct CharacterVertex;
class SkinnedData;
struct BoneIndexAndWeight
{
BYTE BoneIndices;
float BoneWeight;
bool operator < (const BoneIndexAndWeight& rhs)
{
return (BoneIndices > rhs.BoneWeight);
}
};
struct CtrlPoint
{
D3DXVECTOR3 Position;
std::vector<BoneIndexAndWeight> BoneInfo;
std::string BoneName;
CtrlPoint()
{
BoneInfo.reserve(4);
}
void SortBlendingInfoByWeight()
{
std::sort(BoneInfo.begin(), BoneInfo.end());
}
};
class FBXLoader : public Singleton<FBXLoader>
{
private:
FBXLoader(); friend Singleton;
~FBXLoader();
FbxManager* mFbxManager;
FbxScene* mFbxScene;
FbxNode* mFbxNode;
FbxMesh* mFbxMesh;
private:
/*void loadNode(FbxNode* node);
void GetFbxInfo(FbxNode* Node);
void processControlPoints(FbxMesh* mesh, OUT vector<D3DXVECTOR3>& positions);
D3DXVECTOR3 readNormal(const FbxMesh* mesh, int controlPointIndex, int vertexCounter);
D3DXVECTOR3 readBinormal(const FbxGeometryElementBinormal* vertexBinormal, int controlPointIndex, int vertexCounter);
D3DXVECTOR3 readTangent(const FbxGeometryElementTangent* mesh, int controlPointIndex, int vertexCounter);
D3DXVECTOR2 readTexUV(const FbxMesh* mesh, int controlPointIndex, int uvIndex);
D3DXVECTOR3 readNormalByControlPoint(const FbxGeometryElementNormal* vertexNormal, int controlPointIndex);
D3DXVECTOR3 readNormalByPolygonVertex(const FbxGeometryElementNormal* vertexNormal, int vertexCounter);
D3DXVECTOR3 readBinormalByControlPoint(const FbxGeometryElementBinormal* vertexBinormal, int controlPointIndex);
D3DXVECTOR3 readBinormalByPolygonVertex(const FbxGeometryElementBinormal* vertexBinormal, int vertexCounter);
D3DXVECTOR3 readTangentByControlPoint(const FbxGeometryElementTangent* vertexNormal, int controlPointIndex);
D3DXVECTOR3 readTangentByPolygonVertex(const FbxGeometryElementTangent* vertexNormal, int vertexCounter);*/
void GetControlPoints(FbxNode* pFbxRootNode);
void GetVerticesAndIndice(FbxMesh* pMesh, std::vector<CharacterVertex>& outVertexVector,
std::vector<uint32_t>& outIndexVector, SkinnedData* outSkinnedData);
void GetMaterials(FbxNode* node, std::vector<D3DXMATERIAL>& outMaterial);
void GetMaterialAttribute(FbxSurfaceMaterial* material, D3DXMATERIAL& outMaterial);
void GetMaterialTexture(FbxSurfaceMaterial* material, D3DXMATERIAL& mat);
public:
LPD3DXMESH loadFbx(string fileName); // TODO DirectX에 알맞는 아웃풋으로 변경해야함
private:
std::unordered_map<std::int32_t, CtrlPoint*> mControlPoints;
std::vector<std::string> mBoneName;
// skinnedData Output
/*std::vector<int> mBoneHierarchy;
std::vector<D3DXMATRIXA16> mBoneOffsets;
std::unordered_map<std::string, AnimationClip> mAnimations;*/
};
| [
"kmj2942@naver.com"
] | kmj2942@naver.com |
a10e1970fe11d3ec2183b1f65f8917f83a8e5ff1 | 2a01ba4e1d1402863aee619a13f3be9d6ba7186a | /P-5/voltmeter/voltmeter.ino | 1eae51dfed19b66e9f73ae23eec0b743bd8f2eba | [] | no_license | abhiashi3137/Projects | e4c68d88b86ff9bff5ddd027b398a35bbc42d4e3 | ac3e7e11f2276c46689695dcea43ee2efd5eecf6 | refs/heads/master | 2020-03-26T10:43:56.760120 | 2018-08-15T09:41:58 | 2018-08-15T09:41:58 | 144,812,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | ino | #include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27,16,2);
int input=A0;
float r1=3702000.00;
float r2=18000.00;
void setup()
{
Serial.begin(115200);
lcd.begin();
lcd.backlight();
}
void loop()
{
int nomap=analogRead(input);
float temp=(nomap*4.99)/1023;
float volt=temp*(r1/(r1+r2));
if(volt<0.1){
volt=0.00;
}
lcd.setCursor(0,0);
lcd.print("voltage");
lcd.setCursor(0,1);
lcd.print(volt);
Serial.println(volt);
delay(100);
}
| [
"mdameen8225@gmail.com"
] | mdameen8225@gmail.com |
f2ff293e005faee7226f3759d7a3086031cc1e0d | b119d736776cb586d6bf03cd455832e317e23638 | /Game/Network/Connection.cpp | f1cdd72e3a7bedfbaf7d22367d83c721e986a34f | [] | no_license | visanalexandru/VoxelGame | 2ff1057041897565d62f3a35cdb285ae768d92ff | 15b0575433f962c4cace5dbf8615e86d80bcb12e | refs/heads/master | 2020-05-16T13:27:21.919679 | 2019-10-27T19:41:20 | 2019-10-27T19:41:20 | 183,073,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | cpp | #include "Connection.h"
Connection::Connection(const std::string ip,int port)
{
//ctor
has_connected=false;
initialize_connection(ip,port);
}
void Connection::initialize_connection(const std::string ip,int port)
{
sf::Socket::Status status = socket.connect(ip,port);
if(status==sf::Socket::Done)
{
std::cout<<"CONNECTED"<<std::endl;
has_connected=true;
}
else
{
has_connected=false;
std::cout<<"COULD NOT CONNECT"<<std::endl;
}
}
sf::TcpSocket&Connection::get_socket()
{
return socket;
}
const std::string Connection::receive_data()
{
sf::Packet packet;
sf::Socket::Status status=socket.receive(packet);
std::string received;
if(!has_done(status))
{
std::cout<<"COULD NOT RECEIVE PACKET"<<std::endl;
received="";
has_connected=false;
}
else
packet>>received;
return received;
}
bool Connection::is_conected()
{
return has_connected;
}
bool Connection::has_done(sf::Socket::Status stats)
{
return stats==sf::Socket::Status::Done;
}
void Connection::send_data(std::string to_send)
{
sf::Packet packet;
packet<<to_send;
sf::Socket::Status status=socket.send(packet);
if(!has_done(status))
{
has_connected=false;
std::cout<<"COULD NOT SEND PACKET"<<std::endl;
}
}
Connection::~Connection()
{
//dtor
}
| [
"alexandruvisan44@yahoo.com"
] | alexandruvisan44@yahoo.com |
66c83b60dd4760fe0097db25078e0984ce417bc2 | cc54be093f61690cb854092e112ec8cc99111f33 | /C++_Primer_5th_Edition/VisualStudio2012/10/elimDups.cpp | da2c01170a3ef11563c2435e92bc0cbe455e31b5 | [] | no_license | AllenKashiwa/StudyCpp | 655bd15b6702297dab9efac87132891081aeeada | 39b0aba20e8ae333ec3328ea7e6167c470630e10 | refs/heads/master | 2021-01-02T22:47:46.615460 | 2017-09-11T09:17:31 | 2017-09-11T09:17:31 | 99,392,042 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,290 | cpp | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#include <algorithm>
using std::sort; using std::for_each;
#include <functional>
using std::bind;
using namespace std::placeholders;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <iostream>
using std::cin; using std::cout; using std::endl;
// comparison function to be used to sort by word length
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
bool LT(const string &s1, const string &s2)
{
return s1 < s2;
}
void print(const vector<string> &words)
{
for_each(words.begin(), words.end(),
[](const string &s) { cout << s << " "; });
cout << endl;
}
int main()
{
vector<string> words;
// copy contents of each book into a single vector
string next_word;
while (cin >> next_word) {
// insert next book's contents at end of words
words.push_back(next_word);
}
print(words);
vector<string> cpy = words; // save the original data
// uses string < to compare elements
// sort and print the vector
sort(words.begin(), words.end());
words = cpy; // return to the original data
// uses the LT function to compare elements
// should have the same output as the previous sort
sort(words.begin(), words.end(), LT);
print(words);
words = cpy; // return to the original data
// eliminate duplicates
sort(words.begin(), words.end());
auto it = unique(words.begin(), words.end());
words.erase(it, words.end());
// sort by length using a function
stable_sort(words.begin(), words.end(), isShorter);
print(words);
words = cpy; // return to the original data
// sort the original input on word length, shortest to longest
sort(words.begin(), words.end(), isShorter);
print(words);
// use bind to invert isShorter to sort longest to shortest
sort(words.begin(), words.end(), bind(isShorter, _2, _1));
print(words);
return 0;
}
| [
"358804906@qq.com"
] | 358804906@qq.com |
426d4a9c190bf844dcadb0cd0f3a7fd8e5cab514 | ee519f15d4ae475a1220f160a8064b10a4665748 | /IPlayerDebug.h | f80d32ea88303f9f39b52138c92194d4f32b4c17 | [] | no_license | GronLjus/Project-Celestial | 13b2c08d6cba6138d8b36f6fd28cca7d284e68e7 | ebfc9144097d5de6012df8148cb3a593ddb1cf9a | refs/heads/master | 2021-01-12T11:12:00.818450 | 2017-05-30T18:06:58 | 2017-05-30T18:06:58 | 72,864,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #pragma once
namespace Logic
{
///<summary>This interface allows for debugging of the playerhandler</summary>
class IPlayerDebug
{
public:
///<summary>Toggles if the player can fly freely</summary>
///<param name='enabled'>[in]If the player can fly</param>
virtual void ToggleFreeFlight(bool enabled) = 0;
};
} | [
"tim@greencubestudios.com"
] | tim@greencubestudios.com |
9ed9526e2a287648181f6ef02ec3e7972c2a29ab | b3078498adcef2ec518c69e37874889a1970c260 | /change.h | ba837f9c8676f23bb38a67a5d731ecdcf6b3cb5b | [] | no_license | maylanderclick/text_editor | fafc1f5244c92187d993affc106d50c4898f33c7 | 766a5b303825988ed7a58bc7a4073db3412562ca | refs/heads/master | 2023-08-02T09:57:17.690199 | 2021-09-28T15:24:20 | 2021-09-28T15:24:20 | 411,336,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #ifndef CHANGE_H
#define CHANGE_H
#include <QColor>
#include <QColorDialog>
#include <QTextCursor>
#include <QFont>
#include <QFontDialog>
#include <QFontInfo>
#include <QLineEdit>
#include <QMessageBox>
#include <QDebug>
#include <QTextStream>
#include <QFileDialog>
#include <QFile>
#include <QString>
class Change
{
public:
Change();
QColor TextColor();
QFont ChangeFont();
};
#endif // CHANGE_H
| [
"alena21lokis@gmail.com"
] | alena21lokis@gmail.com |
86c39c3b05fd781a9d0a849993a93332774e2d0a | 0a080dd71ae5a34ced094d747b017c37d8f4ad2a | /src/Client/States/Game/ResourceDownloadState.hpp | 2e80c3b1c7fac30feeb5d3a4c27af3bad164db5a | [
"MIT"
] | permissive | DigitalPulseSoftware/BurgWar | f2489490ef53dc8a04b219f04d120e0bc9f7b2cb | e56d50184adc03462e8b0018f68bf357f1a9e506 | refs/heads/master | 2023-07-19T18:31:12.657056 | 2022-11-23T11:16:05 | 2022-11-23T11:16:05 | 150,015,581 | 56 | 21 | MIT | 2022-07-02T17:08:55 | 2018-09-23T18:56:44 | C++ | UTF-8 | C++ | false | false | 2,061 | hpp | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef BURGWAR_STATES_GAME_ASSETDOWNLOADSTATE_HPP
#define BURGWAR_STATES_GAME_ASSETDOWNLOADSTATE_HPP
#include <ClientLib/DownloadManager.hpp>
#include <CoreLib/Protocol/Packets.hpp>
#include <Client/States/Game/CancelableState.hpp>
#include <NDK/Widgets/LabelWidget.hpp>
#include <tsl/hopscotch_map.h>
#include <memory>
#include <optional>
#include <vector>
namespace bw
{
class ClientSession;
class VirtualDirectory;
class ResourceDownloadState final : public CancelableState
{
public:
ResourceDownloadState(std::shared_ptr<StateData> stateData, std::shared_ptr<ClientSession> clientSession, Packets::AuthSuccess authSuccess, Packets::MatchData matchData, std::shared_ptr<AbstractState> originalState);
~ResourceDownloadState() = default;
private:
struct FileData
{
Nz::UInt64 downloadedSize = 0;
Nz::UInt64 totalSize;
};
using FileMap = tsl::hopscotch_map<std::string /*downloadPath*/, FileData>;
FileData& GetDownloadData(const std::string& downloadUrl, bool* isAsset = nullptr);
void OnCancelled() override;
void RegisterFiles(const std::vector<Packets::MatchData::ClientFile>& files, const std::shared_ptr<VirtualDirectory>& resourceDir, const std::shared_ptr<VirtualDirectory>& targetDir, const std::string& cacheDir, FileMap& fileMap, bool keepInMemory);
bool Update(Ndk::StateMachine& fsm, float elapsedTime) override;
using CancelableState::UpdateStatus;
void UpdateStatus();
FileMap m_assetData;
FileMap m_scriptData;
std::shared_ptr<ClientSession> m_clientSession;
std::shared_ptr<VirtualDirectory> m_targetAssetDirectory;
std::shared_ptr<VirtualDirectory> m_targetScriptDirectory;
std::vector<std::unique_ptr<DownloadManager>> m_downloadManagers;
Packets::AuthSuccess m_authSuccess;
Packets::MatchData m_matchData;
};
}
#include <Client/States/Game/ResourceDownloadState.inl>
#endif
| [
"lynix680@gmail.com"
] | lynix680@gmail.com |
4e5e5e0b4c9e1b348bcb326e9af054cd751bfb0d | 6ce5b9e43eba4c66474edc3d40b505596643c996 | /src/Core/Matlab/matlabtofield.cc | 976fc4a6126ee1b15117bd1662d56692f4bb4048 | [
"MIT"
] | permissive | behollis/SCIRun | 3312ccacd40bd583984f8d5b324ffd1305c2af60 | 59b92359dfab3a9bf300a49f5021850b35380b97 | refs/heads/master | 2021-01-18T08:33:09.905788 | 2016-05-20T21:21:23 | 2016-05-20T21:21:23 | 59,523,881 | 0 | 0 | null | 2016-05-23T22:55:31 | 2016-05-23T22:55:31 | null | UTF-8 | C++ | false | false | 102,874 | cc | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
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.
*/
/*
* FILE: matlabconverter.cc
* AUTH: Jeroen G Stinstra
* DATE: 17 OCT 2004
*/
#include <Core/Matlab/matlabtofield.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Logging/LoggerInterface.h>
#include "matlabconverter.h"
using namespace SCIRun;
using namespace SCIRun::MatlabIO;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Geometry;
bool MatlabToFieldAlgo::execute(FieldHandle& field)
{
FieldInformation fi(meshtype,meshbasis,fieldbasis,fieldtype);
field = CreateField(fi);
if (!field)
{
error("MatlobToField: Could not allocate output field");
return (false);
}
VField* vfield = field->vfield();
VMesh* vmesh = field->vmesh();
if (!vfield || !vmesh)
{
error("MatlobToField: The destination field type does not have a virtual interface");
return (false);
}
if (vmesh->is_pointcloudmesh())
{
if (!(addnodes(vmesh))) return(false);
if (!(addderivatives(vmesh))) return (false);
if (!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_curvemesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addedges(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_trisurfmesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addfaces(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_quadsurfmesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addfaces(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_tetvolmesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addcells(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_prismvolmesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addcells(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_hexvolmesh())
{
if(!(addnodes(vmesh))) return (false);
if(!(addcells(vmesh))) return (false);
if(!(addderivatives(vmesh))) return (false);
if(!(addscalefactors(vmesh))) return (false);
}
if (vmesh->is_scanlinemesh())
{
if (!(mldims.isdense())) return (false);
if (mldims.getnumelements() != 1) return (false);
std::vector<int> dims;
mldims.getnumericarray(dims);
Point PointO(0.0,0.0,0.0);
Point PointP(static_cast<double>(dims[0]),0.0,0.0);
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]),PointO,PointP);
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
addtransform(vmesh);
}
if (vmesh->is_imagemesh())
{
if (!(mldims.isdense())) return (false);
if (mldims.getnumelements() != 2) return (false);
std::vector<int> dims;
mldims.getnumericarray(dims);
Point PointO(0.0,0.0,0.0);
Point PointP(static_cast<double>(dims[0]),static_cast<double>(dims[1]),0.0);
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]),static_cast<unsigned int>(dims[1]),PointO,PointP);
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
addtransform(vmesh);
}
if (vmesh->is_latvolmesh())
{
if (!(mldims.isdense())) return (false);
if (mldims.getnumelements() != 3) return (false);
std::vector<int> dims;
mldims.getnumericarray(dims);
Point PointO(0.0,0.0,0.0);
Point PointP(static_cast<double>(dims[0]),static_cast<double>(dims[1]),static_cast<double>(dims[2]));
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]),static_cast<unsigned int>(dims[1]),static_cast<unsigned int>(dims[2]),PointO,PointP);
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
addtransform(vmesh);
}
if (vmesh->is_structcurvemesh())
{
std::vector<int> dims;
std::vector<unsigned int> mdims;
const int numdim = mlx.getnumdims();
dims = mlx.getdims();
mdims.resize(numdim);
for (int p=0; p < numdim; p++) mdims[p] = static_cast<unsigned int>(dims[p]);
if ((numdim == 2)&&(mlx.getn() == 1))
{
mdims.resize(1);
mdims[0] = mlx.getm();
}
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]));
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
int numnodes = mlx.getnumelements();
std::vector<double> X;
std::vector<double> Y;
std::vector<double> Z;
mlx.getnumericarray(X);
mly.getnumericarray(Y);
mlz.getnumericarray(Z);
for (VMesh::size_type p = 0; p < numnodes; p++)
{
vmesh->set_point(Point(X[p],Y[p],Z[p]),VMesh::Node::index_type(p));
}
}
if (vmesh->is_structquadsurfmesh())
{
std::vector<int> dims;
std::vector<unsigned int> mdims;
int numdim = mlx.getnumdims();
dims = mlx.getdims();
mdims.resize(numdim);
for (int p=0; p < numdim; p++) mdims[p] = static_cast<unsigned int>(dims[p]);
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]),static_cast<unsigned int>(dims[1]));
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
std::vector<double> X;
std::vector<double> Y;
std::vector<double> Z;
mlx.getnumericarray(X);
mly.getnumericarray(Y);
mlz.getnumericarray(Z);
unsigned m = mdims[0]*mdims[1];
for (unsigned int p = 0; p < m; p++)
{
vmesh->set_point(Point(X[p],Y[p],Z[p]),VMesh::Node::index_type(p));
}
}
if (vmesh->is_structhexvolmesh())
{
std::vector<int> dims;
std::vector<unsigned int> mdims;
int numdim = mlx.getnumdims();
dims = mlx.getdims();
mdims.resize(numdim);
for (int p=0; p < numdim; p++) mdims[p] = static_cast<unsigned int>(dims[p]);
std::vector<double> X;
std::vector<double> Y;
std::vector<double> Z;
mlx.getnumericarray(X);
mly.getnumericarray(Y);
mlz.getnumericarray(Z);
field.reset();
MeshHandle handle = CreateMesh(fi,static_cast<unsigned int>(dims[0]),static_cast<unsigned int>(dims[1]),static_cast<unsigned int>(dims[2]));
if (!handle)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
field = CreateField(fi,handle);
if (!field)
{
error("MatlabToField: Could not allocate output field");
return (false);
}
vmesh = field->vmesh();
vfield = field->vfield();
unsigned int m = mdims[0]*mdims[1]*mdims[2];
for (unsigned int p = 0; p < m; p++)
{
vmesh->set_point(Point(X[p],Y[p],Z[p]),VMesh::Node::index_type(p));
}
}
vfield->resize_values();
if (vfield->basis_order() == 0)
{
if (!(addfield(vfield)))
{
error("The conversion of the field data failed");
return (false);
}
}
if (vfield->basis_order() == 1)
{
vfield->resize_fdata();
if (!(addfield(vfield)))
{
error("The conversion of the field data failed");
return (false);
}
}
if (vfield->basis_order() == 2)
{
error("There is no converter available for quadratic field data");
return (false);
}
if (vfield->basis_order() == 3)
{
error("There is no converter available for cubic field data");
return (false);
}
return (true);
}
int MatlabToFieldAlgo::analyze_iscompatible(const matlabarray& mlarray, std::string& infotext, bool postremark)
{
infotext = "";
int ret;
try
{
ret = mlanalyze(mlarray, postremark);
if (0 == ret)
return ret;
}
catch (matlabconverter::error_type& e)
{
std::cerr << "analyze_fieldtype error: " << e.what() << std::endl;
return 0;
}
std::ostringstream oss;
std::string name = mlarray.getname();
oss << name << " ";
if (name.length() < 20) oss << std::string(20-(name.length()),' '); // add some form of spacing
oss << "[" << meshtype << "<" << meshbasis << "> - ";
if (fieldbasistype != "nodata")
{
std::string fieldtypestr = "Scalar";
if (fieldtype == "Vector") fieldtypestr = "Vector";
if (fieldtype == "Tensor") fieldtypestr = "Tensor";
oss << fieldtypestr << "<" << fieldbasis << "> - ";
}
else
{
oss << "NoData - ";
}
if (numnodesvec.size() > 0)
{
for (size_t p = 0; p < numnodesvec.size()-1; p++) oss << numnodesvec[p] << "x";
oss << numnodesvec[numnodesvec.size()-1];
oss << " NODES";
}
else
{
oss << numnodes << " NODES " << numelements << " ELEMENTS";
}
oss << "]";
infotext = oss.str();
return ret;
}
int MatlabToFieldAlgo::analyze_fieldtype(const matlabarray& mlarray, std::string& fielddesc)
{
fielddesc = "";
int ret;
try
{
ret = mlanalyze(mlarray, false);
if (0 == ret)
return ret;
}
catch (matlabconverter::error_type& e)
{
std::cerr << "analyze_fieldtype error: " << e.what() << std::endl;
return 0;
}
if (fieldtype == "") fieldtype = "double";
if (fieldtype == "nodata") fieldtype = "double";
fielddesc = "GenericField<"+meshtype+"<"+meshbasis+"<Point> >,"+
fieldbasis+"<"+fieldtype+">,"+fdatatype+"<"+fieldtype;
// DEAL WITH SOME MORE SCIRUN INCONSISTENCIES
if (fdatatype == "FData2d") fielddesc += "," + meshtype + "<" + meshbasis + "<Point> > ";
if (fdatatype == "FData3d") fielddesc += "," + meshtype + "<" + meshbasis + "<Point> > ";
fielddesc += "> > ";
return 1;
}
matlabarray MatlabToFieldAlgo::findfield(const matlabarray& mlarray,const std::string& fieldnamesIn)
{
matlabarray subarray;
std::string fieldnames(fieldnamesIn);
while (true)
{
size_t loc = fieldnames.find(';');
if (loc > fieldnames.size()) break;
std::string fieldname = fieldnames.substr(0,loc);
fieldnames = fieldnames.substr(loc+1);
int index = mlarray.getfieldnameindexCI(fieldname);
if (index > -1)
{
subarray = mlarray.getfield(0,index);
break;
}
}
return(subarray);
}
void MatlabToFieldAlgo::remarkAndThrow(const std::string& msg, bool postremark) const
{
if (postremark) remark(msg);
throw matlabconverter::error_type(msg);
}
int MatlabToFieldAlgo::mlanalyze(matlabarray mlarray, bool postremark)
{
int ret = 1;
if (mlarray.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into SCIRun Field (matrix is empty)", postremark);
}
if (mlarray.getnumelements() == 0)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into SCIRun Field (matrix is empty)", postremark);
}
// If it is regular matrix translate it to a image or a latvol
// The following section of code rewrites the Matlab matrix into a
// structure and then the normal routine picks up the field and translates it
// properly.
if (mlarray.isdense())
{
int numdims = mlarray.getnumdims();
if ((numdims >0)&&(numdims < 4))
{
matlabarray ml;
matlabarray dimsarray;
std::vector<int> d = mlarray.getdims();
if ((d[0]==1)||(d[1]==1))
{
if (d[0]==1) d[0] = d[1];
int temp = d[0];
d.resize(1);
d[0] = temp;
}
dimsarray.createintvector(d);
ml.createstructarray();
ml.setfield(0,"dims",dimsarray);
ml.setfield(0,"field",mlarray);
ml.setname(mlarray.getname());
mlarray = ml;
}
else if (numdims == 4)
{
matlabarray ml;
matlabarray dimsarray;
matlabarray mltype;
std::vector<int> d = mlarray.getdims();
if ((d[0] == 1)||(d[0] == 3)||(d[0] == 6)||(d[0] == 9))
{
std::vector<int> dm(3);
for (size_t p = 0; p < 3; p++) dm[p] = d[p+1];
dimsarray.createintvector(dm);
if (d[0] == 1) mltype.createstringarray("double");
else if (d[0] == 3) mltype.createstringarray("Vector");
else if ((d[0] == 6) || (d[0] == 9)) mltype.createstringarray("Tensor");
ml.createstructarray();
ml.setfield(0,"dims",dimsarray);
ml.setfield(0,"field",mlarray);
ml.setfield(0,"fieldtype",mltype);
ml.setname(mlarray.getname());
mlarray = ml;
}
else if ((d[3] == 1)||(d[3] == 3)||(d[3] == 6)||(d[3] == 9))
{
std::vector<int> dm(3);
for (size_t p = 0; p < 3; p++) dm[p] = d[p];
dimsarray.createintvector(dm);
if (d[3] == 1) mltype.createstringarray("double");
else if (d[3] == 3) mltype.createstringarray("Vector");
else if ((d[3] == 6) || (d[3] == 9)) mltype.createstringarray("Tensor");
ml.createstructarray();
ml.setfield(0,"dims",dimsarray);
ml.setfield(0,"field",mlarray);
ml.setfield(0,"fieldtype",mltype);
ml.setname(mlarray.getname());
mlarray = ml;
}
}
// If the matrix is dense, we score less as we could translate it into a
// matrix as well. This help for bundle conversions, by which we can
// automatically determine how to translate objects.
ret = 0;
}
// Check whether we have a structured matrix
if (!(mlarray.isstruct()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into SCIRun Field (matrix is not a structured matrix)", postremark);
}
// Get all the matrices that specify the mesh
mlnode = findfield(mlarray,"node;pts;pos;");
mlx = findfield(mlarray,"x;");
mly = findfield(mlarray,"y;");
mlz = findfield(mlarray,"z;");
mledge = findfield(mlarray,"meshedge;edge;line;");
mlface = findfield(mlarray,"meshface;face;quad;fac;tri;");
mlcell = findfield(mlarray,"meshcell;cell;prism;hex;tet;");
mldims = findfield(mlarray,"dims;dim;dimension;");
mltransform = findfield(mlarray,"transform;");
mlmeshderivatives = findfield(mlarray,"meshderivatives;derivatives;");
mlmeshscalefactors = findfield(mlarray,"meshscalefactors;scalefactors;");
mlmeshtype = findfield(mlarray,"elemtype;meshclass;meshtype;");
mlmeshbasis = findfield(mlarray,"meshbasis;basis;");
mlmeshbasisorder = findfield(mlarray,"meshbasisorder;meshat;meshlocation;");
// Get all the matrices that specify the field
mlfield = findfield(mlarray,"field;scalarfield;scalardata;potvals;data;");
mlfieldtype = findfield(mlarray,"fieldtype;datatype;");
// Make it compatible with some old versions
matlabarray mlfieldvector = findfield(mlarray,"vectorfield;vectordata;");
if (mlfieldvector.isdense())
{
mlfield = mlfieldvector; mlfieldtype.createstringarray("vector");
}
matlabarray mlfieldtensor = findfield(mlarray,"tensorfield;tensordata;");
if (mlfieldtensor.isdense())
{
mlfield = mlfieldtensor; mlfieldtype.createstringarray("tensor");
}
mlfieldedge = findfield(mlarray,"fieldedge;edge;line;");
mlfieldderivatives = findfield(mlarray,"fieldderivatives;derivatives;");
mlfieldscalefactors = findfield(mlarray,"fieldscalefactors;scalefactors;");
mlfieldbasis = findfield(mlarray,"fieldbasis;basis;");
mlfieldbasisorder = findfield(mlarray,"fieldbasisorder;basisorder;fieldat;fieldlocation;dataat;");
mlchannels = findfield(mlarray,"channels;");
// Figure out the basis type
// Since we went through several systems over the time
// the next code is all for compatibility.
if (!(mlmeshbasisorder.isempty()))
{ // converter table for the string in the mesh array
if (mlmeshbasisorder.isstring())
{
if ((mlmeshbasisorder.compareCI("node"))||(mlmeshbasisorder.compareCI("pts")))
{
mlmeshbasisorder.createdoublescalar(1.0);
}
else if (mlmeshbasisorder.compareCI("none")||
mlmeshbasisorder.compareCI("nodata"))
{
mlmeshbasisorder.createdoublescalar(-1.0);
}
else if (mlmeshbasisorder.compareCI("egde")||
mlmeshbasisorder.compareCI("line")||mlmeshbasisorder.compareCI("face")||
mlmeshbasisorder.compareCI("fac")||mlmeshbasisorder.compareCI("cell")||
mlmeshbasisorder.compareCI("tet")||mlmeshbasisorder.compareCI("hex")||
mlmeshbasisorder.compareCI("prism"))
{
mlmeshbasisorder.createdoublescalar(0.0);
}
}
}
if (mlmeshbasis.isstring())
{
std::string str = mlmeshbasis.getstring();
for (size_t p = 0; p < str.size(); p++) str[p] = tolower(str[p]);
if (str.find("nodata") != std::string::npos) meshbasistype = "nodata";
else if (str.find("constant") != std::string::npos) meshbasistype = "constant";
else if (str.find("linear") != std::string::npos) meshbasistype = "linear";
else if (str.find("quadratic") != std::string::npos) meshbasistype = "quadratic";
else if (str.find("cubic") != std::string::npos) meshbasistype = "cubic";
}
if ((meshbasistype == "")&&(mlmeshbasisorder.isdense()))
{
std::vector<int> data;
mlmeshbasisorder.getnumericarray(data);
if (data.size() > 0)
{
if (data[0] == -1) meshbasistype = "nodata";
else if (data[0] == 0) meshbasistype = "constant";
else if (data[0] == 1) meshbasistype = "linear";
else if (data[0] == 2) meshbasistype = "quadratic";
}
}
// figure out the basis of the field
if (!(mlfieldbasisorder.isempty()))
{ // converter table for the string in the field array
if (mlfieldbasisorder.isstring())
{
if (mlfieldbasisorder.compareCI("node")||mlfieldbasisorder.compareCI("pts"))
{
mlfieldbasisorder.createdoublescalar(1.0);
}
else if (mlfieldbasisorder.compareCI("none")||
mlfieldbasisorder.compareCI("nodata"))
{
mlfieldbasisorder.createdoublescalar(-1.0);
}
else if (mlfieldbasisorder.compareCI("egde")||
mlfieldbasisorder.compareCI("line")||mlfieldbasisorder.compareCI("face")||
mlfieldbasisorder.compareCI("fac")||mlfieldbasisorder.compareCI("cell")||
mlfieldbasisorder.compareCI("tet")||mlfieldbasisorder.compareCI("hex")||
mlfieldbasisorder.compareCI("prism"))
{
mlfieldbasisorder.createdoublescalar(0.0);
}
}
}
if (mlfieldbasis.isstring())
{
std::string str = mlfieldbasis.getstring();
for (size_t p = 0; p < str.size(); p++) str[p] = tolower(str[p]);
if (str.find("nodata") != std::string::npos) fieldbasistype = "nodata";
else if (str.find("constant") != std::string::npos) fieldbasistype = "constant";
else if (str.find("linear") != std::string::npos) fieldbasistype = "linear";
else if (str.find("quadratic") != std::string::npos) fieldbasistype = "quadratic";
else if (str.find("cubic") != std::string::npos) fieldbasistype = "cubic";
}
if ((fieldbasistype == "")&&(mlfieldbasisorder.isdense()))
{
std::vector<int> data;
mlfieldbasisorder.getnumericarray(data);
if (data.size() > 0)
{
if (data[0] == -1) fieldbasistype = "nodata";
else if (data[0] == 0) fieldbasistype = "constant";
else if (data[0] == 1) fieldbasistype = "linear";
else if (data[0] == 2) fieldbasistype = "quadratic";
}
}
// Figure out the fieldtype
fieldtype = "";
if (mlfield.isdense())
{
if (mlfieldtype.isstring())
{
if (mlfieldtype.compareCI("nodata")) fieldtype = "nodata";
else if (mlfieldtype.compareCI("vector")) fieldtype = "Vector";
else if (mlfieldtype.compareCI("tensor")) fieldtype = "Tensor";
else if (mlfieldtype.compareCI("double")) fieldtype = "double";
else if (mlfieldtype.compareCI("float")) fieldtype = "float";
else if (mlfieldtype.compareCI("long long")) fieldtype = "long long";
else if (mlfieldtype.compareCI("unsigned long long")) fieldtype = "unsigned long long";
else if (mlfieldtype.compareCI("long")) fieldtype = "long";
else if (mlfieldtype.compareCI("unsigned long")) fieldtype = "unsigned long";
else if (mlfieldtype.compareCI("int")) fieldtype = "int";
else if (mlfieldtype.compareCI("unsigned int")) fieldtype = "unsigned int";
else if (mlfieldtype.compareCI("short")) fieldtype = "short";
else if (mlfieldtype.compareCI("unsigned short")) fieldtype = "unsigned short";
else if (mlfieldtype.compareCI("char")) fieldtype = "char";
else if (mlfieldtype.compareCI("unsigned char")) fieldtype = "unsigned char";
}
}
if ((fieldtype == "nodata")||(mlfield.isempty()))
{
fieldbasis = "NoDataBasis";
fieldbasistype = "nodata";
fieldtype = "double";
}
// if no meshbasistype is supplied we need to figure it out on the fly
// Now figure out the mesh type and check we have everything for that meshtype
meshtype = "";
if (mlmeshtype.isstring())
{
std::string str = mlmeshtype.getstring();
for (size_t p = 0; p < str.size(); p++) str[p] = tolower(str[p]);
if (str.find("pointcloud") != std::string::npos) meshtype = "PointCloudMesh";
else if (str.find("scanline") != std::string::npos) meshtype = "ScanlineMesh";
else if (str.find("image") != std::string::npos) meshtype = "ImageMesh";
else if (str.find("latvol") != std::string::npos) meshtype = "LatVolMesh";
else if (str.find("structcurve") != std::string::npos) meshtype = "StructCurveMesh";
else if (str.find("structquadsurf") != std::string::npos) meshtype = "StructQuadSurfMesh";
else if (str.find("structhexvol") != std::string::npos) meshtype = "StructHexVolMesh";
else if (str.find("curve") != std::string::npos) meshtype = "CurveMesh";
else if (str.find("trisurf") != std::string::npos) meshtype = "TriSurfMesh";
else if (str.find("quadsurf") != std::string::npos) meshtype = "QuadSurfMesh";
else if (str.find("tetvol") != std::string::npos) meshtype = "TetVolMesh";
else if (str.find("prismvol") != std::string::npos) meshtype = "PrismVolMesh";
else if (str.find("hexvol") != std::string::npos) meshtype = "HexVolMesh";
}
fdatatype = "vector";
numnodes = 0;
numelements = 0;
numnodesvec.clear();
numelementsvec.clear();
if (mltransform.isdense())
{
if (mltransform.getnumdims() != 2)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (transformation matrix is not 2D)", postremark);
}
if ((mltransform.getn() != 4)&&(mltransform.getm() != 4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (transformation matrix is not 4x4)", postremark);
}
}
if (mlx.isdense()||mly.isdense()||mly.isdense())
{
if (mlx.isempty()||mly.isempty()||mlz.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (does not have a complete set of x, y, or z coordinates", postremark);
}
}
// FIGURE OUT THE REGULAR MESH STUFF
// CHECK WHETHER IT IS ONE, AND IF SO CHECK ALL THE DATA
if (((mlnode.isempty()&&(mlx.isempty()))||
(mltransform.isdense())||(meshtype == "ScanlineMesh")||
(meshtype == "ImageMesh")||(meshtype == "LatVolMesh"))&&(mldims.isempty()))
{
if (mlfield.isdense())
{
std::vector<int> dims = mlfield.getdims();
if ((fieldtype == "")&&(dims.size() > 3))
{
if (dims[0] == 3) fieldtype = "Vector";
if ((dims[0] == 6)||(dims[0] == 9)) fieldtype = "Tensor";
}
if ((fieldtype == "Vector")||(fieldtype == "Tensor"))
{
if (fieldbasistype == "quadratic")
{
if (dims.size() > 2) mldims.createintvector(static_cast<int>((dims.size()-2)),&(dims[1]));
}
else
{
if (dims.size() > 1) mldims.createintvector(static_cast<int>((dims.size()-1)),&(dims[1]));
}
}
else
{
if (fieldbasistype == "quadratic")
{
if (dims.size() > 1) mldims.createintvector(static_cast<int>((dims.size()-1)),&(dims[0]));
}
else
{
mldims.createintvector(dims);
}
}
}
if (fieldbasistype == "constant")
{
std::vector<int> dims = mlfield.getdims();
// dimensions need to be one bigger
for (int p = 0; p<static_cast<int>(dims.size()); p++) dims[p] = dims[p]+1;
mldims.createintvector(dims);
}
}
// CHECK WHETHER WE HAVE A REGULAR FIELD
if ((mldims.isempty())&&(mlx.isempty())&&(mlnode.isempty()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated because no node, x, or dims field was found", postremark);
}
// WE HAVE POSSIBLY A FIELD
// NOW CHECK EVERY COMBINATION
// HANDLE REGULAR MESHES
numfield = 0;
datasize = 1;
if (mldims.isdense())
{
size_t size = static_cast<size_t>(mldims.getnumelements());
if (!((size > 0)&&(size < 4)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of dimensions (.dims field) needs to 1, 2, or 3)", postremark);
}
if (meshtype != "")
{ // explicitly stated type: (check whether type confirms the guessed type, otherwise someone supplied us with improper data)
if ((meshtype == "ScanlineMesh")&&(size!=1))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (scanline needs only one dimension)", postremark);
}
else if ((meshtype == "ImageMesh") && (size != 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (an image needs two dimensions)", postremark);
}
else if ((meshtype == "LatVolMesh") && (size != 3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (a latvolmesh needs three dimensions)", postremark);
}
}
else
{
if (size == 1) meshtype = "ScanlineMesh";
else if (size == 2) meshtype = "ImageMesh";
else if (size == 3) meshtype = "LatVolMesh";
}
// We always make this into a linear one
if (meshbasistype == "") meshbasistype = "linear";
if (meshbasistype != "linear")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (regular meshes cannot have higher order basis)", postremark);
}
if (meshtype == "ScanlineMesh") { meshbasis = "CrvLinearLgn"; fdatatype = "vector"; }
else if (meshtype == "ImageMesh") { meshbasis = "QuadBilinearLgn"; fdatatype = "FData2d"; }
else if (meshtype == "LatVolMesh") { meshbasis = "HexTrilinearLgn"; fdatatype = "FData3d"; }
// compute number of elements and number of nodes
mldims.getnumericarray(numnodesvec);
numelementsvec = numnodesvec;
// Number of elements is one less than the dimension in a certain direction
for (size_t p = 0; p < numnodesvec.size(); p++)
{
numelementsvec[p]--;
}
// try to figure out the field basis
if (fieldbasistype == "")
{
// In case no data is there
if (mlfield.isempty())
{
fieldbasistype = "nodata";
fieldtype = "";
}
else
{
if (fieldtype == "")
{
fieldtype = "double";
auto type = mlfield.gettype();
if (type == miINT8) fieldtype = "char";
else if (type == miUINT8) fieldtype = "unsigned char";
else if (type == miINT16) fieldtype = "short";
else if (type == miUINT16) fieldtype = "unsigned short";
else if (type == miINT32) fieldtype = "int";
else if (type == miUINT32) fieldtype = "unsigned int";
else if (type == miSINGLE) fieldtype = "float";
}
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
}
else if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
}
if ((size == 1)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])) fieldbasistype = "linear";
else if ((size == 2) && (size == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1])) fieldbasistype = "linear";
else if ((size == 3) && (size == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1]) && (fdims[2] == numnodesvec[2])) fieldbasistype = "linear";
if ((size == 1)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == 2)) fieldbasistype = "quadratic";
else if ((size == 2) && (size + 1 == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1]) && (fdims[2] == 3)) fieldbasistype = "quadratic";
else if ((size == 3) && (size + 1 == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1]) && (fdims[2] == numnodesvec[2]) && (fdims[3] == 4)) fieldbasistype = "quadratic";
if ((size == 1)&&(size == fdims.size())&&(fdims[0] == numelementsvec[0])) fieldbasistype = "constant";
else if ((size == 2) && (size == fdims.size()) && (fdims[0] == numelementsvec[0]) && (fdims[1] == numelementsvec[1])) fieldbasistype = "constant";
else if ((size == 3) && (size == fdims.size()) && (fdims[0] == numelementsvec[0]) && (fdims[1] == numelementsvec[1]) && (fdims[2] == numelementsvec[2])) fieldbasistype = "constant";
if ((mlfieldderivatives.isdense())&&(fieldbasis == "linear")) fieldbasistype = "cubic";
}
}
//by now we should know what kind of basis we would like
if (fieldbasistype == "")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions field matrix does not match mesh)", postremark);
}
if (fieldbasistype == "nodata") fieldbasis = "NoDataBasis";
else if (fieldbasistype == "constant") fieldbasis = "ConstantBasis";
else if (fieldbasistype == "linear")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
else if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if ((!((size == 1) && (size == fdims.size()) && (fdims[0] == numnodesvec[0]))) &&
(!((size == 2) && (size == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1]))) &&
(!((meshtype == "LatVolMesh") && (size == 3) && (2 == fdims.size()) && (fdims[0] * fdims[1] == numnodesvec[0] * numnodesvec[1] * numnodesvec[2]))) &&
(!((size == 3) && (size == fdims.size()) && (fdims[0] == numnodesvec[0]) && (fdims[1] == numnodesvec[1]) && (fdims[2] == numnodesvec[2]))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (dimensions of field do not match dimensions of mesh", postremark);
}
if (meshtype == "ScanlineMesh") { fieldbasis = "CrvLinearLgn";}
else if (meshtype == "ImageMesh") { fieldbasis = "QuadBilinearLgn"; }
else if (meshtype == "LatVolMesh") { fieldbasis = "HexTrilinearLgn"; }
}
else if (fieldbasistype == "quadratic")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
else if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if ((!((size == 1)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == 2))) &&
(!((size == 2)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == 3))) &&
(!((size == 3)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == numnodesvec[2])&&(fdims[3] == 4))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (dimensions of field do not match dimensions of mesh", postremark);
}
if (meshtype == "ScanlineMesh") { fieldbasis = "CrvQuadraticLgn";}
else if (meshtype == "ImageMesh") { fieldbasis = "QuadBiquadraticLgn"; }
else if (meshtype == "LatVolMesh") { fieldbasis = "HexTriquadraticLgn"; }
}
else if (fieldbasistype == "cubic")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
else if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if (meshtype == "ScanlineMesh") { fieldbasis = "CrvCubicHmt";}
else if (meshtype == "ImageMesh") { fieldbasis = "QuadBicubicLgn"; }
else if (meshtype == "LatVolMesh") { fieldbasis = "HexTricubicLgn"; }
if (mlfieldderivatives.isdense())
{
std::vector<int> derivativesdims = mlfieldderivatives.getdims();
std::vector<int> fielddims = mlfieldderivatives.getdims();
if (meshtype == "ScanlineMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 1)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0]))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
else if (meshtype == "ImageMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 2)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0])||(derivativesdims[3] != fielddims[1]))
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
else if (meshtype == "LatVolMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 7)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0])||(derivativesdims[3] != fielddims[1])||(derivativesdims[4] != fielddims[2]))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
}
else
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
return(1+ret);
}
///////////////////////////////////////////////////
// DEAL WITH STRUCTURED MESHES
if ((mlx.isdense())&&(mly.isdense())&(mlz.isdense()))
{
// TEST: The dimensions of the x, y, and z ,atrix should be equal
size_t size = static_cast<size_t>(mlx.getnumdims());
if (mly.getnumdims() != static_cast<int>(size))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions of the x and y matrix do not match)", postremark);
}
if (mlz.getnumdims() != static_cast<int>(size))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions of the x and z matrix do not match)", postremark);
}
std::vector<int> dimsx = mlx.getdims();
std::vector<int> dimsy = mly.getdims();
std::vector<int> dimsz = mlz.getdims();
// Check dimension by dimension for any problems
for (size_t p=0 ; p < size ; p++)
{
if(dimsx[p] != dimsy[p])
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions of the x and y matrix do not match)", postremark);
}
if(dimsx[p] != dimsz[p])
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions of the x and z matrix do not match)", postremark);
}
}
// Minimum number of dimensions is in Matlab is 2 and hence detect any empty dimension
if (size == 2)
{
// This case will filter out the scanline objects
// Currently SCIRun will fail/crash with an image where one of the
// dimensions is one, hence prevent some troubles
if ((dimsx[0] == 1)||(dimsx[1] == 1)) size = 1;
}
// Disregard data at odd locations. The translation function for those is not straight forward
// Hence disregard those data locations.
if ((fieldtype == "Vector")||(fieldtype == "Tensor")) size--;
if (meshtype != "")
{ // explicitly stated type (check whether type confirms the guessed type, otherwise someone supplied us with improper data)
if ((meshtype == "StructCurveMesh")&&(size!=1))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (invalid number of dimensions for x, y, and z matrix)", postremark);
}
if ((meshtype == "StructQuadSurfMesh")&&(size!=2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (invalid number of dimensions for x, y, and z matrix)", postremark);
}
if ((meshtype == "StructHexVolMesh")&&(size!=3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (invalid number of dimensions for x, y, and z matrix)", postremark);
}
}
if (size == 1) { meshtype = "StructCurveMesh"; }
if (size == 2) { meshtype = "StructQuadSurfMesh"; }
if (size == 3) { meshtype = "StructHexVolMesh"; }
std::vector<int> dims = mlx.getdims();
if ((fieldtype == "Vector")||(fieldtype == "Tensor"))
{
std::vector<int> temp(dims.size()-1);
for (size_t p=0; p < dims.size()-1; p++) temp[p] = dims[p];
dims = temp;
}
numnodesvec = dims;
numelementsvec = dims;
for (size_t p = 0; p < numnodesvec.size(); p++) numelementsvec[p]--;
if (meshtype == "")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (unknown mesh type)", postremark);
}
// We always make this into a linear one
if (meshbasistype == "") meshbasistype = "linear";
if (meshbasistype != "linear")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (geometrical higher order basis for structured meshes is not yet supported)", postremark);
}
if (meshtype == "StructCurveMesh") { meshbasis = "CrvLinearLgn"; fdatatype = "vector"; }
if (meshtype == "StructQuadSurfMesh") { meshbasis = "QuadBilinearLgn"; fdatatype = "FData2d"; }
if (meshtype == "StructHexVolMesh") { meshbasis = "HexTrilinearLgn"; fdatatype = "FData3d"; }
// We should have a meshbasis and a meshtype by now
// try to figure out the field basis
if (fieldbasistype == "")
{
// In case no data is there
if (mlfield.isempty())
{
fieldbasistype = "nodata";
fieldtype = "";
}
else
{
if (fieldtype == "") fieldtype = "double";
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
}
if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
}
if ((size == 1)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])) fieldbasistype = "linear";
if ((size == 2)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])) fieldbasistype = "linear";
if ((size == 3)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == numnodesvec[2])) fieldbasistype = "linear";
if ((size == 1)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == 2)) fieldbasistype = "quadratic";
if ((size == 2)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == 3)) fieldbasistype = "quadratic";
if ((size == 3)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == numnodesvec[2])&&(fdims[3] == 4)) fieldbasistype = "quadratic";
if ((size == 1)&&(size == fdims.size())&&(fdims[0] == numelementsvec[0])) fieldbasistype = "constant";
if ((size == 2)&&(size == fdims.size())&&(fdims[0] == numelementsvec[0])&&(fdims[1] == numelementsvec[1])) fieldbasistype = "constant";
if ((size == 3)&&(size == fdims.size())&&(fdims[0] == numelementsvec[0])&&(fdims[1] == numelementsvec[1])&&(fdims[2] == numelementsvec[2])) fieldbasistype = "constant";
if ((mlfieldderivatives.isdense())&&(fieldbasistype == "linear")) fieldbasistype = "cubic";
}
}
//by now we should know what kind of basis we would like
if (fieldbasistype == "")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (the dimensions field matrix do not match mesh)", postremark);
}
if (fieldbasistype == "nodata") fieldbasis = "NoDataBasis";
if (fieldbasistype == "constant") fieldbasis = "ConstantBasis";
if (fieldbasistype == "linear")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if ((!((size == 1)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0]))) &&
(!((size == 2)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1]))) &&
(!((size == 3)&&(size == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == numnodesvec[2]))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (dimensions of field do not match dimensions of mesh", postremark);
}
if (meshtype == "StructCurveMesh") { fieldbasis = "CrvLinearLgn";}
else if (meshtype == "StructQuadSurfMesh") { fieldbasis = "QuadBilinearLgn"; }
else if (meshtype == "StructHexVolMesh") { fieldbasis = "HexTrilinearLgn"; }
}
else if (fieldbasistype == "quadratic")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if ((!((size == 1)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == 2))) &&
(!((size == 2)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == 3))) &&
(!((size == 3)&&(size+1 == fdims.size())&&(fdims[0] == numnodesvec[0])&&(fdims[1] == numnodesvec[1])&&(fdims[2] == numnodesvec[2])&&(fdims[3] == 4))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (dimensions of field do not match dimensions of mesh", postremark);
}
if (meshtype == "StructCurveMesh") { fieldbasis = "CrvQuadraticLgn";}
if (meshtype == "StructQuadSurfMesh") { fieldbasis = "QuadBiquadraticLgn"; }
if (meshtype == "StructHexVolMesh") { fieldbasis = "HexTriquadraticLgn"; }
}
else if (fieldbasistype == "cubic")
{
std::vector<int> fdims = mlfield.getdims();
if (fieldtype == "Vector")
{
if (fdims[0] != 3)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 3", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if (fieldtype == "Tensor")
{
if ((fdims[0] != 6)&&(fdims[0] != 9))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (first dimension of field needs to be 6, or 9)", postremark);
}
std::vector<int> temp(fdims.size()-1);
for (size_t p = 0; p < temp.size(); p++) temp[p] = fdims[p+1];
fdims = temp;
datasize = fdims[0];
}
if (meshtype == "StructCurveMesh") { fieldbasis = "CrvCubicHmt";}
if (meshtype == "StructQuadSurfMesh") { fieldbasis = "QuadBicubicLgn"; }
if (meshtype == "StructHexVolMesh") { fieldbasis = "HexTricubicLgn"; }
if (mlfieldderivatives.isdense())
{
std::vector<int> derivativesdims = mlfieldderivatives.getdims();
std::vector<int> fielddims = mlfieldderivatives.getdims();
if (meshtype == "StructCurveMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 1)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0]))
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
if (meshtype == "StructQuadSurfMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 2)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0])||(derivativesdims[3] != fielddims[1]))
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
if (meshtype == "StructHexVolMesh")
{
if (derivativesdims.size() != size+2)
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix should have two more dimensions then the field matrix", postremark);
}
if ((derivativesdims[0] != 7)||(derivativesdims[1] != datasize)||(derivativesdims[2] != fielddims[0])||(derivativesdims[3] != fielddims[1])||(derivativesdims[4] != fielddims[2]))
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
}
else
{
remarkAndThrow("Matrix '"+mlarray.getname()+"' cannot be translated into a SCIRun Field, the derivative matrix and the field matrix do not match", postremark);
}
}
return(1+ret);
}
///////////////////////////////////////////////////////////////////////////////
// CHECK FOR UNSTRUCTURED MESHES:
// THIS ONE IS NOW KNOWN
fdatatype = "vector";
if (mlnode.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no node matrix for unstructured mesh, create a .node field)", postremark);
// a node matrix is always required
}
if (mlnode.getnumdims() > 2)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (invalid number of dimensions for node matrix)", postremark);
// Currently N dimensional arrays are not supported here
}
// Check the dimensions of the NODE array supplied only [3xM] or [Mx3] are supported
int m,n;
m = mlnode.getm();
n = mlnode.getn();
if ((n==0)||(m==0))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (node matrix is empty)", postremark);
//empty matrix, no nodes => no mesh => no field......
}
if ((n != 3)&&(m != 3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of node matrix needs to be 3)", postremark);
// SCIRun is ONLY 3D data, no 2D, or 1D
}
numnodes = n; if ((m!=3)&&(n==3)) { numnodes = m; mlnode.transpose(); }
numelements = 0;
//////////////
// IT IS GOOD TO HAVE THE NUMBER OF ELEMENTS IN THE FIELD
numfield = 0;
datasize = 1;
if (mlfield.isdense())
{
if (fieldtype == "Vector")
{
n = mlfield.getn(); m = mlfield.getm();
if ((m != 3)&&(n != 3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (field matrix with vectors does not have a dimension of 3)", postremark);
}
numfield = n;
if (m!=3) { numfield = m; mlfield.transpose(); }
datasize = 3;
}
else if (fieldtype == "Tensor")
{
n = mlfield.getn(); m = mlfield.getm();
if (((m != 6)&&(m !=9))&&((n != 6)&&(n != 9)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (field matrix with tensors does not have a dimension of 6 or 9)", postremark);
}
numfield = n;
datasize = m;
if ((m!=6)&&(m!=9)) { numfield = m; mlfield.transpose(); datasize = n; }
}
else if (fieldtype == "")
{
n = mlfield.getn(); m = mlfield.getm();
if (((m != 1)&&(n != 1))&&((m != 3)&&(n != 3))&&((m != 6)&&(n != 6))&&((m != 9)&&(n != 9)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (field matrix does not have a dimension of 1, 3, 6, or 9)", postremark);
}
numfield = n;
if (m == 1) fieldtype = "double";
if (m == 3) fieldtype = "Vector";
if ((m == 6)||(m == 9)) fieldtype = "Tensor";
datasize = m;
if ((m!=1)&&(m!=3)&&(m!=6)&&(m!=9))
{
numfield = m;
if (n == 1) fieldtype = "double";
if (n == 3) fieldtype = "Vector";
if ((n == 6)||(n == 9)) fieldtype = "Tensor";
datasize = n;
mlfield.transpose();
}
}
else
{
n = mlfield.getn(); m = mlfield.getm();
if (((m != 1)&&(n != 1)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (field matrix does not have a dimension of 1)", postremark);
}
numfield = n;
if (m!=1) { numfield = m; mlfield.transpose(); }
datasize = 1;
}
}
// FIRST COUPLE OF CHECKS ON FIELDDATA
if (fieldbasistype == "nodata")
{
if (numfield != 0)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (nodata field basis should not have field data)", postremark);
}
fieldbasis = "NoDataBasis";
}
else if ((fieldbasistype == "linear")||(fieldbasistype == "cubic"))
{
if (meshbasistype != "quadratic")
{
if (numfield != numnodes)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of field entries does not match number of nodes)", postremark);
}
}
}
if (fieldbasistype == "")
{
if (numfield == 0)
{
fieldbasis = "NoDataBasis";
fieldbasistype = "nodata";
}
}
if (meshbasistype == "nodata")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (mesh needs to have points and cannot be nodata)", postremark);
}
//// POINTCLOUD CODE ////////////
if ((mledge.isempty())&&(mlface.isempty())&&(mlcell.isempty()))
{
// This has no connectivity data => it must be a pointcloud ;)
// Supported mesh/field types here:
// PointCloudField
if (meshtype == "") meshtype = "PointCloudMesh";
if (meshtype != "PointCloudMesh")
{
// explicitly stated type (check whether type confirms the guessed type, otherwise someone supplied us with improper data)
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (data has to be of the pointcloud class)", postremark);
}
if (meshbasistype == "")
{
meshbasistype = "constant";
}
// Now pointcloud does store data at nodes as constant
if (meshbasistype != "constant")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (element is a point, hence no linear/higher order interpolation is supported)", postremark);
}
meshbasis = "ConstantBasis";
if (fieldbasistype == "")
{
if (numfield == numnodes)
{
fieldbasistype = "constant";
}
else if (numfield == 0)
{
fieldbasistype = "nodata";
}
}
if ((fieldbasistype != "nodata")&&(fieldbasistype != "constant"))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (element is a point, hence no linear/higher order interpolation is supported)", postremark);
}
numelements = numnodes;
if (fieldbasistype == "nodata") fieldbasis = "NoDataBasis";
if (fieldbasistype == "constant")
{
fieldbasis = "ConstantBasis";
if (numfield != numelements)
{
if (datasize == numelements)
{
if (numfield == 1) { fieldtype = "double"; numfield = datasize; datasize = 1; mlfield.transpose(); }
else if (numfield == 3) { fieldtype = "Vector"; numfield = datasize; datasize = 3; mlfield.transpose(); }
else if (numfield == 6) { fieldtype = "Tensor"; numfield = datasize; datasize = 6; mlfield.transpose(); }
else if (numfield == 9) { fieldtype = "Tensor"; numfield = datasize; datasize = 9; mlfield.transpose(); }
}
if (numfield != numelements)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements does not match number of field entries)", postremark);
}
}
}
if ((mlmeshderivatives.isdense())||(mlfieldderivatives.isdense())||
(mlfieldedge.isdense()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (element is a point, hence no linear/higher order interpolation is supported)", postremark);
}
return(1+ret);
}
if (meshbasistype == "constant")
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (spatial distributed elements cannot have a constant mesh interpolation)", postremark);
}
///// CURVEMESH ////////////////////////////////////
if (mledge.isdense())
{
int n,m;
// Edge data is provide hence it must be some line element!
// Supported mesh/field types here:
// CurveField
if (meshtype == "") meshtype = "CurveMesh";
if (meshtype != "CurveMesh")
{ // explicitly stated type
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (edge connectivity does not macth meshtype)", postremark);
}
// established meshtype //
if ((mlface.isdense())||(mlcell.isdense()))
{ // a matrix with multiple connectivities is not yet allowed
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (multiple connectivity matrices defined)", postremark);
}
// Connectivity should be 2D
if ((mledge.getnumdims() > 2)||(mlfieldedge.getnumdims() > 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (edge connectivity matrix should be 2D)", postremark);
}
// Check whether the connectivity data makes any sense
// from here on meshtype can only be linear/cubic/quadratic
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mledge.getm(); n = mledge.getn();
if ((n!=2)&&(m!=2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of edge needs to be of size 2)", postremark);
}
numelements = n;
if ((m!=2)&&(n==2)) { numelements = m; mledge.transpose(); }
if (meshbasistype == "linear") meshbasis = "CrvLinearLgn"; else meshbasis = "CrvCubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mledge.getm(); n = mledge.getn();
if ((n!=3)&&(m!=3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of edge needs to be of size 3)", postremark);
}
numelements = n;
if ((m!=3)&&(n==3)) { numelements = m; mledge.transpose(); }
meshbasistype = "CrvQuadraticLgn";
}
else
{
m = mledge.getm(); n = mledge.getn();
if (((n!=2)&&(m!=2))&&((n!=3)&&(m!=3)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of edge needs to be of size 2 or 3)", postremark);
}
numelements = n;
if (((m!=2)&&(m!=3))&&((n==2)||(n==3))) { numelements = m; m = n; mledge.transpose(); }
if (m == 2) { meshbasistype = "linear"; meshbasis = "CrvLinearLgn"; }
if (m == 3) { meshbasistype = "quadratic"; meshbasis = "CrvQuadraticLgn"; }
}
// established meshbasis
if ((mlmeshderivatives.isempty())&&(meshbasistype == "cubic"))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no meshderatives matrix was found)", postremark);
}
if (meshbasistype == "cubic")
{
std::vector<int> ddims = mlmeshderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
if ((ddims[0] != 1)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
// established and checked mesh type ///
// CHECK THE FIELD PROPERTIES
if (fieldbasistype == "")
{
if ((numfield == numelements)&&(numfield != numnodes))
{
fieldbasistype = "constant";
}
else if (numfield == numnodes)
{
if (meshbasistype == "quadratic")
{
fieldbasistype = "quadratic";
}
else if ((meshbasistype == "cubic")&&(mlfieldderivatives.isdense()))
{
fieldbasistype = "cubic";
}
else
{
fieldbasistype = "linear";
}
}
else
{
if ((meshbasistype == "quadratic")&&(mlfieldedge.isdense()))
{
fieldbasistype = "linear";
}
else
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements in field does not match mesh)", postremark);
}
}
}
if (fieldbasistype == "constant")
{
if (numfield != numelements)
{
if (datasize == numelements)
{
if (numfield == 1) { fieldtype = "double"; numfield = datasize; datasize = 1; mlfield.transpose(); }
else if (numfield == 3) { fieldtype = "Vector"; numfield = datasize; datasize = 3; mlfield.transpose(); }
else if (numfield == 6) { fieldtype = "Tensor"; numfield = datasize; datasize = 6; mlfield.transpose(); }
else if (numfield == 9) { fieldtype = "Tensor"; numfield = datasize; datasize = 9; mlfield.transpose(); }
}
if (numfield != numelements)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements does not match number of field entries)", postremark);
}
}
fieldbasis = "ConstantBasis";
}
if ((fieldbasistype == "linear")||(fieldbasistype == "cubic"))
{
if ((meshbasistype == "quadratic")&&(mlfieldedge.isempty()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldedge connectivity matrix)", postremark);
}
if (fieldbasistype == "linear")
{
fieldbasis = "CrvLinearLgn";
}
else
{
if (mlfieldderivatives.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldderivatives matrix)", postremark);
}
fieldbasis = "CrvCubicHmt";
}
}
if (fieldbasis == "quadratic")
{
if (((meshbasistype == "linear")||(meshbasistype == "cubic"))&&(mlfieldedge.isempty()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldedge connectivity matrix)", postremark);
}
fieldbasis = "CrvQuadraticLgn";
}
// established fieldbasis //
if (mlfieldedge.isdense())
{
m = mlfieldedge.getm(); n = mlfieldedge.getn();
if (fieldbasistype == "quadratic")
{
if (!(((m==3)&&(n==numelements))||((m==numelements)&&(n==3))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of fieldedge needs to be of size 2 or 3)", postremark);
}
if (m!=3) mlfieldedge.transpose();
}
else
{
if (!(((m==2)&&(n==numelements))||((m==numelements)&&(n==2))))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of fieldedge needs to be of size 2 or 3)", postremark);
}
if (m!=2) mlfieldedge.transpose();
}
}
if (mlfieldderivatives.isdense())
{
std::vector<int> ddims = mlfieldderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
if ((ddims[0] != 1)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
return(1+ret);
}
if (mlface.isdense())
{
int n,m;
// Edge data is provide hence it must be some line element!
// Supported mesh/field types here:
// CurveField
if (meshtype == "")
{
m = mlface.getm();
n = mlface.getn();
if ((m==3)||(m==4)||(m==6)||(m==8)) n = m;
if ((n==3)||(n==4)||(n==6)||(n==8))
{
if ((n==3)||(n==6)) meshtype = "TriSurfMesh";
else meshtype = "QuadSurfMesh";
}
}
if ((meshtype != "TriSurfMesh")&&(meshtype != "QuadSurfMesh"))
{ // explicitly stated type
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (face connectivity does not match meshtype)", postremark);
}
// established meshtype //
if ((mledge.isdense())||(mlcell.isdense())||
(mlfieldedge.isdense()))
{ // a matrix with multiple connectivities is not yet allowed
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (multiple connectivity matrices defined)", postremark);
}
// Connectivity should be 2D
if ((mlface.getnumdims() > 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (face connectivity matrix should be 2D)", postremark);
}
// Check whether the connectivity data makes any sense
// from here on meshtype can only be linear/cubic/quadratic
if (meshtype == "TriSurfMesh")
{
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mlface.getm(); n = mlface.getn();
if ((n!=3)&&(m!=3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 3)", postremark);
}
numelements = n;
if ((m!=3)&&(n==3)) { numelements = m; mlface.transpose(); }
if (meshbasistype == "linear") meshbasis = "TriLinearLgn"; else meshbasis = "TriCubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mlface.getm(); n = mlface.getn();
if ((n!=6)&&(m!=6))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 6)", postremark);
}
numelements = n;
if ((m!=6)&&(n==6)) { numelements = m; mlface.transpose(); }
meshbasistype = "TriQuadraticLgn";
}
else
{
m = mlface.getm(); n = mlface.getn();
if (((n!=3)&&(m!=3))&&((n!=6)&&(m!=6)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 3 or 6)", postremark);
}
numelements = n;
if (((m!=3)&&(m!=6))&&((n==3)||(n==6))) { numelements = m; m = n; mlface.transpose(); }
if (m == 3) { meshbasistype = "linear"; meshbasis = "TriLinearLgn"; }
if (m == 6) { meshbasistype = "quadratic"; meshbasis = "TriQuadraticLgn"; }
}
}
else
{
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mlface.getm(); n = mlface.getn();
if ((n!=4)&&(m!=4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 4)", postremark);
}
numelements = n;
if ((m!=4)&&(n==4)) { numelements = m; mlface.transpose(); }
if (meshbasistype == "linear") meshbasis = "QuadBilinearLgn"; else meshbasis = "QuadBicubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mlface.getm(); n = mlface.getn();
if ((n!=8)&&(m!=8))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 8)", postremark);
}
numelements = n;
if ((m!=8)&&(n==8)) { numelements = m; mlface.transpose(); }
meshbasistype = "QuadBiquadraticLgn";
}
else
{
m = mlface.getm(); n = mlface.getn();
if (((n!=4)&&(m!=4))&&((n!=8)&&(m!=8)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of face needs to be of size 4 or 8)", postremark);
}
numelements = n;
if (((m!=4)&&(m!=8))&&((n==4)||(n==8))) { numelements = m; m = n; mlface.transpose(); }
if (m == 4) { meshbasistype = "linear"; meshbasis = "QuadBilinearLgn"; }
if (m == 8) { meshbasistype = "quadratic"; meshbasis = "QuadBiquadraticLgn"; }
}
}
// established meshbasis
if ((mlmeshderivatives.isempty())&&(meshbasistype == "cubic"))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no meshderatives matrix was found)", postremark);
}
if (meshbasistype == "cubic")
{
std::vector<int> ddims = mlmeshderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
if (meshtype == "TriSurfMesh")
{
if ((ddims[0] != 2)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
else
{
if ((ddims[0] != 2)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
}
// established and checked mesh type ///
// CHECK THE FIELD PROPERTIES
if (fieldbasistype == "")
{
if ((numfield == numelements)&&(numfield != numnodes))
{
fieldbasistype = "constant";
}
else if (numfield == numnodes)
{
if (meshbasistype == "quadratic")
{
fieldbasistype = "quadratic";
}
else if ((meshbasistype == "cubic")&&(mlfieldderivatives.isdense()))
{
fieldbasistype = "cubic";
}
else
{
fieldbasistype = "linear";
}
}
else
{
if ((meshbasistype == "quadratic"))
{
fieldbasistype = "linear";
}
else
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements in field does not match mesh)", postremark);
}
}
}
if (fieldbasistype == "constant")
{
if (numfield != numelements)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements in field does not match mesh)", postremark);
}
fieldbasis = "ConstantBasis";
}
if ((fieldbasistype == "linear")||(fieldbasistype == "cubic"))
{
if ((meshbasistype == "quadratic")&&(mlfieldedge.isempty()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldedge connectivity matrix)", postremark);
}
if (fieldbasistype == "linear")
{
if (meshtype == "TriSurfMesh") fieldbasis = "TriLinearLgn"; else fieldbasis = "QuadBilinearLgn";
}
else
{
if (mlfieldderivatives.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldderivatives matrix)", postremark);
}
if (meshtype == "TriSurfMesh") fieldbasis = "TriCubicHmt"; else fieldbasis = "QuadBicubicHmt";
}
}
if (fieldbasis == "quadratic")
{
if (((meshbasistype == "linear")||(meshbasistype == "cubic"))&&(true))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldedge connectivity matrix)", postremark);
}
if (meshtype == "TriSurfMesh") fieldbasis = "TriQuadraticLgn"; else fieldbasis = "QuadBiquadraticLgn";
}
if ((mlfieldderivatives.isdense())&&(fieldbasistype == "cubic"))
{
std::vector<int> ddims = mlfieldderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
if (meshtype == "TriSurfMesh")
{
if ((ddims[0] != 2)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 3))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
else
{
if ((ddims[0] != 2)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
}
return(1+ret);
}
if (mlcell.isdense())
{
int n,m;
// Edge data is provide hence it must be some line element!
// Supported mesh/field types here:
// CurveField
if (meshtype == "")
{
m = mlcell.getm();
n = mlcell.getn();
if ((m==4)||(m==6)||(m==8)||(m==10)||(m==15)||(m==20)) n = m;
if ((n==4)||(n==6)||(n==8)||(n==10)||(n==15)||(n==20))
{
if ((n==4)||(n==10)) meshtype = "TetVolMesh";
else if ((n==6)||(n==15)) meshtype = "PrismVolMesh";
else meshtype = "HexVolMesh";
}
}
if ((meshtype != "TetVolMesh")&&(meshtype != "PrismVolMesh")&&(meshtype != "HexVolMesh"))
{ // explicitly stated type
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (cell connectivity does not match meshtype)", postremark);
}
// established meshtype //
if ((mledge.isdense())||(mlface.isdense())||
(mlfieldedge.isdense()))
{ // a matrix with multiple connectivities is not yet allowed
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (multiple connectivity matrices defined)", postremark);
}
// Connectivity should be 2D
if ((mlcell.getnumdims() > 2))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (cell connectivity matrix should be 2D)", postremark);
}
// Check whether the connectivity data makes any sense
// from here on meshtype can only be linear/cubic/quadratic
if (meshtype == "TetVolMesh")
{
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=4)&&(m!=4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 4)", postremark);
}
numelements = n;
if ((m!=4)&&(n==4)) { numelements = m; mlcell.transpose(); }
if (meshbasistype == "linear") meshbasis = "TetLinearLgn"; else meshbasis = "TetCubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=10)&&(m!=10))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 10)", postremark);
}
numelements = n;
if ((m!=10)&&(n==10)) { numelements = m; mlcell.transpose(); }
meshbasistype = "TetQuadraticLgn";
}
else
{
m = mlcell.getm(); n = mlcell.getn();
if (((n!=4)&&(m!=4))&&((n!=10)&&(m!=10)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of edge needs to be of size 4 or 10)", postremark);
}
numelements = n;
if (((m!=4)&&(m!=10))&&((n==4)||(n==10))) { numelements = m; m = n; mlcell.transpose(); }
if (m == 4) { meshbasistype = "linear"; meshbasis = "TetLinearLgn"; }
if (m == 10) { meshbasistype = "quadratic"; meshbasis = "TetQuadraticLgn"; }
}
}
else if (meshtype == "PrismVolMesh")
{
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=6)&&(m!=6))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 6)", postremark);
}
numelements = n;
if ((m!=6)&&(n==6)) { numelements = m; mlcell.transpose(); }
if (meshbasistype == "linear") meshbasis = "TetLinearLgn"; else meshbasis = "PrismCubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=15)&&(m!=15))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 15)", postremark);
}
numelements = n;
if ((m!=15)&&(n==15)) { numelements = m; mlcell.transpose(); }
meshbasistype = "PrismQuadraticLgn";
}
else
{
m = mlcell.getm(); n = mlcell.getn();
if (((n!=6)&&(m!=6))&&((n!=15)&&(m!=15)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 6 or 15)", postremark);
}
numelements = n;
if (((m!=6)&&(m!=15))&&((n==6)||(n==15))) { numelements = m; m = n; mlcell.transpose(); }
if (m == 6) { meshbasistype = "linear"; meshbasis = "PrismLinearLgn"; }
if (m == 15) { meshbasistype = "quadratic"; meshbasis = "PrismQuadraticLgn"; }
}
}
else
{
if ((meshbasistype == "linear")||(meshbasistype == "cubic"))
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=8)&&(m!=8))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 8)", postremark);
}
numelements = n;
if ((m!=8)&&(n==8)) { numelements = m; mlcell.transpose(); }
if (meshbasistype == "linear") meshbasis = "HexTrilinearLgn"; else meshbasis = "HexTricubicHmt";
}
else if (meshbasistype == "quadratic")
{
m = mlcell.getm(); n = mlcell.getn();
if ((n!=20)&&(m!=20))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 20)", postremark);
}
numelements = n;
if ((m!=20)&&(n==20)) { numelements = m; mlcell.transpose(); }
meshbasistype = "HexTriquadraticLgn";
}
else
{
m = mlcell.getm(); n = mlcell.getn();
if (((n!=8)&&(m!=8))&&((n!=20)&&(m!=20)))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (one of the dimensions of cell needs to be of size 8 or 20)", postremark);
}
numelements = n;
if (((m!=8)&&(m!=20))&&((n==8)||(n==20))) { numelements = m; m = n; mlcell.transpose(); }
if (m == 8) { meshbasistype = "linear"; meshbasis = "HexTrilinearLgn"; }
if (m == 20) { meshbasistype = "quadratic"; meshbasis = "HexTriquadraticLgn"; }
}
}
// established meshbasis
if ((mlmeshderivatives.isempty())&&(meshbasistype == "cubic"))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no meshderatives matrix was found)", postremark);
}
if (meshbasistype == "cubic")
{
std::vector<int> ddims = mlmeshderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
if (meshtype == "TetVolMesh")
{
if ((ddims[0] != 3)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
else if (meshtype == "PrismVolMesh")
{
if ((ddims[0] != 3)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 6))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
else
{
if ((ddims[0] != 7)&&(ddims[1] != 3)&&(ddims[2] != numelements)&&(ddims[3] != 8))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (meshderatives matrix has not proper dimensions)", postremark);
}
}
}
// established and checked mesh type ///
// CHECK THE FIELD PROPERTIES
if (fieldbasistype == "")
{
if ((numfield == numelements)&&(numfield != numnodes))
{
fieldbasistype = "constant";
}
else if (numfield == numnodes)
{
if (meshbasistype == "quadratic")
{
fieldbasistype = "quadratic";
}
else if ((meshbasistype == "cubic")&&(mlfieldderivatives.isdense()))
{
fieldbasistype = "cubic";
}
else
{
fieldbasistype = "linear";
}
}
else
{
if ((meshbasistype == "quadratic"))
{
fieldbasistype = "linear";
}
else
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements in field does not match mesh)", postremark);
}
}
}
if (fieldbasistype == "constant")
{
if (numfield != numelements)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (number of elements in field does not match mesh)", postremark);
}
fieldbasis = "ConstantBasis";
}
if ((fieldbasistype == "linear")||(fieldbasistype == "cubic"))
{
if ((meshbasistype == "quadratic")&&(mlfieldedge.isempty()))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldedge connectivity matrix)", postremark);
}
if (fieldbasistype == "linear")
{
if (meshtype == "TetVolMesh") fieldbasis = "TetLinearLgn";
else if (meshtype == "PrismVolMesh") fieldbasis = "PrismLinearLgn";
else fieldbasis = "HexTrilinearLgn";
}
else
{
if (mlfieldderivatives.isempty())
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldderivatives matrix)", postremark);
}
if (meshtype == "TetVolMesh") fieldbasis = "TetCubicHmt";
else if (meshtype == "PrismVolMesh") fieldbasis = "PrismCubicHmt";
else fieldbasis = "HexTricubicHmt";
}
}
if (fieldbasis == "quadratic")
{
if (((meshbasistype == "linear")||(meshbasistype == "cubic")))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (no fieldface connectivity matrix)", postremark);
}
if (meshtype == "TetVolMesh") fieldbasis = "TetQuadraticLgn";
else if (meshtype == "PrismVolMesh") fieldbasis = "PrismQuadraticLgn";
else fieldbasis = "HexTriquadraticLgn";
}
if ((mlfieldderivatives.isdense())&&(fieldbasistype == "cubic"))
{
std::vector<int> ddims = mlfieldderivatives.getdims();
if (ddims.size() != 4)
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
if (meshtype == "TetVolMesh")
{
if ((ddims[0] != 3)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 4))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
else if (meshtype == "PrismVolMesh")
{
if ((ddims[0] != 3)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 6))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
else
{
if ((ddims[0] != 7)&&(ddims[1] != datasize)&&(ddims[3] != numelements)&&(ddims[2] != 8))
{
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (fieldderatives matrix has not proper dimensions)", postremark);
}
}
}
return(1+ret);
}
remarkAndThrow("Matrix '" + mlarray.getname() + "' cannot be translated into a SCIRun Field (cannot match the Matlab structure with any of the supported mesh classes)", postremark);
return 0;
}
bool MatlabToFieldAlgo::addtransform(VMesh* vmesh)
{
if (mltransform.isdense())
{
Transform T;
double trans[16];
mltransform.getnumericarray(trans,16);
T.set_trans(trans);
vmesh->set_transform(T);
}
return(true);
}
bool MatlabToFieldAlgo::addnodes(VMesh* vmesh)
{
// Get the data from the Matlab file, which has been buffered
// but whose format can be anything. The next piece of code
// copies and casts the data
if (meshbasistype == "quadratic")
{
error("The converter misses code to add quadratic nodes to mesh");
return (false);
}
std::vector<double> mldata;
mlnode.getnumericarray(mldata);
// Again the data is copied but now reorganised into
// a vector of Point objects
int numnodes = mlnode.getn();
vmesh->node_reserve(VMesh::Node::size_type(numnodes));
int p,q;
for (p = 0, q = 0; p < numnodes; p++, q+=3)
{
vmesh->add_point(Point(mldata[q],mldata[q+1],mldata[q+2]));
}
return (true);
}
bool MatlabToFieldAlgo::addedges(VMesh* vmesh)
{
// Get the data from the Matlab file, which has been buffered
// but whose format can be anything. The next piece of code
// copies and casts the data
if (meshbasistype == "quadratic")
{
error("The converter misses code to add quadratic edges to mesh");
return (false);
}
std::vector<unsigned int> mldata;
mledge.getnumericarray(mldata);
// check whether it is zero based indexing
// In short if there is a zero it must be zero
// based numbering right ??
// If not we assume one based numbering
bool zerobased = false;
int size = static_cast<int>(mldata.size());
for (int p = 0; p < size; p++) { if (mldata[p] == 0) {zerobased = true; break;} }
if (!zerobased)
{ // renumber to go from Matlab indexing to C++ indexing
for (int p = 0; p < size; p++) { mldata[p]--;}
}
int m,n;
m = mledge.getm();
n = mledge.getn();
vmesh->elem_reserve(VMesh::Elem::size_type(n));
VMesh::Node::array_type edge(m);
int r;
r = 0;
for (int p = 0; p < n; p++)
{
for (int q = 0 ; q < m; q++)
{
edge[q] = mldata[r]; r++;
}
vmesh->add_elem(edge);
}
return (true);
}
bool MatlabToFieldAlgo::addfaces(VMesh* vmesh)
{
// Get the data from the Matlab file, which has been buffered
// but whose format can be anything. The next piece of code
// copies and casts the data
if (meshbasistype == "quadratic")
{
error("The converter misses code to add quadratic edges to mesh");
return (false);
}
std::vector<unsigned int> mldata;
mlface.getnumericarray(mldata);
// check whether it is zero based indexing
// In short if there is a zero it must be zero
// based numbering right ??
// If not we assume one based numbering
bool zerobased = false;
int size = static_cast<int>(mldata.size());
for (int p = 0; p < size; p++) { if (mldata[p] == 0) {zerobased = true; break;} }
if (!zerobased)
{ // renumber to go from Matlab indexing to C++ indexing
for (int p = 0; p < size; p++) { mldata[p]--;}
}
int m,n;
m = mlface.getm();
n = mlface.getn();
vmesh->elem_reserve(VMesh::Elem::size_type(n));
VMesh::Node::array_type face(m);
int r;
r = 0;
for (int p = 0; p < n; p++)
{
for (int q = 0 ; q < m; q++)
{
face[q] = mldata[r]; r++;
}
vmesh->add_elem(face);
}
return (true);
}
bool MatlabToFieldAlgo::addcells(VMesh* vmesh)
{
// Get the data from the Matlab file, which has been buffered
// but whose format can be anything. The next piece of code
// copies and casts the data
if (meshbasistype == "quadratic")
{
error("The converter misses code to add quadratic edges to mesh");
return (false);
}
std::vector<unsigned int> mldata;
mlcell.getnumericarray(mldata);
// check whether it is zero based indexing
// In short if there is a zero it must be zero
// based numbering right ??
// If not we assume one based numbering
bool zerobased = false;
int size = static_cast<int>(mldata.size());
for (int p = 0; p < size; p++) { if (mldata[p] == 0) {zerobased = true; break;} }
if (!zerobased)
{ // renumber to go from Matlab indexing to C++ indexing
for (int p = 0; p < size; p++) { mldata[p]--;}
}
int m,n;
m = mlcell.getm();
n = mlcell.getn();
vmesh->elem_reserve(VMesh::Elem::size_type(n));
VMesh::Node::array_type cell(m);
int r;
r = 0;
for (int p = 0; p < n; p++)
{
for (int q = 0 ; q < m; q++)
{
cell[q] = mldata[r]; r++;
}
vmesh->add_elem(cell);
}
return (true);
}
bool MatlabToFieldAlgo::addderivatives(VMesh* /*vmesh*/)
{
if (meshbasistype == "cubic")
{
error("The converter misses code to add cubic hermitian derivatives edges to mesh");
return (false);
}
return (true);
}
bool MatlabToFieldAlgo::addscalefactors(VMesh* /*vmesh*/)
{
if (meshbasistype == "cubic")
{
error("The converter misses code to add cubic hermitian scalefactors edges to mesh");
return (false);
}
return (true);
}
bool MatlabToFieldAlgo::addfield(VField* field)
{
if (field->is_scalar())
{
if (field->is_char())
{
std::vector<char> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_unsigned_char())
{
std::vector<unsigned char> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_short())
{
std::vector<short> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_unsigned_short())
{
std::vector<unsigned short> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_int())
{
std::vector<int> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_unsigned_int())
{
std::vector<unsigned int> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_longlong())
{
std::vector<long long> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_unsigned_longlong())
{
std::vector<unsigned long long> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_float())
{
std::vector<float> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
if (field->is_double())
{
std::vector<double> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
field->set_values(fielddata);
return (true);
}
}
if (field->is_vector())
{
std::vector<double> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
VMesh::size_type numdata = static_cast<VMesh::size_type>(fielddata.size());
if (numdata > (3*field->num_values())) numdata = (3*field->num_values()); // make sure we do not copy more data than there are elements
VField::index_type p,q;
for (p=0,q=0; p < numdata; q++)
{
Vector v(fielddata[p],fielddata[p+1],fielddata[p+2]); p+=3;
field->set_value(v,VMesh::index_type(q));
}
return(true);
}
if (field->is_tensor())
{
std::vector<double> fielddata;
mlfield.getnumericarray(fielddata); // cast and copy the real part of the data
VMesh::size_type numdata = static_cast<VMesh::size_type>(fielddata.size());
Tensor tensor;
if (mlfield.getm() == 6)
{ // Compressed tensor data : xx,yy,zz,xy,xz,yz
if (numdata > (6*field->num_values())) numdata = (6*field->num_values()); // make sure we do not copy more data than there are elements
VField::index_type p,q;
for (p = 0, q = 0; p < numdata; p +=6, q++)
{
compressedtensor(fielddata,tensor,p);
field->set_value(tensor,VMesh::index_type(q));
}
}
else
{ // UnCompressed tensor data : xx,xy,xz,yx,yy,yz,zx,zy,zz
if (numdata > (9*field->num_values())) numdata = (9*field->num_values()); // make sure we do not copy more data than there are elements
VField::index_type p,q;
for (p = 0, q = 0; p < numdata; p +=9, q++)
{
uncompressedtensor(fielddata,tensor,p);
field->set_value(tensor,VMesh::index_type(q));
}
}
}
return(true);
}
MatlabToFieldAlgo::MatlabToFieldAlgo() : numnodes(0), numelements(0), numfield(0), datasize(0)
{
}
void MatlabToFieldAlgo::setreporter(LoggerHandle pr)
{
pr_ = pr;
}
void MatlabToFieldAlgo::error(const std::string& error) const
{
if(pr_) pr_->error(error);
}
void MatlabToFieldAlgo::warning(const std::string& warning) const
{
if(pr_) pr_->warning(warning);
}
void MatlabToFieldAlgo::remark(const std::string& remark) const
{
if(pr_) pr_->remark(remark);
}
void MatlabToFieldAlgo::compressedtensor(std::vector<double> &fielddata,Tensor &tens, unsigned int p)
{
tens.val(0,0) = fielddata[p+0];
tens.val(0,1) = fielddata[p+1];
tens.val(0,2) = fielddata[p+2];
tens.val(1,0) = fielddata[p+1];
tens.val(1,1) = fielddata[p+3];
tens.val(1,2) = fielddata[p+4];
tens.val(2,0) = fielddata[p+2];
tens.val(2,1) = fielddata[p+4];
tens.val(2,2) = fielddata[p+5];
}
void MatlabToFieldAlgo::uncompressedtensor(std::vector<double> &fielddata,Tensor &tens, unsigned int p)
{
tens.val(0, 0) = fielddata[p];
tens.val(0, 1) = fielddata[p + 1];
tens.val(0, 2) = fielddata[p + 2];
tens.val(1, 0) = fielddata[p + 3];
tens.val(1, 1) = fielddata[p + 4];
tens.val(1, 2) = fielddata[p + 5];
tens.val(2, 0) = fielddata[p + 6];
tens.val(2, 1) = fielddata[p + 7];
tens.val(2, 2) = fielddata[p + 8];
}
| [
"dwhite@sci.utah.edu"
] | dwhite@sci.utah.edu |
4305abeda2e8695d021eef8aba071dc01c516a26 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/net/tapi/skywalker/ipconf/test/t3out/systemp.h | 55a194d6ffc2f7397551dd45cf339fefb0ac7e42 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,999 | h |
/****************************************************************************
* @doc INTERNAL SYSTEMP
*
* @module SystemP.h | Header file for the <c CSystemProperty>
* class used to implement a property page to test the TAPI control
* interface <i ITQualityControllerConfig>.
***************************************************************************/
#define NUM_SYSTEM_CONTROLS 6
#define IDC_Curr_OutputBandwidth 0
#define IDC_Curr_InputBandwidth 1
#define IDC_Curr_CPULoad 2
#define IDC_Max_OutputBandwidth 3
#define IDC_Max_InputBandwidth 4
#define IDC_Max_CPULoad 5
/****************************************************************************
* @doc INTERNAL CSYSTEMPCLASS
*
* @class CSystemProperty | This class implements handling of a
* single net property in a property page.
*
* @mdata int | CSystemProperty | m_NumProperties | Keeps
* track of the number of properties.
*
* @mdata ITQualityControllerConfig* | CSystemProperty | m_pITQualityControllerConfig | Pointer
* to the <i ITQualityControllerConfig> interface.
***************************************************************************/
class CSystemProperty : public CPropertyEditor
{
public:
CSystemProperty(HWND hDlg, ULONG IDLabel, ULONG IDMinControl, ULONG IDMaxControl, ULONG IDDefaultControl, ULONG IDStepControl, ULONG IDEditControl, ULONG IDTrackbarControl, ULONG IDProgressControl, ULONG IDProperty); //, ITQualityControllerConfig *pITQualityControllerConfig);
~CSystemProperty ();
// CPropertyEditor base class pure virtual overrides
HRESULT GetValue();
HRESULT SetValue();
HRESULT GetRange();
private:
// ITQualityControllerConfig *m_pITQualityControllerConfig;
};
/****************************************************************************
* @doc INTERNAL CSYSTEMPCLASS
*
* @class CSystemProperties | This class implements a property page
* to test the new TAPI control interface <i ITQualityControl>.
*
* @mdata int | CSystemProperties | m_NumProperties | Keeps
* track of the number of properties.
*
* @mdata ITQualityControllerConfig* | CSystemProperties | m_pITQualityControllerConfig | Pointer
* to the <i ITQualityControllerConfig> interface.
*
* @mdata CSystemProperty* | CSystemProperties | m_Controls[NUM_SYSTEM_CONTROLS] | Array
* of capture properties.
***************************************************************************/
class CSystemProperties
{
public:
CSystemProperties();
~CSystemProperties();
HPROPSHEETPAGE OnCreate();
HRESULT OnConnect(ITAddress *pITAddress);
HRESULT OnDisconnect();
HRESULT OnActivate();
HRESULT OnDeactivate();
HRESULT OnApplyChanges();
private:
void SetDirty();
BOOL m_bInit;
HWND m_hDlg;
int m_NumProperties;
// ITQualityControllerConfig *m_pITQualityControllerConfig;
CSystemProperty *m_Controls[NUM_SYSTEM_CONTROLS];
// Dialog proc
static BOOL CALLBACK BaseDlgProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam);
};
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
65a9b113f0b13074b8a94782fb834fee86b1b1d6 | 0c212767060623791f8ecc7dd172f8c9f853f443 | /R2DEngine/R2DEngine/Rigidbody2D.h | 8e9d150faa1671d815670417c778ae5cfd5040f7 | [] | no_license | rohunb/R2DEngine | bafcb00162eca57fc33c4da3b4a7edefc4a8bb5a | 4001c76d1c8bd6ee0d8d63e5075fcb26c76c0543 | refs/heads/master | 2021-03-12T19:16:52.363914 | 2015-08-05T23:47:18 | 2015-08-05T23:47:18 | 33,456,403 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 338 | h | #ifndef R_RIGIDBODY_2D_H_
#define R_RIGIDBODY_2D_H_
#include "R2DComponent.h"
#include "RVector.h"
namespace rb
{
class Rigidbody2D: public R2DComponent
{
public:
Vec2 velocity;
Rigidbody2D();
explicit Rigidbody2D(const Vec2& velocity);
//default copy/move/dtors
void Update(float dt);
};
}
#endif // R_RIGIDBODY_2D_H_
| [
"rohunb@gmail.com"
] | rohunb@gmail.com |
5ba7f4a63c26546bef68ea6481334583eca1bc5c | 6b4f03decc4ae4d9bd24641e69137d9f4a98eafa | /HavokOpenGL/HavokOpenGL/Game.h | 238ec9061978903771d9e78120f1b632b3f3eab6 | [] | no_license | Desendos/PhysicsGame | fc4211ba211d15a4271728ec7d84acad2fcb682a | 14082152869f1508fe8416e20ef65a4109db81b4 | refs/heads/master | 2020-04-06T07:03:24.373923 | 2014-04-28T17:21:59 | 2014-04-28T17:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,237 | h | #pragma once
#include "BaseGame.h"
#include "DebugPrint.h"
#include <string>
#include "BFont.h"
#include "Timer.h"
#include "HavokInit.h"
#include <irrKlang.h>
using namespace timer;
#define _USE_MATH_DEFINES
#include <math.h>
#include "random.h"
using namespace random;
using namespace std;
const float VIEW_ANGLE = 50.0f; // field of view in the Y direction
const float NEAR_CLIPPING = 0.05f; // near clipping distance (5cm)
const float FAR_CLIPPING = 1000.0f; // far clipping distance (10m)
const int ARRAY_BOX_NUMBER = 4;
const int ARRAY_WALL_NUMBER = 3;
//MY CLASSES
#include "Platform.h"
#include "Box.h"
#include "OGL_Box.h"
#include "Sphere.h"
#include "OGL_Sphere.h"
#include "Marker.h"
using namespace irrklang;
const float ANGLE_LIMIT = 7.0f * HK_REAL_PI/180.0f; // 7 degrees limit
/**
The class inherits from BaseGame and provides the game data model and the game logic
*/
class Game : public BaseGame{
// Allow event handler direct access to these attributes
// (copied from BaseGame since friendship is not inherited)
friend LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
// HERE WE DECLARE ANY FONTS, TIMERS OR OTHER VARIABLES WE WANT
int mouseX, mouseY;
float camX, camY, camZ, camRad;
float angEW, angNS;
BFont* font1;
char text[256];
ISoundEngine* m_sEngine;
Timer* timer;
float cft, lft, tbf, fps, avgFps;
unsigned int fCount;
// HERE WE DECLARE ANY GAME OBJECTS AND CREATE THEM IN THE INITIALISE function
//HAVOK
hkpWorld* m_world; // Havok persistent objects
#ifdef _DEBUG
hkVisualDebugger* m_vdb;
hkpPhysicsContext* m_physicsContext;
#endif
///////
//Physics objects
Box* pForm;
Box* pBox;
Box* pBoxArray[ARRAY_BOX_NUMBER];
Sphere* pSphere;
Box* pWall[ARRAY_WALL_NUMBER];
//OpenGL objects
OGL_Box* oPlatform;
OGL_Box* oBox;
OGL_Box* oBoxArray[ARRAY_BOX_NUMBER];
OGL_Sphere* oSphere;
Marker* mark;
OGL_Box* oWall[ARRAY_WALL_NUMBER];
Marker* goal;
bool isColliding;
float toX,toY,toZ;
bool placingWalls;
int wallNumber;
public:
bool physicsState;
Game(void);
virtual ~Game(void);
/**
Use this method to perform any first time initialisation of OpenGL
*/
void InitOpenGL();
/**
Use this method to create timers, fonts and all game objects. Do NOT
execute any OpenGL commands in this method, use initOpenGL instead.
*/
void Initialise();
/**
Use this method to perform any clean up of objects created for
the game - including fonts and timers.
*/
void Shutdown();
/**
Use this method to create any game objects and initialise the
game's state
*/
bool InitGame();
/**
Use this method to update the game's state, but do not use it for rendering
*/
void Game::Update();
/**
The main rendering method - renders a single frame
*/
void Game::Render();
/**
Used to alter Camera x, y and z positions
*/
void CameraPos();
/**
Used to display text messages in game display area
*/
void RenderHUD();
void initPhysicsObjects();
void makeWall();
void moveWeight1Up();
void moveWeight1Down();
void moveWeight2Up();
void moveWeight2Down();
void makeWeightsJump();
void moveMarkerUp();
void moveMarkerDown();
void moveMarkerRight();
void moveMarkerLeft();
void makeGoal();
};
| [
"rseymour8@gmail.com"
] | rseymour8@gmail.com |
0014dd091151313cc5aca1f13c036272ef55b03f | 81c66c9c0b78f8e9c698dcbb8507ec2922efc8b7 | /src/domains/de/kernel/EventQueue.cc | 5327341dbc2b30846fe1ce2dce69ef8da35d5d5d | [
"MIT-Modern-Variant"
] | permissive | Argonnite/ptolemy | 3394f95d3f58e0170995f926bd69052e6e8909f2 | 581de3a48a9b4229ee8c1948afbf66640568e1e6 | refs/heads/master | 2021-01-13T00:53:43.646959 | 2015-10-21T20:49:36 | 2015-10-21T20:49:36 | 44,703,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,676 | cc | static const char file_id[] = "EventQueue.cc";
/**************************************************************************
Version identification:
@(#)EventQueue.cc 2.6 03/02/95
Copyright (c) 1990-1997 The Regents of the University of California.
All rights reserved.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in all
copies of this software.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
PT_COPYRIGHT_VERSION_2
COPYRIGHTENDKEY
Programmer: Soonhoi Ha
Date of creation: 10/11/91
Revisions:
This file contains member functions for EventQueue..
******************************************************************/
#ifdef __GNUG__
#pragma implementation
#endif
#include "EventQueue.h"
#include "Particle.h"
Event* EventQueue:: getEvent(Particle* p, PortHole* ph) {
Event* temp;
// a free event instance
if (freeEventHead) {
temp = freeEventHead;
freeEventHead = temp->next;
} else {
LOG_NEW; temp = new Event;
}
// set the event members.
temp->dest = ph;
temp->p = p;
return temp;
}
// delete the free events.
void EventQueue:: clearFreeEvents() {
if (!freeEventHead) return;
while (freeEventHead->next) {
Event* temp = freeEventHead;
freeEventHead = freeEventHead->next;
LOG_DEL; delete temp;
}
LOG_DEL; delete freeEventHead;
freeEventHead = 0;
}
// Put the unused particles into the plasmas.
void EventQueue:: clearParticles() {
Event* temp = freeEventHead;
while (temp) {
temp->p->die();
temp = temp->next;
}
}
void EventQueue:: putFreeLink(LevelLink* p) {
if (p->fineLevel) {
Event* temp = (Event*) p->e;
putEvent(temp);
}
PriorityQueue:: putFreeLink(p);
}
void EventQueue :: initialize() {
// first maintain free links and free events.
clearFreeEvents();
PriorityQueue :: initialize();
clearParticles();
}
EventQueue :: ~EventQueue() {
initialize();
clearFreeEvents();
}
| [
"dermalin3k@hotmail.com"
] | dermalin3k@hotmail.com |
1e2f97eb093f87bd517477d5f38981b45ef24dc3 | 99f5cc49d507b217e67d1dfb2971ea0794dc9edd | /HackerRank/C++/LANG/pointers.cpp | 457f07f38d39a1ae1ad89000f726f9ac07af2c16 | [] | no_license | OmkarSsawant/Programming-Battle- | 2de886f9ee5cd72ca2e1259f35f64a663d23bccd | dac2c4c1d2f6076f34217f228623e3a18aecc5a2 | refs/heads/main | 2023-04-30T18:36:15.697221 | 2021-05-25T06:36:14 | 2021-05-25T06:36:14 | 336,482,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 529 | cpp | #include <stdio.h>
#include<math.h>
/* You have to complete the function void update(int *a,int *b),
which reads two integers as argument,
and sets with a the sum of them, and b with the absolute difference of them. */
void update(int *a, int *b)
{
int o1 =(*a) + (*b);
(*b) = abs((*a) - (*b));
*a = o1;
// Complete this function
}
int main()
{
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
| [
"omkar18sawant@gmail.com"
] | omkar18sawant@gmail.com |
1d4ba6f524c4cc30746bdabb9368a4f4d19ac8b6 | 5deab316a4ab518e3a409ab69885d372f4d45706 | /PreNationals/Contests/CF/NWERC2021/A.cpp | b3958c63acd293aaa291e3c16a55374cc7e5ea78 | [] | no_license | af-orozcog/competitiveProgramming | 9c01937b321b74f3d6b24e1b8d67974cad841e17 | 5bbfbd4da9155a7d1ad372298941a04489207ff5 | refs/heads/master | 2023-04-28T11:44:04.320533 | 2021-05-19T19:04:30 | 2021-05-19T19:04:30 | 203,208,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | #include<bits/stdc++.h>
#define ll long long
using namespace std;
typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
ll gcd(ll a, ll b){
return b == 0? a: gcd(b,a%b);
}
ll lcm(ll a, ll b){
return (a/gcd(a,b))*b;
}
pi maxx(pl &a,pl &b){
if(a.first*b.second >= b.first*a.second) return a;
return b;
}
int main(){
int n,q;
scanf(" %d %d",&n,&q);
int nums[n+1];
nums[0] = 0;
for(int i = 1; i <= n;++i) scanf(" %d",&nums[i]);
pl use = {1,nums[1]};
ll imp = gcd(use.first,use.second);
use.first /= imp, use.second /= imp;
for(int i = 2; i <= n;++i){
pl comp = {i,nums[i]};
imp = gcd(comp.first,comp.second);
comp.first /= imp, comp.second /= imp;
use = maxx(use,comp);
}
int co = 2*10000+1;
ll dp[2*10000+1];
for(int i = 1; i <= n;++i) dp[i] = (ll)nums[i];
for(int i = n+1; i < co;++i){
dp[i] = LLONG_MAX;
for(int j = 1;j <= n;++j)
dp[i] = min(dp[i],dp[j]+dp[i-j]);
}
while(q--){
int k;
scanf(" %d",&k);
if(k < co){
printf("%lld\n",dp[k]); continue;
}
ll x = (k-co)/use.first + 1;
ll ans = x*(ll)nums[use.first];
k -= x*use.first;
ans += dp[k];
printf("%lld\n",ans);
}
return 0;
}
| [
"af.orozcog@uniandes.edu.co"
] | af.orozcog@uniandes.edu.co |
3aa1748194313ea862de65a9acc2962b2dd68f1d | 30b58700c2a2c5801a6e9a0486e9d302a65c84a9 | /images/battery/battery0.cpp | 3098ee65a90e025addb2bece68920124fdb09666 | [] | no_license | Wendor/arduino-barman | ce44833f6a307391f764ebd55c89a97409a40736 | 8a1ed5b242d92a6987df550949ac56ffdebd6eb9 | refs/heads/master | 2023-02-14T04:03:11.706677 | 2020-08-07T05:32:45 | 2020-08-07T05:32:45 | 328,623,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | static const uint8_t battery0[] PROGMEM = {
0b00011000,
0b01111110,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b10000001,
0b11111111
}; | [
"weny@bk.ru"
] | weny@bk.ru |
0eae5157f4b2da888a54ff681eccb4a8a4056183 | e47319035ba7422b224125a28434fa45569e3a9f | /Min-Length-Subarray-Unsorted/Min-Length-Subarray-Unsorted/Source.cpp | 1bd040e1bc83126b3e44ce80ad2740379a701831 | [] | no_license | HassanMahmoudd/DataStructures-Algorithms | 76e5b521a34fb0ba215e109b9e6819fa6e437b5d | e043202e06e195e5222eb6c0c6e3d42eb6604298 | refs/heads/master | 2021-01-17T07:31:34.715538 | 2017-09-17T01:05:39 | 2017-09-17T01:05:39 | 83,744,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,085 | cpp | #include<set>
#include<map>
#include<list>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<complex>
#include<sstream>
#include<iostream>
#include<fstream>
#include<iterator>
#include<algorithm>
#include<numeric>
#include<utility>
#include<functional>
#include<stdio.h>
#include<assert.h>
#include<memory.h>
#include<bitset>
using namespace std;
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define clr(v, d) memset(v, d, sizeof(v))
#define rep(i, v) for(int i=0;i<sz(v);++i)
#define lp(i, n) for(int i=0;i<(int)(n);++i)
#define lpi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define lpd(i, j, n) for(int i=(j);i>=(int)(n);--i)
typedef long long ll;
const ll OO = 1e8;
const double EPS = (1e-7);
int dcmp(double x, double y) { return fabs(x - y) <= EPS ? 0 : x < y ? -1 : 1; }
#define pb push_back
#define MP make_pair
#define P(x) cout<<#x<<" = { "<<x<<" }\n"
typedef long double ld;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector< vi > vvi;
typedef vector< vd > vvd;
typedef vector<string> vs;
void minLengthSubarray(vector<int> matrix)
{
int startIndex, endIndex;
for (int i = 0; i < matrix.size() - 1; i++)
{
if (matrix[i] > matrix[i + 1])
{
startIndex = i;
break;
}
}
for (int j = matrix.size() - 1; j >= 1; j--)
{
if (matrix[j] < matrix[j - 1])
{
endIndex = j;
break;
}
}
auto maxElement = max_element(matrix.begin() + startIndex, matrix.begin() + endIndex);
auto minElement = min_element(matrix.begin() + startIndex, matrix.begin() + endIndex);
for (int i = 0; i < startIndex; i++)
{
if (matrix[i] > *minElement)
{
startIndex = i;
break;
}
}
for (int j = matrix.size() - 1; j > endIndex; j--)
{
if (matrix[j] < *maxElement)
{
endIndex = j;
break;
}
}
cout << startIndex << " to " << endIndex << endl;
}
int main() {
vector<int> matrix(10);
matrix = { 1, 4, 7, 3, 10, 48, 17, 26, 30, 45, 50, 62};
minLengthSubarray(matrix);
return 0;
}
| [
"hassanmahmoudsd@gmail.com"
] | hassanmahmoudsd@gmail.com |
27c0f94e52266e07832b339a086e5ac35c6fee4e | a0be71e84272af17e3f9c71b182f782c35a56974 | /Mesh/App/FeatureMeshSegmentByMesh.h | f4580d5ddf87dd69953eba75988c4f59a1e576d0 | [] | no_license | PrLayton/SeriousFractal | 52e545de2879f7260778bb41ac49266b34cec4b2 | ce3b4e98d0c38fecf44d6e0715ce2dae582c94b2 | refs/heads/master | 2021-01-17T19:26:33.265924 | 2016-07-22T14:13:23 | 2016-07-22T14:13:23 | 60,533,401 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | h | /***************************************************************************
* Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#ifndef FEATURE_MESH_SEGMENTBYMESH_H
#define FEATURE_MESH_SEGMENTBYMESH_H
#include <App/PropertyStandard.h>
#include "MeshFeature.h"
#include <App/PropertyLinks.h>
#include <App/PropertyGeo.h>
namespace Mesh
{
/**
* The SegmentByMesh class creates a mesh segment from two meshes whereat
* the facets of the first mesh that lie inside the second mesh build up the segment.
* @author Werner Mayer
*/
class SegmentByMesh : public Mesh::Feature
{
PROPERTY_HEADER(Mesh::SegmentByMesh);
public:
SegmentByMesh();
App::PropertyLink Source;
App::PropertyLink Tool;
App::PropertyVector Base;
App::PropertyVector Normal;
/** @name methods overide Feature */
//@{
/// recalculate the Feature
App::DocumentObjectExecReturn *execute(void);
short mustExecute() const;
//@}
};
}
#endif // FEATURE_MESH_SEGMENTBYMESH_H
| [
"gogokoko3@hotmail.fr"
] | gogokoko3@hotmail.fr |
8d92fa643ca05bf0c7ee0dfbeaadadfbcd313a86 | 1caac536823205c3cb57b7db726e72ae035a846d | /simulateur/srcSimu/dynamiquePassive.h | 859ba9b6ea69d7c52b2c7713c4f406addfebd080 | [] | no_license | nicolasboulay/astromech | 0a86754b727c155649b1ae918f163eaee69e20b7 | ab20004b31bce5607a2e138bc2301e425196dbdc | refs/heads/master | 2021-01-10T19:20:01.209757 | 2007-05-26T21:33:29 | 2007-05-26T21:33:29 | 38,930,094 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 590 | h | #ifndef DynamiquePassiveH
#define DynamiquePassiveH
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class Effecteur;
class Trace;
class Systeme;
class Contour;
class DynamiquePassive : public Effecteur
{
protected: //accessible uniquement par héritage
Contour * contour;
public : // accessible partout
DynamiquePassive(Systeme *s,Trace * t);
~DynamiquePassive(void);
void execute(int tempsCourant_ms);
void chargerXML(TiXmlElement* pModuleXML);
void connectModules(void);
};
#endif
| [
"nicolas.boulay@4a5454c4-a219-0410-82dd-e5acffe59b65"
] | nicolas.boulay@4a5454c4-a219-0410-82dd-e5acffe59b65 |
6eba327c905a1c5d46f3b2c176ab757852645bde | a6f6975d724ae7dcd047392e109a4ee32a2276c9 | /Week12 lab/Week12 lab/Ex4.cpp | e2739dc05bedf27ec8156a072739602e8c940962 | [] | no_license | PhilipHenderson/Lab5 | 0fdb1e8a8b3323fed45a05a89ea958f4f5c7fb15 | 38c2a41c94eeca4857dabe536e93101442098c35 | refs/heads/main | 2023-03-31T07:18:12.160193 | 2021-04-07T18:23:49 | 2021-04-07T18:23:49 | 355,350,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | cpp | #include <iostream>
#include <cstdlib>
#include "DynTempQueue.h"
using namespace std;
int main()
{
DynTempQueue<int> iQueue;
DynTempQueue<double> dQueue;
cout << "Enqueue up to 15 Ints...\n";
for (int i = 1; i <= 15; i++)
{
iQueue.enqueue(i);
cout << i << " ";
}
cout << endl;
cout << "Dequeued Int Values Were:\n";
while (!iQueue.isEmpty())
{
int value;
iQueue.dequeue(value);
cout << value << " ";
}
cout << endl;
cout << endl;
cout << "Enqueue up tp 15 Doubles...\n";
for (double i = 1; i <= 15; i = (i * 1.25))
{
dQueue.enqueue(i);
cout << i << " ";
}
cout << endl;
cout << "Dequeued Double Values Were:\n";
while (!dQueue.isEmpty())
{
double value;
dQueue.dequeue(value);
cout << value << " ";
}
cout << endl << endl;
return 0;
} | [
"philip.henderson@hotmail.com"
] | philip.henderson@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.