repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
AndyHuntDesign/andyhuntdesign | wp-content/plugins/nextend-smart-slider2-full/plugins/nextendslidergenerator/instagram/tagsearch/generator.php | 2932 | <?php
nextendimportsmartslider2('nextend.smartslider.generator_abstract');
class NextendGeneratorInstagram_TagSearch extends NextendGeneratorAbstract {
function NextendGeneratorInstagram_TagSearch($data) {
parent::__construct($data);
$this->_variables = array(
'title' => NextendText::_('Caption_of_the_image'),
'image' => NextendText::_('Url_of_the_photo'),
'thumbnail' => NextendText::_('Thumbnail_image_url'),
'url' => NextendText::_('Website_of_the_photo_s_owner'),
'author_name' => NextendText::_('Full_name_of_the_photo_s_owner'),
'author_url' => NextendText::_('Website_of_the_photo_s_owner'),
'low_res_image' => NextendText::_('Low_resolution_image_url'),
'owner_username' => NextendText::_('Username_of_the_photo_s_owner'),
'owner_website' => NextendText::_('Website_of_the_photo_s_owner'),
'owner_profile_picture' => NextendText::_('Profile_picture_of_the_photo_s_owner'),
'owner_bio' => NextendText::_('Bio_of_the_photo_s_owner'),
'comment_count' => NextendText::_('Comment_count_on_the_image')
);
}
function getData($number) {
$data = array();
$api = getNextendInstagram();
if (!$api) return $data;
$instagramtagsearch = $this->_data->get('instagramtagsearch', '');
$result = json_decode($api->getRecentTags($instagramtagsearch), true);
if ($result['meta']['code'] == 200) {
$i = 0;
foreach ($result['data'] AS $image) {
if ($image['type'] != 'image') continue;
$data[$i]['title'] = $data[$i]['caption'] = is_array($image['caption']) ? $image['caption']['text'] : '';
$data[$i]['image'] = $data[$i]['standard_res_image'] = $image['images']['standard_resolution']['url'];
$data[$i]['thumbnail'] = $data[$i]['thumbnail_image'] = $image['images']['thumbnail']['url'];
$data[$i]['description'] = 'Description is not available for Intagram images.';
$data[$i]['url'] = $image['link'];
$data[$i]['url_label'] = 'View image';
$data[$i]['author_name'] = $data[$i]['owner_full_name'] = $image['user']['full_name'];
$data[$i]['author_url'] = $data[$i]['owner_website'] = ($image['user']['website'] ? $image['user']['website'] : '#');
$data[$i]['low_res_image'] = $image['images']['low_resolution']['url'];
$data[$i]['owner_username'] = $image['user']['username'];
$data[$i]['owner_profile_picture'] = $image['user']['profile_picture'];
$data[$i]['owner_bio'] = $image['user']['bio'];
$data[$i]['comment_count'] = $image['comments']['count'];
$i++;
}
}
return $data;
}
} | gpl-2.0 |
widelands/widelands | data/campaigns/emp01.wmf/scripting/mission_thread.lua | 3640 | function mission_thread()
sleep(1000)
-- Initial messages
local sea = wl.Game().map:get_field(50,25)
local ship = p1:place_ship(sea)
p1:hide_fields(sea:region(6), "permanent")
scroll_to_field(sea,0)
campaign_message_box(diary_page_1)
sleep(200)
-- Show the sea
reveal_concentric(p1, sea, 5)
sleep(1000)
campaign_message_box(diary_page_2)
sleep(500)
-- hide a bit more as revealed as the ship might move and discover some fields
hide_concentric(p1, sea, 6)
ship:remove()
-- Back home
include "map:scripting/starting_conditions.lua"
p1:hide_fields(wl.Game().map.player_slots[1].starting_field:region(13),"permanent")
scroll_to_field(wl.Game().map.player_slots[1].starting_field)
campaign_message_box(diary_page_3)
sleep(1000)
reveal_concentric(p1, wl.Game().map.player_slots[1].starting_field, 13)
sleep(400)
-- Check for trees and remove them
local fields = {{12,0}, -- Buildspace
{12,1}, -- Flag of building
{12,2}, {11,2}, -- Roads ...
{10,2}, {9,2},
{8,2}, {7,1},
{7,0},}
remove_trees(fields)
campaign_message_box(saledus_1)
p1:allow_buildings{"empire_blockhouse"}
local o = add_campaign_objective(obj_build_blockhouse)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:run_training_wheel("objectives", true)
while #p1:get_buildings("empire_blockhouse") < 1 do sleep(3249) end
set_objective_done(o)
-- Blockhouse is completed now
-- Make sure no tree blocks the building space for Lumberjack
local fields = {{6,3}, -- Buildspace
{7,4}, -- Flag of building
{7,3}, {7,2},} -- Roads
remove_trees(fields)
campaign_message_box(saledus_2)
p1:allow_buildings{"empire_lumberjacks_house"}
o = add_campaign_objective(obj_build_lumberjack)
campaign_message_box(amalea_1)
while #p1:get_buildings("empire_lumberjacks_house") < 1 do sleep(3249) end
set_objective_done(o)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:mark_training_wheel_as_solved("logs")
-- Lumberjack is now build
campaign_message_box(amalea_2)
p1:allow_buildings{"empire_sawmill"}
o = add_campaign_objective(obj_build_sawmill_and_lumberjacks)
while not check_for_buildings(p1, { empire_lumberjacks_house = 3, empire_sawmill = 1})
do sleep(2343) end
set_objective_done(o)
-- Now the lady demands a forester after having us cut down the whole forest.
campaign_message_box(amalea_3)
o = add_campaign_objective(obj_build_forester)
p1:allow_buildings{"empire_foresters_house"}
while not check_for_buildings(p1, { empire_foresters_house = 1 }) do sleep(2434) end
set_objective_done(o)
-- Now a quarry
campaign_message_box(saledus_3)
o = add_campaign_objective(obj_build_quarry)
p1:allow_buildings{"empire_quarry"}
while not check_for_buildings(p1, { empire_quarry = 1 }) do sleep(2434) end
set_objective_done(o)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:mark_training_wheel_as_solved("rocks")
-- All buildings done. Got home
campaign_message_box(saledus_4)
sleep(25000) -- Sleep a while
campaign_message_box(diary_page_4)
p1:mark_scenario_as_solved("emp01.wmf")
end
-- Show a funny message when the player has build 10 blockhouses
function easter_egg()
while not check_for_buildings(p1, {empire_blockhouse = 10}) do sleep(4253) end
campaign_message_box(safe_peninsula)
end
run(mission_thread)
run(easter_egg)
| gpl-2.0 |
gdassori/BitcoinAVM | base_app/views.py | 7524 | # Bitcoin AVM, an open source Django base Bitcoin ATM
# https://github.com/mn3monic/BitcoinAVM
import scripts, json, sys, time
#from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseServerError
from datetime import datetime
from base_app.btcprocessor import BTCProcessor, Configuration
from base_app.models import Transactions, Peripherals
from base_app.utils import get_btccurrency_rate, Currency, log_error, to_btc
def index(request):
params = {}
configuration = scripts.check_configuration()
if not configuration:
params['missing_config'] = True
else:
params['configuration'] = configuration
btc_processor = BTCProcessor(False)
params['wallet_exists'] = btc_processor.does_wallet_exists()
return render(request, 'index.html', params)
def create_wallet(request):
BTCProcessor(True)
return redirect('/')
def restore_from_seed(request):
btcprocessor = BTCProcessor(False)
seed = request.POST.get('seedToRestore')
btcprocessor.restore_wallet_from_seed(seed)
return redirect('/')
def machine_status(request):
# get the machine status based on network connectivity, btc availability etc...
machine_status = {}
machine_status['active'] = True # TODO: replace this with proper implementation
try:
config = Configuration.objects.get()
except Configuration.DoesNotExist:
machine_status['error'] = True
machine_status['missing_configuration'] = True
return HttpResponse(json.dumps(machine_status), content_type="application/json")
try:
currency_btc_rate = get_btccurrency_rate(config.currency)
machine_status['exchange_rate'] ='%.2f' % currency_btc_rate
machine_status['last_retrieved'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
machine_status['currency'] = Currency.AcceptedCurrency[config.currency-1][1]
return HttpResponse(json.dumps(machine_status), content_type="application/json")
except:
return HttpResponseServerError(json.dumps({'error': "can't connect to Bitstamp Api"}), content_type="application/json")
def transaction_init(request):
"""
Start transaction page:
- Start transaction with a new session_id
- Set init_timestamp
- Set fixed price for exchange rate, fetch latest
- Enable QR code reader
- Set status: init
- Returns sessionId and available coins
"""
config = Configuration.objects.get()
transaction_exchange_rate = get_btccurrency_rate(config.currency)
init_tx_result = scripts.init_transaction(transaction_exchange_rate)
session_id = init_tx_result['session_id']
initialized = init_tx_result['initialized']
request.session['session_id'] = session_id
if not session_id:
return HttpResponseServerError(json.dumps('Invalid session id'), content_type="application/json")
if initialized:
return HttpResponse(json.dumps(init_tx_result), content_type="application/json")
else:
return HttpResponseServerError(json.dumps('ATM disabled'), content_type="application/json")
def read_address(request):
res = {}
try:
session_id = '9d0e2ee14b44d4d75f682f0be1c24f73'
#session_id = request.session['session_id']
except:
res = {'error': 1, 'message': 'no session id'}
return HttpResponse(json.dumps(res), content_type="application/json")
else:
status = request.GET.get('status') # TODO: Switch to post, GET only for testing
if status == 'start':
print 'starting qrcode reader'
scripts.qrcode_reader(status, session_id)
res['status'] = 'QRCode reader started'
res['error'] = 0
elif status == 'stop':
print 'stopping qrcode reader'
per = Peripherals.objects.get()
per.qrcode_status = False
per.save()
res['status'] = 'QRCode reader stopped'
res['error'] = 0
elif status == 'check':
transaction = Transactions.objects.get(session_id = session_id)
dest_addr = transaction.dest_address
if dest_addr != '':
res['address'] = dest_addr
res['error'] = 0
else:
res['status'] = 'invalid request'
res['error'] = 1
return HttpResponse(json.dumps(res), content_type="application/json")
def set_address(request):
try:
session_id = request.session['session_id']
except:
res = {'error': 1, 'message': 'no session id'}
return HttpResponse(json.dumps(res), content_type="application/json")
address = request.GET.get('address') # TODO: Switch to post, GET only for testing
print request
print address
res = scripts.set_address(session_id, address)
return HttpResponse(json.dumps(res), content_type="application/json")
def notes_reader(request):
pass
def check_notes_reader_status(request):
session_id = request.session['session_id']
try:
transaction_status = scripts.check_transaction_status(session_id)
return HttpResponse(json.dumps(transaction_status), content_type="application/json")
except Transactions.DoesNotExist:
log_error('check_notes_reader_status', 'transaction does not exists', session_id=session_id)
raise
except:
exc_info = sys.exc_info()
message = str(exc_info[0]) + ' - ' + str(exc_info[1])
log_error('check_notes_reader_status', message, session_id=session_id)
raise
def confirm_payment(request):
try:
res = {}
session_id = request.session['session_id']
if not session_id:
res['message'] = 'Invalid session id'
if request.method == 'POST':
#notes_reader_command_message_queue.put(True)
time.sleep(2)
notes_reader_status = {}
transaction = Transactions.objects.get(session_id=session_id)
notes_reader_status['notes_inserted'] = transaction.cash_amount
notes_reader_status['btc_amount'] = transaction.btc_amount
tx_result = scripts.broadcast_transaction(session_id)
res = notes_reader_status
else:
return HttpResponseServerError(json.dumps({'error': "can't broadcast transaction - invalid http method"}), content_type="application/json")
return HttpResponse(json.dumps(res), content_type="application/json")
except Transactions.DoesNotExist:
log_error('confirm_payment', 'transaction does not exists', session_id=session_id)
except:
exc_info = sys.exc_info()
message = str(exc_info[0]) + ' - ' + str(exc_info[1])
log_error('confirm_payment', message, session_id=session_id)
return HttpResponseServerError(json.dumps({'error': "can't broadcast transaction"}), content_type="application/json")
def wallet(request):
btcp = BTCProcessor(True)
b = btcp.check_balance()
balance = str(to_btc(b[0])) + ' ' + str(to_btc(b[1]))
wallet_status = {}
wallet_status['balance'] = balance
wallet_status['addresses'] = btcp.wallet.addresses()
return HttpResponse(json.dumps(wallet_status), content_type="application/json")
def test(request):
#FIXME what's this ?
btcp = BTCProcessor(True)
t = btcp.broadcast_transaction('1GEQsEtzeUJHVNWR9xt24RMXu676rxGhf5',0.0003)
return HttpResponse(json.dumps(t), content_type="application/json") | gpl-2.0 |
temnoregg/qore | lib/QoreRemoveOperatorNode.cpp | 2717 | /*
QoreRemoveOperatorNode.cpp
Qore Programming Language
Copyright (C) 2003 - 2015 David Nichols
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.
Note that the Qore library is released under a choice of three open-source
licenses: MIT (as above), LGPL 2+, or GPL 2+; see README-LICENSE for more
information.
*/
#include <qore/Qore.h>
QoreString QoreRemoveOperatorNode::remove_str("remove operator expression");
// if del is true, then the returned QoreString * should be removed, if false, then it must not be
QoreString *QoreRemoveOperatorNode::getAsString(bool &del, int foff, ExceptionSink *xsink) const {
del = false;
return &remove_str;
}
int QoreRemoveOperatorNode::getAsString(QoreString &str, int foff, ExceptionSink *xsink) const {
str.concat(&remove_str);
return 0;
}
QoreValue QoreRemoveOperatorNode::evalValueImpl(bool& needs_deref, ExceptionSink *xsink) const {
LValueRemoveHelper lvrh(exp, xsink, false);
if (!lvrh)
return QoreValue();
return lvrh.remove();
}
AbstractQoreNode *QoreRemoveOperatorNode::parseInitImpl(LocalVar *oflag, int pflag, int &lvids, const QoreTypeInfo *&typeInfo) {
assert(!typeInfo);
if (exp) {
exp = exp->parseInit(oflag, pflag, lvids, typeInfo);
if (exp && check_lvalue(exp))
parse_error("the remove operator expects an lvalue as its operand, got '%s' instead", exp->getTypeName());
returnTypeInfo = typeInfo;
}
return this;
}
QoreRemoveOperatorNode* QoreRemoveOperatorNode::copyBackground(ExceptionSink* xsink) const {
ReferenceHolder<> n_exp(copy_and_resolve_lvar_refs(exp, xsink), xsink);
if (*xsink)
return 0;
return new QoreRemoveOperatorNode(n_exp.release());
}
| gpl-2.0 |
gsnarawat/mywp | wp-content/plugins/Signup/admin/signup-admin.php | 693 | <?php require_once('/../myplugin.php');
require('D:/xampp/htdocs/new/wp-load.php');
add_action( 'admin_menu', 'register_my_custom_menu_page' );
function register_my_custom_menu_page(){
add_menu_page( 'custom menu title', 'Myplugin', 'manage_options', 'custompage', 'my_custom_menu_page');
}
function my_custom_menu_page(){
$url = plugins_url();?>
<form action="<?php echo $url?>/myplugin/myplugin.php" method="get">
<h1>Myplugin</h1>
<table>
<tr>
<td>No of post to show :</td><td><input type="text" name="noofpost"/></td></tr>
<tr><td></td><td><input type="submit" name="noof" value="Save" /></td></tr>
</table></form>
<?php }
?>
| gpl-2.0 |
Jacy-Wang/MyLeetCode | Triangle120.java | 1250 | public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[] prevMin = new int[n];
int[] curMin = new int[n];
prevMin[0] = triangle.get(0).get(0);
findMin(triangle, n, 1, prevMin, curMin);
int minimum = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (prevMin[i] < minimum) {
minimum = prevMin[i];
}
}
return minimum;
}
private void findMin(List<List<Integer>> triangle, int n, int level, int[] prevMin, int[] curMin) {
if (level < n) {
List<Integer> arr = triangle.get(level);
for (int i = 0; i < arr.size(); i++) {
if (i == 0) {
curMin[i] = prevMin[i] + arr.get(i);
} else if (i == arr.size() - 1) {
curMin[i] = prevMin[i - 1] + arr.get(i);
} else {
curMin[i] = Math.min(prevMin[i - 1], prevMin[i]) + arr.get(i);
}
}
for (int i = 0; i < level + 1; i++) {
prevMin[i] = curMin[i];
}
findMin(triangle, n, level + 1, prevMin, curMin);
}
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/FusedMultiplyAddNode.java | 5585 | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.replacements.nodes;
import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_2;
import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
import org.graalvm.compiler.core.common.type.FloatStamp;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.core.common.type.StampFactory;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.graph.spi.CanonicalizerTool;
import org.graalvm.compiler.lir.gen.ArithmeticLIRGeneratorTool;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.NodeView;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.calc.TernaryNode;
import org.graalvm.compiler.nodes.spi.ArithmeticLIRLowerable;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import org.graalvm.compiler.serviceprovider.GraalServices;
@NodeInfo(cycles = CYCLES_2, size = SIZE_1)
public final class FusedMultiplyAddNode extends TernaryNode implements ArithmeticLIRLowerable {
public static final NodeClass<FusedMultiplyAddNode> TYPE = NodeClass.create(FusedMultiplyAddNode.class);
public FusedMultiplyAddNode(ValueNode x, ValueNode y, ValueNode z) {
super(TYPE, computeStamp(x.stamp(NodeView.DEFAULT), y.stamp(NodeView.DEFAULT), z.stamp(NodeView.DEFAULT)), x, y, z);
assert x.getStackKind().isNumericFloat();
assert y.getStackKind().isNumericFloat();
assert z.getStackKind().isNumericFloat();
}
@Override
public Stamp foldStamp(Stamp stampX, Stamp stampY, Stamp stampZ) {
return computeStamp(stampX, stampY, stampZ);
}
private static Stamp computeStamp(Stamp stampX, Stamp stampY, Stamp stampZ) {
if (stampX.isEmpty()) {
return stampX;
}
if (stampY.isEmpty()) {
return stampY;
}
if (stampZ.isEmpty()) {
return stampZ;
}
JavaConstant constantX = ((FloatStamp) stampX).asConstant();
JavaConstant constantY = ((FloatStamp) stampY).asConstant();
JavaConstant constantZ = ((FloatStamp) stampZ).asConstant();
if (constantX != null && constantY != null && constantZ != null) {
if (stampX.getStackKind() == JavaKind.Float) {
float result = GraalServices.fma(constantX.asFloat(), constantY.asFloat(), constantZ.asFloat());
if (Float.isNaN(result)) {
return StampFactory.forFloat(JavaKind.Float, Double.NaN, Double.NaN, false);
} else {
return StampFactory.forFloat(JavaKind.Float, result, result, true);
}
} else {
double result = GraalServices.fma(constantX.asDouble(), constantY.asDouble(), constantZ.asDouble());
assert stampX.getStackKind() == JavaKind.Double;
if (Double.isNaN(result)) {
return StampFactory.forFloat(JavaKind.Double, Double.NaN, Double.NaN, false);
} else {
return StampFactory.forFloat(JavaKind.Double, result, result, true);
}
}
}
return stampX.unrestricted();
}
@Override
public ValueNode canonical(CanonicalizerTool tool, ValueNode forX, ValueNode forY, ValueNode forZ) {
if (forX.isConstant() && forY.isConstant() && forZ.isConstant()) {
JavaConstant constantX = forX.asJavaConstant();
JavaConstant constantY = forY.asJavaConstant();
JavaConstant constantZ = forZ.asJavaConstant();
if (forX.getStackKind() == JavaKind.Float) {
return ConstantNode.forFloat(GraalServices.fma(constantX.asFloat(), constantY.asFloat(), constantZ.asFloat()));
} else {
assert forX.getStackKind() == JavaKind.Double;
return ConstantNode.forDouble(GraalServices.fma(constantX.asDouble(), constantY.asDouble(), constantZ.asDouble()));
}
}
return this;
}
@Override
public void generate(NodeLIRBuilderTool builder, ArithmeticLIRGeneratorTool gen) {
builder.setResult(this, gen.emitFusedMultiplyAdd(builder.operand(getX()), builder.operand(getY()), builder.operand(getZ())));
}
}
| gpl-2.0 |
hackathon-2014/awesomesauce-repo | backend/config/routes.rb | 2076 | Rails.application.routes.draw do
devise_for :users, :controllers => { omniauth_callbacks: 'omniauth_callbacks' }
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'welcome#index'
resources :favorite_lists do
end
resources :spells do
member do
post :cast_spell
end
end
resources :users do
end
resources :battles do
member do
get :challenged
get :playing
get :finished
put :update_battle
get :get_challenge_data
post :end_battle
end
collection do
post :detect_challenge
end
end
# Example of regular route:
post '/create_user' => 'users#create'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| gpl-2.0 |
scerbo/Signature-Site | wp-content/plugins/simple-real-estate-pack-4/includes/srp-AffordabilityResult.php | 6658 | <?php
$output = false;
if($_GET['type'] == 'affordability'){
// Get Posted Values
$mo_gross_income = $_GET['mo_gross_income'];
$mo_debt_expences = $_GET['mo_debt_expences'];
$down_payment = $_GET['down_payment'];
$annual_interest_rate = $_GET['interest_rate'];
$front_end_ratio_payment = $mo_gross_income * 0.28;
$funds_available = $mo_gross_income*0.36 - $mo_debt_expences;
$percentage_available = number_format(($funds_available*100/$mo_gross_income), 2);
$back_end_ratio_payment = $mo_gross_income * 0.36;
$home_insurance = 0.5; //0.5%
$property_tax = 1; //1%
$pmi = 0;
//finding out which is smalle $back_end_ratio_payment or $funds_available
if($front_end_ratio_payment < $funds_available){
$smaller = $front_end_ratio_payment;
}else{
$smaller = $funds_available;
}
$monthly_interest_rate = $annual_interest_rate/100/12;
$month_term = 360;
$power = -($month_term);
$denom = pow((1 + $monthly_interest_rate), $power);
$a = $monthly_interest_rate / (1 - $denom);
$b = ($home_insurance + $property_tax)/100 / 12;
$principal = ($smaller / ($a + $b)) + $down_payment;
if($down_payment > 0){
$principal = ($smaller - $down_payment*$b) / ($a + $b);
}
//Home insurance, Tax and PMI + Principal = 100%, then $principal_ = X%+(Hi+Tx+PMI)% = 100%
$dp_percent = $down_payment * 100 / ($principal + $down_payment);
$deductions = 'Less: taxes and insurance*';
if($dp_percent < 20){
$pmi = 0.5;
$x = $home_insurance + $property_tax + $pmi;
$b = $x/100/12;
$principal = ($smaller - $down_payment*$b) / ($a + $b);
$deductions = 'Less: taxes, insurance and PMI<sup>[2]</sup>';
}
$total_amount = $principal + $down_payment;
$monthly_tax_insurance = $total_amount * ($home_insurance + $property_tax + $pmi)/100/12;
$deductions_ = '<hr />
<div><small>
<sup>[1]</sup> Calculations are based on the following estimate values:
<ul>
<li>Annual Property Tax - '.$property_tax.'% [$'. number_format($property_tax/100*$total_amount) .'/yr. or $'. number_format($property_tax/100*$total_amount/12) .'/mo]</li>
<li>Annual Home Insurance - '.$home_insurance.'% [$'. number_format($home_insurance/100*$total_amount) .'/yr. or $'. number_format($home_insurance/100*$total_amount/12) .']</li>';
if($pmi > 0){ $deductions_ .= '<li>Premium Mortgage Insurance - '.$pmi.'% [$'. number_format($pmi/100*$total_amount) .'/yr. or $'. number_format($pmi/100*$total_amount/12) .'/mo.]</li>'; }
$deductions_ .= '</ul> ';
if($pmi > 0){ $deductions_ .= '<sup>[2]</sup> PMI (Premium Mortgage Insurance) only being calculated when the down payment is less than 20% of the price of the property.'; }
$deductions_ .= '</small></div>';
if($down_payment > 0){
$dp = 'your total mortgage amount equals $'.number_format($principal).', plus your downpayment $'.number_format($down_payment) .' brings your home affordability up to $'.number_format($principal+$down_payment).'.';
}else{
$dp = 'your total mortgage amount (and home affordability) equals $'.number_format($principal).'.';
}
$table = array(
'Front-End Ratio (28%)' => array(
'Monthly gross income' => '$'.number_format($mo_gross_income),
'Front-End Ratio' => '28%',
'Calculated payment for front-end ratio' => '$'.number_format($front_end_ratio_payment),
'Explanation' => 'Your total monthly housing allowance should not ecceed 28% of your gross income, or $'.number_format($front_end_ratio_payment) . ' per month.',
),
'Back-End Ratio (36%)' => array(
'Debt and obligations' => '$'.number_format($mo_debt_expences),
'Percent of gross income' => number_format(($mo_debt_expences/$mo_gross_income*100), 2) . '%',
'Maximum percentage available for mortgage payment' => $percentage_available . '%',
'Calculated payment for back-end ratio' => '$'.number_format($funds_available),
'Explanation' => '36% of your total income is '. '$'.number_format($back_end_ratio_payment) .', minus your monthly debt ('. '$'.number_format($mo_debt_expences) .'), equals '. '$'.number_format($funds_available) .' for your housing allowance, including insurance and taxes.',
),
'Payment Calculation' => array(
'Smaller of the two ratio options' => '$'.number_format($smaller),
$deductions => '$'.number_format($monthly_tax_insurance).'<sup>[1]</sup>',
'Equals: maximum allowable payment' => '$'.number_format($smaller - $monthly_tax_insurance),
'Calculated mortgage amount' => '$'.number_format($principal),
'Down payment' => '$'.number_format($down_payment), //Get value
'Explanation' => 'Smaller amount of the two ratios ('.'$'.number_format($smaller).') minus property tax & home insurance ($'.number_format($monthly_tax_insurance).') comes to $'.number_format($smaller - $monthly_tax_insurance) .' funds available for principal and interest. Based on this, '. $dp,
),
'Home value you should be able to afford' => '$'.number_format($principal+$down_payment),
);
$tr = '';
$i = 0;
foreach($table as $k => $row){
if(is_array($row)){
$tr .= '<tr class="srp_subtitle">
<td colspan="2">'.$k.'</td>
</tr>';
foreach($row as $name => $value){
if($name == 'Explanation'){
$tr .= '<tr>
<td colspan="2"><div class="srp_additional-info"><small><strong>'.$name.':</strong> '.$value.'</small></div></td>
</tr>';
}else{
$tr .= '<tr>
<td>'.$name.':</td>
<td>'.$value.'</td>
</tr>';
}
}
}else{
$tr .= '<tr class="srp_subtitle">
<td>'.$k.':</td>
<td>'.$table[$k].'</td>
</tr>';
}
$i++;
}
$output .= '<h3>Here is what you should be able to afford based on the data you provided:</h3>';
$output .= '<p>Usually lenders will cap monthly housing allowance (including taxes and insurance) by lesser of the two ratios: 28% (from your gross income) and 36% (from your gross income including other monthly debt and payment obligations).<p>';
$output .= '<table class="srp_result_table">'.$tr.'</table>';
$output .= $deductions_;
$output .= '<p><small>Disclaimer: the calculations are estimated and can only be used as guidance. For specific information contact your real estate agent or lending company.</small></p>';
}
function get_interest_factor($year_term, $monthly_interest_rate) {
global $base_rate;
$factor = 0;
$base_rate = 1 + $monthly_interest_rate;
$denominator = $base_rate;
for ($i=0; $i < ($year_term * 12); $i++) {
$factor += (1 / $denominator);
$denominator *= $base_rate;
}
return $factor;
}
print $output;
?> | gpl-2.0 |
hostianer/HostiBootstrap | Themes/Frontend/HostiBootstrap/frontend/_public/src/js/shopware/jquery.shipping-payment.js | 1740 | ;(function($) {
'use strict';
$.plugin('shippingPayment', {
defaults: {
formSelector: '#shippingPaymentForm',
radioSelector: 'input.auto_submit[type=radio]',
submitSelector: 'input[type=submit]'
},
/**
* Plugin constructor.
*/
init: function () {
var me = this;
me.applyDataAttributes();
me.registerEvents();
},
/**
* Registers all necessary event listener.
*/
registerEvents: function () {
var me = this;
me.$el.on('change', me.opts.radioSelector, $.proxy(me.onInputChanged, me));
},
/**
* Called on change event of the radio fields.
*/
onInputChanged: function () {
var me = this,
form = me.$el.find(me.opts.formSelector),
url = form.attr('action'),
data = form.serialize() + '&isXHR=1';
$.loadingIndicator.open();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(res) {
me.$el.empty().html(res);
me.$el.find('input[type="submit"][form], button[form]').formPolyfill();
$.loadingIndicator.close();
window.picturefill();
}
})
},
/**
* Destroy method of the plugin.
* Removes attached event listener.
*/
destroy: function() {
var me = this;
me.$el.off('change', me.opts.radioSelector);
me._destroy();
}
});
})(jQuery);
| gpl-2.0 |
evertonts/delivery | db/migrate/20140927023940_create_routes.rb | 275 | class CreateRoutes < ActiveRecord::Migration
def change
create_table :routes do |t|
t.string :source, limit: 16
t.string :destination, limit: 16
t.decimal :distance, scale: 3, precision: 10
t.references :map
t.timestamps
end
end
end
| gpl-2.0 |
joshuacoddingyou/php | core/classes/utils/datavalidator/usstate.php | 4411 | <?php
/* Copyright [2011, 2012, 2013] da Universidade Federal de Juiz de Fora
* Este arquivo é parte do programa Framework Maestro.
* O Framework Maestro é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada
* pela Fundação do Software Livre (FSF); na versão 2 da Licença.
* Este programa é distribuído na esperança que possa ser útil,
* mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer
* MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL
* em português para maiores detalhes.
* Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
* "LICENCA.txt", junto com este programa, se não, acesse o Portal do Software
* Público Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a
* Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* $Id: Usstate.php 7490 2010-03-29 19:53:27Z jwage $
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Validator_Usstate
*
* @package Doctrine
* @subpackage Validator
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 1.0
* @version $Revision: 7490 $
* @author Konsta Vesterinen <[email protected]>
*/
class Doctrine_Validator_Usstate extends Doctrine_Validator_Driver
{
private static $states = array(
'AK' => true,
'AL' => true,
'AR' => true,
'AZ' => true,
'CA' => true,
'CO' => true,
'CT' => true,
'DC' => true,
'DE' => true,
'FL' => true,
'GA' => true,
'HI' => true,
'IA' => true,
'ID' => true,
'IL' => true,
'IN' => true,
'KS' => true,
'KY' => true,
'LA' => true,
'MA' => true,
'MD' => true,
'ME' => true,
'MI' => true,
'MN' => true,
'MO' => true,
'MS' => true,
'MT' => true,
'NC' => true,
'ND' => true,
'NE' => true,
'NH' => true,
'NJ' => true,
'NM' => true,
'NV' => true,
'NY' => true,
'OH' => true,
'OK' => true,
'OR' => true,
'PA' => true,
'PR' => true,
'RI' => true,
'SC' => true,
'SD' => true,
'TN' => true,
'TX' => true,
'UT' => true,
'VA' => true,
'VI' => true,
'VT' => true,
'WA' => true,
'WI' => true,
'WV' => true,
'WY' => true
);
public function getStates()
{
return self::$states;
}
/**
* checks if given value is a valid US state code
*
* @param string $args
* @return boolean
*/
public function validate($value)
{
if (is_null($value)) {
return true;
}
return isset(self::$states[$value]);
}
} | gpl-2.0 |
Onirik79/aaritmud | src/mob.py | 33924 | # -*- coding: utf-8 -*-
"""
Modulo per la gestione generica dei Mob, base anche della classe Player.
"""
#= IMPORT ======================================================================
import math
import random
from src.affect import is_affected
from src.behaviour import BehaviourUpdaterSuperclass
from src.calendar import calendar
from src.config import config
from src.color import remove_colors
from src.database import database
from src.entity import ProtoEntity, create_random_entity
from src.element import Element
from src.engine import engine
from src.enums import (COLOR, CONSTELLATION, DAMAGE, DIR, AFFECT, FLAG,
HAND, HAIRTYPE, LANGUAGE, MONTH, PART, POSITION,
RACE, SEX, STYLE, TO, TRUST, VIRTUE, WAY)
from src.gamescript import check_trigger
from src.log import log
from src.name import create_random_name
from src.utility import copy_existing_attributes
#= COSTANTI ====================================================================
# (TD) probabilmente queste bisognerà spostarle lato enumerazione CONDITION
LIGHT_CONDITION = 16
MEDIUM_CONDITION = 8
SERIOUS_CONDITION = 0
MAX_CONDITION = 100
#= CLASSI ======================================================================
class ProtoMob(ProtoEntity):
"""
Classe che gestisce il prototipo di un Mob.
"""
PRIMARY_KEY = "code"
VOLATILES = ProtoEntity.VOLATILES + []
MULTILINES = ProtoEntity.MULTILINES + []
SCHEMA = {"behaviour" : ("src.behaviour", "MobBehaviour"),
"height" : ("", "measure")}
SCHEMA.update(ProtoEntity.SCHEMA)
REFERENCES = {}
REFERENCES.update(ProtoEntity.REFERENCES)
WEAKREFS = {}
WEAKREFS.update(ProtoEntity.WEAKREFS)
IS_AREA = False
IS_DESCR = True
IS_ROOM = False
IS_EXIT = False
IS_WALL = False
IS_ACTOR = True
IS_MOB = True
IS_ITEM = False
IS_PLAYER = False
IS_EXTRA = False
IS_PROTO = True
ACCESS_ATTR = "proto_mobs"
CONSTRUCTOR = None # Classe Mob una volta che viene definita a fine modulo
def __init__(self, code=""):
super(ProtoMob, self).__init__()
self.code = code or ""
self.height = 0
self.constellation = Element(CONSTELLATION.NONE) # Costellazione sotto cui è nato il mob
self.virtue = Element(VIRTUE.NONE) # Virtù che il mob segue principalmente
self.hand = Element(HAND.NONE) # Indica quale mano utilizza preferibilmente
self.hometown = "" # Area che il mob o il pg considera come propria casa
self.group_name = "" # Nome del gruppo in cui fa parte, fanno parte tutti i mob che lo hanno uguale
self.voice_emote = "" # Stringa che ne descrive la voce nel canale rpg_channel()
self.voice_potence = 50 # Potenza della voce, 0 o meno significa aver perso la voce, per razze umanoidi i valori sono da 40 a 80, per razze 'minori' o 'maggiori' i valori possono variare e superare anche il 100
self.parts = {} # Forma, materiale, vita, flags delle parti sono già di default a seconda delle razza, però si possono cambiare anche a livello di file di area
self.morph = None # Tipo di morph sotto cui il personaggio è affetto
self.skill_messages = {} # Dizionario dei messaggi personalizzati riguardanti le skill
# Attributi
self.strength = 0
self.endurance = 0
self.agility = 0
self.speed = 0
self.intelligence = 0
self.willpower = 0
self.personality = 0
self.luck = 0
# Condizioni
self.thirst = 0
self.hunger = 0
self.sleep = 0
self.drunkness = 0
self.adrenaline = 0
self.mind = 0 # Tale quale a quello dello smaug
self.emotion = 0 # Tale quale a quello dello smaug
self.bloodthirst = 0
self.eye_color = Element(COLOR.NONE)
self.hair_color = Element(COLOR.NONE)
self.hair_length = 0
self.hair_type = Element(HAIRTYPE.NONE)
self.skin_color = Element(COLOR.NONE)
#- Fine Inizializzazione -
def get_error_message(self):
msg = super(ProtoMob, self).get_error_message()
if msg:
pass
elif self.IS_MOB and "_mob_" not in self.code:
msg = "code di mob senza l'identificativo _mob_ al suo interno"
elif self.race.get_error_message(RACE, "race", allow_none=False) != "":
return self.race.get_error_message(RACE, "race", allow_none=False)
elif self.birth_day <= 0 or self.birth_day > config.days_in_month:
return "birth_day errato: %d" % self.birth_day
elif self.birth_month.get_error_message(MONTH, "birth_month") != "":
return self.birth_month.get_error_message(MONTH, "birth_month")
elif self.age < 0:
return "age minore di zero: %d" % self.age
elif self.height <= 0:
msg = "altezza minore o uguale a zero: %s" % self.height
elif self.constellation.get_error_message(CONSTELLATION, "constellation") != "":
msg = self.constellation.get_error_message(CONSTELLATION, "constellation")
elif self.virtue.get_error_message(VIRTUE, "virtue") != "":
msg = self.virtue.get_error_message(VIRTUE, "virtue")
elif self.hometown and self.hometown not in database["areas"]:
msg = "hometown inesistente tra i codici delle aree: %s" % self.hometown
elif self.group_name and self.group_name not in database["groups"]:
msg = "group_name inesistente tra i nomi dei gruppi: %s" % self.group_name
elif self.strength <= 0 or self.strength > config.max_stat_value:
msg = "strength non è tra zero e %d: %d" % (config.max_stat_value, self.strength)
elif self.endurance <= 0 or self.endurance > config.max_stat_value:
msg = "endurance non è tra zero e %d: %d" % (config.max_stat_value, self.endurance)
elif self.agility <= 0 or self.agility > config.max_stat_value:
msg = "agility non è tra zero e %d: %d" % (config.max_stat_value, self.agility)
elif self.speed <= 0 or self.speed > config.max_stat_value:
msg = "speed non è tra zero e %d: %d" % (config.max_stat_value, self.speed)
elif self.intelligence <= 0 or self.intelligence > config.max_stat_value:
msg = "intelligence non è tra zero e %d: %d" % (config.max_stat_value, self.intelligence)
elif self.willpower <= 0 or self.willpower > config.max_stat_value:
msg = "willpower non è tra zero e %d: %d" % (config.max_stat_value, self.willpower)
elif self.personality <= 0 or self.personality > config.max_stat_value:
msg = "personality non è tra zero e %d: %d" % (config.max_stat_value, self.personality)
elif self.luck <= 0 or self.luck > config.max_stat_value:
msg = "luck non è tra zero e %d: %d" % (config.max_stat_value, self.luck)
elif self.voice_potence < 0:
msg = "voice_potence non può essere minore di zero: %s" % self.voice_potence
# (TD) ricordarsi di aggiungere il controllo alle parts
else:
return ""
if type(self) == ProtoMob:
log.bug("(ProtoMob: code %s) %s" % (self.code, msg))
return msg
#- Fine Metodo -
def get_area_code(self):
"""
Ritorna il codice dell'area carpendolo dal proprio codice.
"""
if "_mob_" in self.code:
return self.code.split("_mob_", 1)[0]
else:
log.bug("Codice errato per l'entità %s: %s" % (self.__class__.__name__, self.code))
return ""
#- Fine Metodo -
class Mob(ProtoMob, BehaviourUpdaterSuperclass):
"""
Istanza di un Mob.
"""
PRIMARY_KEY = "code"
VOLATILES = ProtoMob.VOLATILES + ["prototype"]
MULTILINES = ProtoMob.MULTILINES + []
SCHEMA = {"specials" : ("", "str")}
SCHEMA.update(ProtoMob.SCHEMA)
REFERENCES = {"area" : ["areas"]}
REFERENCES.update(ProtoMob.REFERENCES)
WEAKREFS = {}
WEAKREFS.update(ProtoMob.WEAKREFS)
ACCESS_ATTR = "mobs"
IS_PROTO = False
CONSTRUCTOR = None # Classe Mob una volta che viene definita a fine modulo
# Qui non bisogna passare altri attributi oltre il code, perché altrimenti
# offuscherebbero gli attributi prototype
def __init__(self, code=""):
super(Mob, self).__init__()
BehaviourUpdaterSuperclass.__init__(self)
self.code = ""
self.prototype = None
if code:
self.reinit_code(code)
copy_existing_attributes(self.prototype, self, except_these_attrs=["code"])
self.after_copy_existing_attributes()
# Eventuale inizializzazione dei punti
if self.max_life == 0:
self.max_life = config.starting_points
if self.max_mana == 0:
self.max_mana = config.starting_points
if self.max_vigour == 0:
self.max_vigour = config.starting_points
if self.life == 0:
self.life = self.max_life
if self.mana == 0:
self.mana = self.max_mana
if self.vigour == 0:
self.vigour = self.max_vigour
if self.hand == HAND.NONE:
self.hand = self.hand.randomize()
# Variabili proprie di una istanza di mob:
self.area = None
self.attack = 1
self.defense = 1
self.speaking = Element(LANGUAGE.COMMON) # Indica con quale linguaggio sta attualmente parlando il mob
self.style = Element(STYLE.NONE) # Style di combattimento che sta utilizzando
self.experience = 0 # Esperienza accumulata prima di poter livellare
self.mount = None # Indica quale mob o pg sta cavalcando
self.mounted_by = None # Indica da quali mob o pg è cavalcato
self.specials = {} # E' una lista di variabili speciali, possono essere utilizzate come delle flags, vengono aggiunte di solito nei gamescript
self.reply = None # Entità a cui si può replicare
# self.tracking = Track() # Serve quando il mob inizia a tracciare e cacciare una preda fuggita
self.last_fight_time = None
self.last_death_time = None
# Contatori di statistica
self.defeat_from_mob_counter = 0 # Conteggio delle sconfitte
self.defeat_from_item_counter = 0 # Conteggio delle sconfitte
self.defeat_from_player_counter = 0 # Conteggio delle sconfitte
self.death_from_player_counter = 0 # Conteggio delle sconfitte
self.mob_defeated_counter = 0 # Conteggio delle vittorie sui mob
self.item_defeated_counter = 0 # Conteggio degli oggetti distrutti
self.player_defeated_counter = 0 # Conteggio delle vittorie sui giocatori
self.player_killed_counter = 0 # Conteggio delle volte che viene ucciso un giocatore
check_trigger(self, "on_init", self)
#- Fine Inizializzazione -
def get_error_message(self):
msg = super(Mob, self).get_error_message()
if msg:
pass
elif self.life < 0 or self.life > 9999:
msg = "life non è tra zero e 9999: %d" % self.life
elif self.mana < 0 or self.mana > 9999:
msg = "mana non è tra zero e 9999: %d" % self.mana
elif self.vigour < 0 or self.vigour > 9999:
msg = "vigour non è tra zero e 9999: %d" % self.vigour
elif self.max_life < 0 or self.max_life > 9999:
msg = "life non è tra zero e 9999: %d" % self.max_life
elif self.max_mana < 0 or self.max_mana > 9999:
msg = "mana non è tra zero e 9999: %d" % self.max_mana
elif self.max_vigour < 0 or self.max_vigour > 9999:
msg = "vigour non è tra zero e 9999: %d" % self.max_vigour
elif self.thirst < 0 or self.thirst > MAX_CONDITION:
msg = "thirst non è tra zero e %s: %d" % (MAX_CONDITION, self.thirst)
elif self.hunger < 0 or self.hunger > MAX_CONDITION:
msg = "hunger non è tra zero e %s: %d" % (MAX_CONDITION, self.hunger)
elif self.drunkness < 0 or self.drunkness > MAX_CONDITION:
msg = "drunkness è tra 0 e %d: %d" % (MAX_CONDITION, self.drunkness)
elif self.bloodthirst < 0 or self.bloodthirst > MAX_CONDITION:
msg = "bloodthirst non è tra zero e %d: %d" % (MAX_CONDITION, self.bloodthirst)
elif self.adrenaline < 0 or self.adrenaline > MAX_CONDITION:
msg = "adrenaline non è tra zero e %d: %d" % (MAX_CONDITION, self.adrenaline)
elif self.mind < 0 or self.mind > MAX_CONDITION:
msg = "mind non è tra zero e %d: %d" % (MAX_CONDITION, self.mind)
elif self.emotion < 0 or self.emotion > MAX_CONDITION:
msg = "emotion non è tra zero e %d: %d" % (MAX_CONDITION, self.emotion)
elif self.attack < 1:
msg = "attack minore di 1: %d" % self.attack
elif self.defense < 1:
msg = "defense minore di 1: %d" % self.defense
elif self.speaking.get_error_message(LANGUAGE, "speaking") != "":
msg = self.speaking.get_error_message(LANGUAGE, "speaking")
elif self.defeat_from_mob_counter < 0:
msg = "defeat_from_mob_counter è un contatore, non può essere minore di 0: %d" % self.defeat_from_mob_counter
elif self.defeat_from_item_counter < 0:
msg = "defeat_from_item_counter è un contatore, non può essere minore di 0: %d" % self.defeat_from_item_counter
elif self.defeat_from_player_counter < 0:
msg = "defeat_from_player_counter è un contatore, non può essere minore di 0: %d" % self.defeat_from_player_counter
elif self.death_from_player_counter < 0:
msg = "death_from_player_counter è un contatore, non può essere minore di 0: %d" % self.death_from_player_counter
elif self.mob_defeated_counter < 0:
msg = "mob_defeated_counter è un contatore, non può essere minore di 0: %d" % self.mob_defeated_counter
elif self.item_defeated_counter < 0:
msg = "item_defeated_counter è un contatore, non può essere minore di 0: %d" % self.item_defeated_counter
elif self.player_defeated_counter < 0:
msg = "player_defeated_counter è un contatore, non può essere minore di 0: %d" % self.player_defeated_counter
elif self.player_killed_counter < 0:
msg = "player_killed_counter è un contatore, non può essere minore di 0: %d" % self.player_killed_counter
elif self.style.get_error_message(STYLE, "style") != "":
msg = self.style.get_error_message(STYLE, "style")
elif self.mount and self.mount not in database.players and self.mount not in self.mobs:
msg = "mount non è un player o un mob valido: %s" % self.mount
elif self.mounted_by and self.mount not in database.players and self.mount not in self.mobs:
msg = "mounted_by non è un player o un mob valido: %s" % self.mounted_by
elif self.reply and self.reply not in database.players and self.reply not in database.mobs and self.reply not in database.items:
msg = "reply non è un entità valida: %s" % self.reply
# elif self.tracking.get_error_message() != "":
# msg = self.tracking.get_error_message()
else:
return ""
# Se arriva fino a qui ha trovato un errore
if type(self) == Mob:
log.bug("(Mob: code %s) %s" % (self.code, msg))
return msg
#- Fine Metodo -
# -------------------------------------------------------------------------
def get_strength_way(self):
"""
Ritorna quale via l'actor sta seguendo, a seconda delle skill che
conosce.
"""
# (TD)
return WAY.GLADIATOR
#- Fine Metodo -
def get_weak_way(self):
"""
Ritorna quale via l'actor non sta seguendo, a seconda delle skill che
conosce.
"""
# (TD)
return WAY.RUNIC
#- Fine Metodo -
def has_sight_sense(self):
"""
Ritorna falso se il mob è cieco, di solito si utilizza questo metodo
al posto della sintassi normale con l'operatore in per controllare
un'entità non ci può vedere anche magicamente.
Concettualmente sarebbe il contrario della funzione is_blind definita
in molti Diku-like.
"""
if self.trust >= TRUST.MASTER:
return True
if is_affected(self, "truesight"):
return True
if is_affected(self, "blind"):
return False
return True
#- Fine Metodo -
def has_hearing_sense(self):
"""
Ritorna vero se l'entità è sorda.
"""
# (TD)
return True
#- Fine Metodo -
def has_smell_sense(self):
"""
Ritorna vero se l'entità non è il possesso del senso dell'olfatto.
"""
# (TD)
return True
#- Fine Metodo -
def has_touch_sense(self):
"""
Ritorna vero se l'entità non è il possesso della sensibilità del tocco.
"""
# (TD)
return True
#- Fine Metodo -
def has_taste_sense(self):
"""
Ritorna vero se l'entità non è il possesso del senso del gusto.
"""
# (TD)
return True
#- Fine Metodo -
def has_sixth_sense(self):
"""
Ritorna vero se l'entità non è il possesso di intuito, o sesto senso.
"""
# (TD)
return True
#- Fine Metodo -
# -------------------------------------------------------------------------
def is_drunk(self, difficulty=1):
"""
Esegue una specie di tiro di salvezza per vedere se l'entità è ubriaca
o meno.
L'argomento difficulty può essere un numero variabile ad indicare la
difficoltà del controllo, maggiore è difficulty più probabile è che
l'entità sia considerata ubriaca.
"""
if difficulty <= 0 or difficulty > 10:
log.bug("difficulty non è valido: %d" % difficulty)
return False
# ---------------------------------------------------------------------
if random.randint(1, 100) < self.drunkness * difficulty:
return True
return False
#- Fine Metodo -
def has_drunk_walking(self):
"""
Ritorna una coppia di valori, il primo indica se il mob ha l'andatura
da ubriaco, il secondo indica se la propria cavalcatura ha l'andatura
da ubriaco (sempre che il mob abbia una cavalcatura).
"""
drunk = False
mount_drunk = False
if self.is_drunk() and self.position != POSITION.SHOVE and self.position != POSITION.DRAG:
drunk = True
if (self.mount and self.mount.is_drunk()
and self.mount.position != POSITION.SHOVE and self.mount.position != POSITION.DRAG):
mount_drunk = True
return drunk, mount_drunk
#- Fine Metodo -
# (TD) skill per guadagnare più punti
def update_points(self):
# Recupero dei punti base
# (bb) attenzione che questo dies potrebbe conflittare con quello del
# ciclo di loop di fight, da rivedere
if self.life <= 0:
self.dies()
elif self.life < self.max_life:
self.gain_points("life")
if self.mana < self.max_mana:
self.gain_points("mana")
if self.vigour < self.max_vigour:
self.gain_points("vigour")
#- Fine Metodo -
def gain_points(self, name):
"""
Aggiorna la quantità dei punti: vita, mana e vigore.
"""
if not name:
log.bug("name non è un parametro valido: %r" % name)
return
# ---------------------------------------------------------------------
if self.is_fighting():
return
if self.position == POSITION.DEAD:
gain = 0
elif self.position == POSITION.MORTAL:
gain = -random.randint(4, 16)
elif self.position == POSITION.INCAP:
gain = -random.randint(0, 4)
elif self.position == POSITION.STUN:
gain = random.randint(0, 1)
elif self.position == POSITION.SLEEP:
gain = random.randint(5, max(6, math.log(1 + self.level/3) * 9))
elif self.position == POSITION.REST:
gain = random.randint(4, max(5, math.log(1 + self.level/3) * 8))
elif self.position == POSITION.SIT:
gain = random.randint(3, max(4, math.log(1 + self.level/3) * 7))
elif self.position == POSITION.KNEE:
gain = random.randint(2, max(3, math.log(1 + self.level/3) * 6))
else:
# (TD) da pensare se il gain in piedi è da disattivare, tranne
# che per i troll
gain = random.randint(1, max(2, math.log(1 + self.level/3) * 4))
points = getattr(self, name)
max_points = getattr(self, "max_" + name)
# Non si può guadagnare per volta più della metà della rimanenza dei punti
if points >= 2:
gain = min(gain, points / 2)
else:
# Caso particolare, la disperazione porta a piccole grazie!
# (TD) aggiungere un messaggio e un check sulla fortuna invece del random.randint
if gain > 0 and random.randint(1, 10) == 1:
gain = random.randint(gain, gain * 2)
# Se si ha fame o sete il guadagno dei punti è compromesso
if gain > 0:
if self.hunger >= MAX_CONDITION - SERIOUS_CONDITION: gain = 0
elif self.hunger >= MAX_CONDITION - MEDIUM_CONDITION: gain /= 2
elif self.hunger >= MAX_CONDITION - LIGHT_CONDITION: gain /= 4
if self.thirst >= MAX_CONDITION - SERIOUS_CONDITION: gain = 0
elif self.thirst >= MAX_CONDITION - MEDIUM_CONDITION: gain /= 2
elif self.thirst >= MAX_CONDITION - LIGHT_CONDITION: gain /= 4
# (TD) se si è avvelenati il guadagno della vita è compromesso
# (TD) se si è sotto effetto di incantesimi o se ci si trova in un
# posto con clima ostile l'energia è compromessa
# (TD) Se si è vampiri il guadagno dei punti cambia a seconda che sia giorno o notte
# Capita quando si hanno dei punti sovra-restorati
alternate_gain = max_points - points
if gain > 0 and alternate_gain < 0 and -alternate_gain > gain * 2:
alternate_gain /= 2
setattr(self, name, max(0, points + min(gain, alternate_gain)))
#- Fine Metodo -
def update_conditions(self):
# ---------------------------------------------------------------------
# Modifica dello stato delle condizioni
# (TD) probabilmente questo devo farlo una volta ogni minuto reale
# (TD) (BB) per ora disattivata per via del baco sui reset che non
# darebbero abbastanza cibo
return
is_alive = True
if self.level > 1 and self.trust == TRUST.PLAYER:
#if is_alive and self.thirst < MAX_CONDITION:
# self.gain_condition("thirst", +1)
is_alive = self.gain_condition("hunger", +2)
#if is_alive and self.drunkness > 0:
# self.gain_condition("drunkness", -1)
#if is_alive and self.adrenaline > 0:
# self.gain_condition("adrenaline", -1)
#if is_alive and self.bloodthirst < MAX_CONDITION:
# self.gain_condition("bloodthirst", +1)
# (TD) da rivalutare e finire, magari farla solo come malus per le
# morti, una delle due o tutte e due
#self.gain_condition("mind")
#self.gain_condition("emotion")
if not is_alive:
return
#- Fine Metodo -
def gain_condition(self, name, value):
"""
Aggiorna lo stato delle condizioni (fame, sete, sonno...)
"""
if not name:
log.bug("name non è un parametro valido: %r" % name)
return True
if value < 0 or value > MAX_CONDITION:
log.bug("name non è un parametro valido: %d" % value)
return True
# ---------------------------------------------------------------------
# (TD) qui tutto cambia molto quando ci saranno le malattie del
# vampirismo e della licantropia
# (TD) Inserire anche dei modificato di value razziali
condition = getattr(self, name)
if condition < MAX_CONDITION:
condition = max(0, min(condition + value, MAX_CONDITION))
setattr(self, name, condition)
is_alive = True
if self.IS_PLAYER and name == "hunger":
if condition >= MAX_CONDITION - SERIOUS_CONDITION:
self.act("\n" + self.get_hunger_condition(), TO.ENTITY)
self.act("$n sta languendo per la [orange]fame[close]!", TO.OTHERS)
is_alive = self.damage(self, int(math.log(self.level) * 2), DAMAGE.HUNGER)
self.send_prompt()
elif condition >= MAX_CONDITION - MEDIUM_CONDITION:
self.act("\n" + self.get_hunger_condition(), TO.ENTITY)
self.act("Avverti lo stomaco di $n che [orange]brontola[close].", TO.OTHERS)
is_alive = self.damage(self, int(math.log(self.level)), DAMAGE.HUNGER)
self.send_prompt()
elif condition >= MAX_CONDITION - LIGHT_CONDITION:
self.act("\n" + self.get_hunger_condition(), TO.ENTITY)
self.send_prompt()
# Qui nessun messaggio di act per gli altri, per evitare spam
return is_alive
#- Fine Metodo -
def skin_colorize(self, argument):
if not argument:
log.bug("argument non è un parametro valido: %r" % argument)
return ""
# ---------------------------------------------------------------------
if self.skin_color == COLOR.NONE:
return "[pink]%s[close]" % argument
elif self.skin_color.web_name == config.text_color:
return argument
else:
return "[%s]%s[close]" % (self.skin_color.web_name, argument)
#- Fine Metodo -
def eye_colorize(self, argument):
if not argument:
log.bug("argument non è un parametro valido: %r" % argument)
return ""
# ---------------------------------------------------------------------
if self.eye_color == COLOR.NONE or self.eye_color.web_name == config.text_color:
return argument
else:
return "[%s]%s[close]" % (self.eye_color.web_name, argument)
#- Fine Metodo -
def hair_colorize(self, argument):
if not argument:
log.bug("argument non è un parametro valido: %r" % argument)
return ""
# ---------------------------------------------------------------------
if self.hair_color == COLOR.NONE or self.hair_color.web_name == config.text_color:
return argument
else:
return "[%s]%s[close]" % (self.hair_color.web_name, argument)
#- Fine Metodo -
# -------------------------------------------------------------------------
def get_thirst_condition(self):
# (TD)
return "Non hai [darkcyan]sete[close]"
#- Fine Metodo -
def get_hunger_condition(self):
if self.hunger >= MAX_CONDITION - SERIOUS_CONDITION:
return "Stai languendo per la [orange]FAME[close]!"
elif self.hunger >= MAX_CONDITION - MEDIUM_CONDITION:
return "Il tuo stomaco brontola per la [orange]fame[close]"
elif self.hunger >= MAX_CONDITION - LIGHT_CONDITION:
return "Hai [orange]fame[close]"
else:
return "Non hai [orange]fame[close]"
#- Fine Metodo -
def get_sleep_condition(self):
# (TD)
return "Non hai [blue]sonno[close]"
#- Fine Metodo -
def get_drunkness_condition(self):
# (TD)
return "Non sei [purple]ubriac$o[close]"
#- Fine Metodo -
def get_adrenaline_condition(self):
# (TD)
return "La tua [red]adrenalina[close] è sotto controllo"
#- Fine Metodo -
def get_mind_condition(self):
# (TD)
return ""
#- Fine Metodo -
def get_emotion_condition(self):
# (TD)
return ""
#- Fine Metodo -
def get_bloodthirst_condition(self):
# (TD)
return ""
#- Fine Metodo -
def dies(self, opponent=None, auto_loot=False, teleport_corpse=False):
force_return = check_trigger(self, "before_die", self, opponent)
if force_return:
return
if opponent:
force_return = check_trigger(opponent, "before_dies", self, opponent)
if force_return:
return
remains, use_repop = self.make_remains(auto_loot)
# Attenzione che l'utilizzo di tali trigger potrebbero essere pericolosi
# visto che sotto c'è un'extract
force_return = check_trigger(self, "after_die", self, opponent)
if force_return:
return
if opponent:
force_return = check_trigger(opponent, "after_dies", self, opponent)
if force_return:
return
self.extract(1, use_repop=use_repop)
#- Fine Metodo -
class Track(object):
# (TD) forse spostarlo in un altro modulo in futuro
pass
def get_error_message(self):
# (TD)
return ""
#- Fine Metodo -
#= FUNZIONI ====================================================================
def create_random_mob(mob=None, name="", level=0, race=RACE.NONE, sex=SEX.NONE, way=WAY.NONE):
"""
Crea un nuovo mob con caratteristiche casuali.
"""
if not name and name != "":
log.bug("name non è un parametro valido: %r" % name)
return None
if level < 0 or level > config.max_level:
log.bug("level non è un parametro valido: %d" % level)
return None
if not race:
log.bug("race non è un parametro valido: %r" % race)
return None
if not sex:
log.bug("sex non è un parametro valido: %r" % sex)
return None
if not way:
log.bug("way non è un parametro valido: %r" % way)
return None
# ---------------------------------------------------------------------
# Crea a caso un nome se non è stato passato
if not name:
name = create_random_name(race, sex)
proto_mob_code = random.choice(database["proto_mobs"].keys())
if not mob:
mob = Mob(proto_mob_code)
mob = create_random_entity(mob, name, level, race, sex)
# (TD) tramite il way è possibile creare un set di skill adatte
# Crea casualmente gli attributi di entità che non sono stati ancora
# inizializzati dalla create_random_entity()
mob.weight = random.randint(mob.race.weight_low, mob.race.weight_high)
mob.height = random.randint(mob.race.height_low, mob.race.height_high)
mob.age = random.randint(mob.race.age_adolescence, mob.race.age_old)
# (TD) Sceglie una descrizione casuale a seconda della razza del sesso e dell'età
mob.descr = ""
mob.descr_night = ""
# Punti
mob.max_life = random.randint(90, 110)
mob.max_mana = random.randint(90, 110)
mob.max_vigour = random.randint(90, 110)
mob.life = mob.max_life - random.randint(0, mob.max_life / 4)
mob.mana = mob.max_mana - random.randint(0, mob.max_mana / 4)
mob.vigour = mob.max_vigour - random.randint(0, mob.max_vigour / 4)
# Attributi
mob.strength = random.randint(5, 95)
mob.endurance = random.randint(5, 95)
mob.agility = random.randint(5, 95)
mob.speed = random.randint(5, 95)
mob.intelligence = random.randint(5, 95)
mob.willpower = random.randint(5, 95)
mob.personality = random.randint(5, 95)
mob.luck = random.randint(5, 95)
# Condizioni
mob.thirst = random.randint(0, 25)
mob.hunger = random.randint(0, 25)
mob.drunkness = random.randint(0, 25)
mob.bloodthirst = random.randint(0, 25)
mob.adrenaline = random.randint(0, 25)
mob.mind = random.randint(0, 25)
mob.emotion = random.randint(0, 25)
# Imposta le altre variabili # (TD) da migliorare
mob.attack = random.randint(1, mob.level)
mob.defense = random.randint(1, mob.level)
mob.position.randomize(from_element=POSITION.REST, to_element=POSITION.STAND)
mob.skills = create_random_skills(mob)
mob.constellation.randomize()
mob.voice_potence = random.randint(45, 55) + mob.level / 4
if random.randint(0, 200) == 0:
mob.flags += Element(FLAG.AMBIDEXTROUS)
else:
if random.randint(0, 3) == 0:
mob.hand = Element(HAND.RIGHT)
else:
mob.hand = Element(HAND.LEFT)
return mob
#- Fine Funzione -
def create_random_skills(mob):
"""
"""
if not mob:
log.bug("mob non è valido: %s" % mob)
return
# -------------------------------------------------------------------------
skills = {}
# (TD)
return skills
#- Fine Funzione -
#= FINALIZE ====================================================================
ProtoMob.CONSTRUCTOR = Mob
Mob.CONSTRUCTOR = Mob
| gpl-2.0 |
rabbitvcs/rabbitvcs | rabbitvcs/ui/settings.py | 15360 | from __future__ import absolute_import
#
# This is an extension to the Nautilus file manager to allow better
# integration with the Subversion source control system.
#
# Copyright (C) 2006-2008 by Jason Field <[email protected]>
# Copyright (C) 2007-2008 by Bruce van der Kooij <[email protected]>
# Copyright (C) 2008-2010 by Adam Plumb <[email protected]>
#
# RabbitVCS 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.
#
# RabbitVCS 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 RabbitVCS; If not, see <http://www.gnu.org/licenses/>.
#
import os
import dbus
import datetime
from rabbitvcs.util import helper
import gi
gi.require_version("Gtk", "3.0")
sa = helper.SanitizeArgv()
from gi.repository import Gtk, GObject, Gdk, Pango
sa.restore()
from rabbitvcs.ui import InterfaceView
import rabbitvcs.ui.widget
import rabbitvcs.ui.dialog
import rabbitvcs.util.settings
from rabbitvcs.util._locale import get_locale
from rabbitvcs.util.strings import S
import rabbitvcs.services.checkerservice
from rabbitvcs.services.checkerservice import StatusCheckerStub
from rabbitvcs import gettext, _gettext, APP_NAME, LOCALE_DIR
_ = gettext.gettext
CHECKER_UNKNOWN_INFO = _("Unknown")
CHECKER_SERVICE_ERROR = _(
"There was an error communicating with the status checker service.")
class Settings(InterfaceView):
dtformats = [
["", _("default")],
["%c", _("locale")],
["%Y-%m-%d %H:%M:%S", _("ISO")],
["%b %d, %Y %I:%M:%S %p", None],
["%B %d, %Y %I:%M:%S %p", None],
["%m/%d/%Y %I:%M:%S %p", None],
["%b %d, %Y %H:%M:%S", None],
["%B %d, %Y %H:%M:%S", None],
["%m/%d/%Y %H:%M:%S", None],
["%d %b %Y %H:%M:%S", None],
["%d %B %Y %H:%M:%S", None],
["%d/%m/%Y %H:%M:%S", None]
]
def __init__(self, base_dir=None):
"""
Provides an interface to the settings library.
"""
InterfaceView.__init__(self, "settings", "Settings")
self.checker_service = None
self.settings = rabbitvcs.util.settings.SettingsManager()
self.get_widget("enable_attributes").set_active(
int(self.settings.get("general", "enable_attributes"))
)
self.get_widget("enable_emblems").set_active(
int(self.settings.get("general", "enable_emblems"))
)
self.get_widget("enable_recursive").set_active(
int(self.settings.get("general", "enable_recursive"))
)
self.get_widget("enable_highlighting").set_active(
int(self.settings.get("general","enable_highlighting"))
)
self.get_widget("enable_colorize").set_active(
int(self.settings.get("general","enable_colorize"))
)
self.get_widget("show_debug").set_active(
int(self.settings.get("general","show_debug"))
)
self.get_widget("enable_subversion").set_active(
int(self.settings.get("HideItem", "svn")) == 0
)
self.get_widget("enable_git").set_active(
int(self.settings.get("HideItem", "git")) == 0
)
dtfs = []
dt = datetime.datetime.today()
# Disambiguate day.
if dt.day <= 12:
dt = datetime.datetime(dt.year, dt.month, dt.day + 12,
dt.hour, dt.minute, dt.second)
for format, label in self.dtformats:
if label is None:
label = helper.format_datetime(dt, format)
dtfs.append([format, label])
self.datetime_format = rabbitvcs.ui.widget.ComboBox(self.get_widget("datetime_format"), dtfs, 2, 1)
self.datetime_format.set_active_from_value(
self.settings.get("general", "datetime_format")
)
self.default_commit_message = rabbitvcs.ui.widget.TextView(self.get_widget("default_commit_message"))
self.default_commit_message.set_text(
S(self.settings.get_multiline("general", "default_commit_message")).display()
)
self.get_widget("diff_tool").set_text(
S(self.settings.get("external", "diff_tool")).display()
)
self.get_widget("diff_tool_swap").set_active(
int(self.settings.get("external", "diff_tool_swap"))
)
self.get_widget("merge_tool").set_text(
S(self.settings.get("external", "merge_tool")).display()
)
self.get_widget("cache_number_repositories").set_text(
S(self.settings.get("cache", "number_repositories")).display()
)
self.get_widget("cache_number_messages").set_text(
S(self.settings.get("cache", "number_messages")).display()
)
self.logging_type = rabbitvcs.ui.widget.ComboBox(
self.get_widget("logging_type"),
["None", "Console", "File", "Both"]
)
val = self.settings.get("logging", "type")
if not val:
val = "Console"
self.logging_type.set_active_from_value(val)
self.logging_level = rabbitvcs.ui.widget.ComboBox(
self.get_widget("logging_level"),
["Debug", "Info", "Warning", "Error", "Critical"]
)
val = self.settings.get("logging", "level")
if not val:
val = "Debug"
self.logging_level.set_active_from_value(val)
# Git Configuration Editor
show_git = False
self.file_editor = None
if base_dir:
vcs = rabbitvcs.vcs.VCS()
git_config_files = []
if vcs.is_in_a_or_a_working_copy(base_dir) and vcs.guess(base_dir)["vcs"] == rabbitvcs.vcs.VCS_GIT:
git = vcs.git(base_dir)
git_config_files = git.get_config_files(base_dir)
self.file_editor = rabbitvcs.ui.widget.MultiFileTextEditor(
self.get_widget("git_config_container"),
_("Config file:"),
git_config_files,
git_config_files,
show_add_line=False
)
show_git = True
if show_git:
self.get_widget("pages").get_nth_page(5).show()
else:
self.get_widget("pages").get_nth_page(5).hide()
self._populate_checker_tab()
def _get_checker_service(self, report_failure=True):
if not self.checker_service:
try:
session_bus = dbus.SessionBus()
self.checker_service = session_bus.get_object(
rabbitvcs.services.checkerservice.SERVICE,
rabbitvcs.services.checkerservice.OBJECT_PATH)
# Initialize service locale in case it just started.
self.checker_service.SetLocale(*get_locale())
except dbus.DBusException as ex:
if report_failure:
rabbitvcs.ui.dialog.MessageBox(CHECKER_SERVICE_ERROR)
return self.checker_service
def _populate_checker_tab(self, report_failure = True, connect = True):
# This is a limitation of GLADE, and can be removed when we migrate to
# GTK2 Builder
checker_service = self.checker_service
if not checker_service and connect:
checker_service = self._get_checker_service(report_failure)
self.get_widget("stop_checker").set_sensitive(bool(checker_service))
if(checker_service):
self.get_widget("checker_type").set_text(S(checker_service.CheckerType()).display())
self.get_widget("pid").set_text(S(checker_service.PID()).display())
memory = checker_service.MemoryUsage()
if memory:
self.get_widget("memory_usage").set_text("%s KB" % memory)
else:
self.get_widget("memory_usage").set_text(CHECKER_UNKNOWN_INFO)
self.get_widget("locale").set_text(S(".".join(checker_service.SetLocale())).display())
self._populate_info_table(checker_service.ExtraInformation())
else:
self.get_widget("checker_type").set_text(CHECKER_UNKNOWN_INFO)
self.get_widget("pid").set_text(CHECKER_UNKNOWN_INFO)
self.get_widget("memory_usage").set_text(CHECKER_UNKNOWN_INFO)
self.get_widget("locale").set_text(CHECKER_UNKNOWN_INFO)
self._clear_info_table()
def _clear_info_table(self):
for info_table in self.get_widget("info_table_area").get_children():
info_table.destroy()
def _populate_info_table(self, info):
self._clear_info_table()
table_place = self.get_widget("info_table_area")
table = rabbitvcs.ui.widget.KeyValueTable(info)
table_place.add(table)
table.show()
def on_refresh_info_clicked(self, widget):
self._populate_checker_tab()
def _stop_checker(self):
pid = None
if self.checker_service:
try:
pid = self.checker_service.Quit()
except dbus.exceptions.DBusException:
# Ignore it, it will necessarily happen when we kill the service
pass
self.checker_service = None
if pid:
try:
os.waitpid(pid, 0)
except OSError:
# This occurs if the process is already gone.
pass
def on_restart_checker_clicked(self, widget):
self._stop_checker()
rabbitvcs.services.checkerservice.start()
self._populate_checker_tab()
def on_stop_checker_clicked(self, widget):
self._stop_checker()
self._populate_checker_tab(report_failure = False, connect = False)
def on_destroy(self, widget):
Gtk.main_quit()
def on_cancel_clicked(self, widget):
Gtk.main_quit()
def on_ok_clicked(self, widget):
self.save()
Gtk.main_quit()
def on_apply_clicked(self, widget):
self.save()
def save(self):
self.settings.set(
"general", "enable_attributes",
self.get_widget("enable_attributes").get_active()
)
self.settings.set(
"general", "enable_emblems",
self.get_widget("enable_emblems").get_active()
)
self.settings.set(
"general", "enable_recursive",
self.get_widget("enable_recursive").get_active()
)
self.settings.set(
"general", "enable_highlighting",
self.get_widget("enable_highlighting").get_active()
)
self.settings.set(
"general", "enable_colorize",
self.get_widget("enable_colorize").get_active()
)
self.settings.set(
"general", "show_debug",
self.get_widget("show_debug").get_active()
)
self.settings.set(
"HideItem", "svn",
not self.get_widget("enable_subversion").get_active()
)
self.settings.set(
"HideItem", "git",
not self.get_widget("enable_git").get_active()
)
self.settings.set_multiline(
"general", "default_commit_message",
self.default_commit_message.get_text()
)
self.settings.set(
"general", "datetime_format",
self.datetime_format.get_active_text()
)
self.settings.set(
"external", "diff_tool",
self.get_widget("diff_tool").get_text()
)
self.settings.set(
"external", "diff_tool_swap",
self.get_widget("diff_tool_swap").get_active()
)
self.settings.set(
"external", "merge_tool",
self.get_widget("merge_tool").get_text()
)
self.settings.set(
"cache", "number_repositories",
self.get_widget("cache_number_repositories").get_text()
)
self.settings.set(
"cache", "number_messages",
self.get_widget("cache_number_messages").get_text()
)
self.settings.set(
"logging", "type",
self.logging_type.get_active_text()
)
self.settings.set(
"logging", "level",
self.logging_level.get_active_text()
)
self.settings.write()
if self.file_editor:
self.file_editor.save()
def on_external_diff_tool_browse_clicked(self, widget):
chooser = rabbitvcs.ui.dialog.FileChooser(
_("Select a program"), "/usr/bin"
)
path = chooser.run()
if not path is None:
path = path.replace("file://", "")
self.get_widget("diff_tool").set_text(S(path).display())
def on_cache_clear_repositories_clicked(self, widget):
confirmation = rabbitvcs.ui.dialog.Confirmation(
_("Are you sure you want to clear your repository paths?")
)
if confirmation.run() == Gtk.ResponseType.OK:
path = helper.get_repository_paths_path()
fh = open(path, "w")
fh.write("")
fh.close()
rabbitvcs.ui.dialog.MessageBox(_("Repository paths cleared"))
def on_cache_clear_messages_clicked(self, widget):
confirmation = rabbitvcs.ui.dialog.Confirmation(
_("Are you sure you want to clear your previous messages?")
)
if confirmation.run() == Gtk.ResponseType.OK:
path = helper.get_previous_messages_path()
fh = open(path, "w")
fh.write("")
fh.close()
rabbitvcs.ui.dialog.MessageBox(_("Previous messages cleared"))
def on_cache_clear_authentication_clicked(self, widget):
confirmation = rabbitvcs.ui.dialog.Confirmation(
_("Are you sure you want to clear your authentication information?")
)
if confirmation.run() == Gtk.ResponseType.OK:
home_dir = helper.get_user_path()
subpaths = [
'/.subversion/auth/svn.simple',
'/.subversion/auth/svn.ssl.server',
'/.subversion/auth/svn.username'
]
for subpath in subpaths:
path = "%s%s" % (home_dir, subpath)
if os.path.exists(path):
files = os.listdir(path)
for filename in files:
filepath = "%s/%s" % (path, filename)
os.remove(filepath)
rabbitvcs.ui.dialog.MessageBox(_("Authentication information cleared"))
if __name__ == "__main__":
from rabbitvcs.ui import main, BASEDIR_OPT
(options, paths) = main(
[BASEDIR_OPT],
usage="Usage: rabbitvcs settings"
)
window = Settings(options.base_dir)
window.register_gtk_quit()
Gtk.main()
| gpl-2.0 |
benoitjupille/gestion_garderie | class/eleve.class.php | 773 | <?php
class eleve{
private $id;
private $nom;
private $prenom;
private $date_naissance;
private $classe;
public function get_date(){
return date_format(date_create($this->date_naissance), 'd/m/Y');
}
// Hydrate depuis un array associatif
public function hydrate($_donnees){
foreach ($_donnees as $propriete=>$valeur){
if(property_exists($this, $propriete)){
$this->$propriete=$valeur;
}
}
}
// GET
public function __get($_propriete){
if(property_exists($this, $_propriete)){
return $this->$_propriete;
}
}
// SET
public function __set($_propriete, $_value){
if(property_exists($this, $_propriete)){
$this->$_propriete = $_value ;
}
}
public function __destruct(){}
}
?> | gpl-2.0 |
akudryav/cms | v/themes/lang/twig_cache/cc/99/42738d6ac514ba48f35b27bedee27939ef0929cf58ffef256d83d1f0059e.php | 1189 | <?php
/* v_login.php */
class __TwigTemplate_cc9942738d6ac514ba48f35b27bedee27939ef0929cf58ffef256d83d1f0059e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<?/*
Шаблон авторизации пользователя
===============================
\$login - логин пользователя
*/?>
<h1>Авторизация</h1>
<form method=\"post\">
\tЛогин:
\t<br/>
\t<input name=\"login\" type=\"text\" value=\"\"/>
\t<br/>
\tПароль:
\t<br/>
\t<input name=\"password\" type=\"password\" value=\"\"/>
\t<br/>
\t<input type=\"checkbox\" name=\"remember\" /> запомнить меня
\t<br/>\t
\t<input type=\"submit\" value=\"Войти\"/>
\t<br/>
\t<br/>\t
\t<a href=\"/\">Главная страница</a>
</form>
";
}
public function getTemplateName()
{
return "v_login.php";
}
public function getDebugInfo()
{
return array ( 19 => 1,);
}
}
| gpl-2.0 |
stbd/walvomo-server | src/DatabaseSession.hpp | 3343 | #ifndef DATABASE_SESSION_HPP_
#define DATABASE_SESSION_HPP_
#include "Globals.hpp"
#include <stddef.h>
namespace W
{
static const unsigned NUMBER_OF_DB_WRITE_RETIRES = 5;
class DatabaseSession
{
public:
DatabaseSession() {};
virtual ~DatabaseSession(void) {};
virtual void connectToDatabase() = 0;
virtual bool createNewUser(const char * username, const size_t usernameLength) = 0;
virtual bool setUserData(WGlobals::UserInformation & user) = 0; //Not const for updates
virtual bool validateUser(const WGlobals::UserInformation & user) = 0;
virtual bool userExists(const char * username, const size_t & usernameLength) = 0;
virtual void setUserReferece(const char * username, const unsigned usernameLength, const char * key, const unsigned keyLength) = 0;
virtual const WGlobals::UserInformation & findUser(const char * username, const size_t & usernameLength) = 0;
virtual bool deleteUser(const WGlobals::UserInformation & user) = 0;
virtual const WGlobals::ListOfVotesForMonth & findVotesForMonth(const unsigned year, const unsigned month) = 0;
virtual const WGlobals::VoteInformation & findVote(const char * voteId, const size_t idLength) = 0;
virtual const WGlobals::PoliticalSeasonSeating & findSeatingForSeason(const unsigned seasonStartingYear) = 0;
virtual const WGlobals::RepresentativeInfo & findRepresentativeInfo(const unsigned representativeId) = 0;
virtual const WGlobals::PoliticalSeasonsList & findPoliticalSeasonsList(void) = 0;
virtual const WGlobals::PoliticalSeason & findPoliticalSeason(const unsigned seasonStartingYear) = 0;
virtual const WGlobals::UserVoteList & findUserVoteList(const char * username, const unsigned usernameLength, const unsigned listId) = 0;
virtual const WGlobals::UserInformation & findUserByReferece(const char * key, const unsigned keyLength) = 0;
virtual const WGlobals::NewsIndex & findNewsIndex(void) = 0;
virtual const WGlobals::NewsItem & findNewsItem(const char * key, const unsigned keyLength) = 0;
virtual const WGlobals::PoliticalPartyNames & findPoliticalPartyNameInfo(void) = 0;
virtual const WGlobals::VoteRecord & findVoteRecord(const char * date, const unsigned dateLength) = 0;
virtual const WGlobals::VoteStatistics & findVoteStatistics(const char * voteId, const unsigned idLength) = 0;
virtual const WGlobals::Collections & findCollections(void) = 0;
virtual const WGlobals::CollectionOfUpdateSources & findCollectionOfUpdateSources(const char * name, const unsigned nameLength) = 0;
virtual const WGlobals::UpdateSource & findUpdateSource(const char * name, const unsigned nameLength) = 0;
virtual const WGlobals::UpdateItem & findUpdateItem(const char * baseName, const unsigned baseNameLength, const unsigned newsNumber) = 0;
virtual void setUserVoteList(const char * username, const unsigned usernameLength, const unsigned listId, const WGlobals::UserVoteList & userVoteList) = 0;
virtual bool setUnstructuredData(const char * key, const unsigned keyLength, const char * data, const unsigned dataLength, unsigned expirationLength = 0) = 0;
virtual bool findUnstructuredData(const char * key, const unsigned keyLength, std::string & data) = 0;
virtual bool clearUnstructuredData(const char * key, const unsigned keyLength) = 0;
protected:
private:
};
}
#endif
| gpl-2.0 |
mxr1027/Xinrui-Ma | wp-content/themes/bizway/category.php | 2331 | <?php
/**
* The template for displaying Category pages.
*
*/
?>
<?php get_header(); ?>
<!--Start Page Heading -->
<div class="page-heading-container">
<div class="container_24">
<div class="grid_24">
<div class="page-heading">
<h1 class="page-title"><a href="#"><?php printf(__('Category Archives: %s', 'bizway'), '' . single_cat_title('', false) . ''); ?></a></h1>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<!--End Page Heading -->
<!--Start Page Content -->
<div class="page-content-container">
<div class="container_24">
<div class="grid_24">
<div class="page-content">
<div class="grid_sub_16 sub_alpha">
<div class="content-bar">
<?php if (have_posts()) : ?>
<?php
$category_description = category_description();
if (!empty($category_description))
echo '' . $category_description . '';
/* Run the loop for the category page to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-category.php and that will be used instead.
*/
?>
<?php get_template_part('loop', 'category'); ?>
<div class="clear"></div>
<nav id="nav-single"> <span class="nav-previous">
<?php next_posts_link(__('← Older posts', 'bizway')); ?>
</span> <span class="nav-next">
<?php previous_posts_link(__('Newer posts →', 'bizway')); ?>
</span> </nav>
<?php endif; ?>
</div>
</div>
<div class="grid_sub_8 sub_omega">
<!--Start Sidebar-->
<?php get_sidebar(); ?>
<!--End Sidebar-->
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<?php get_footer(); ?> | gpl-2.0 |
CristinaVidal/programas-c-ris | 44_ordinal_fichero/ordinal.cpp | 2264 | #include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <unistd.h>
#define MAXLETRAS 100
#define MAXCARACTERES 4
#define MAXNUMERO 1000
typedef struct Datos{
char numeroCardinal[MAXCARACTERES];
char numeroOrdinal[MAXLETRAS];
}Tablero;
int main(int argc, const char **argv){
FILE *pf;
int numero;
char caracter[MAXCARACTERES];
char ordinal[MAXLETRAS];
char letra;
int letra_comprobada;
Tablero tablero[MAXNUMERO];
/*Poner los bytes a 0*/
bzero(caracter, MAXCARACTERES*sizeof(char));
bzero(ordinal, MAXLETRAS*sizeof(char));
if(argc < 2){
printf("ERROR. FALTAN ARGUMENTOS\n");
exit(EXIT_FAILURE);
}
if(!(pf = fopen("ordinales.txt", "r+"))){
printf("ERROR. NO SE HA PODIDO ABRIR EL ARCHIVO \"ordinales.txt\"");
exit(EXIT_FAILURE);
}
if(!(numero = atoi(argv[1]))){//atoi convierte a numero
printf("ERROR. NO SE HA INTRODUCIDO UN NÚMERO.\n");
exit(EXIT_FAILURE);
}
if(numero > MAXNUMERO || numero < 0){
printf("ERROR. NÚMERO NO VÁLIDO.\nSE ADMITEN LOS VALORES COMPRENDIDOS ENTRE 0 Y %i\n", MAXNUMERO);
exit(EXIT_FAILURE);
}
printf("Cargando %i en ordinal", numero);
fflush(stdout);
sleep(1);
printf(".");
fflush(stdout);
sleep(1);
printf(".");
fflush(stdout);
sleep(1);
printf(".");
fflush(stdout);
sleep(1);
printf("\n\t\t\t");
/*Buscar el número*/
//while(letra = fgetc(pf) != EOF){
/*introducir numero en la estructura*/
for (int i = 0; i < MAXNUMERO; i++){
fscanf(pf, "%s\t%s", tablero[i].numeroCardinal, tablero[i].numeroOrdinal);
}
/*Poner primera en mayuscula y el resto en minuscula*/
for(int i = 0; i < MAXNUMERO; i++){
tablero[i].numeroOrdinal[0] = toupper(tablero[i].numeroOrdinal[0]);
for(int e = 1; e < MAXNUMERO; e++)
tablero[i].numeroOrdinal[e] = tolower(tablero[i].numeroOrdinal[e]);
}
/*Escribir la solución*/
for(int i = 0; i < MAXNUMERO; i++)
if(atoi(tablero[i].numeroCardinal) == numero){
printf("%s\n", tablero[i].numeroOrdinal);
exit(EXIT_SUCCESS);
}
return EXIT_SUCCESS;
}
| gpl-2.0 |
lanusau/aquarium | lib/aquarium/tags/plsql.rb | 802 | module Aquarium
module Tags
# IF table
class Plsql < Aquarium::Tag
register_tag :plsql
def initialize(parameters,file_name,change_collection)
@change_collection = change_collection
end
# Parse tag information from current position in the specified file
def parse(file)
plsql_blob = ''
while (line = file.gets)
# PLSQL tag should terminate with --#endplsql
if line =~ /^--#/
if line =~ /^--#endplsql/
@change_collection.current_change.current_sql_collection << plsql_blob
break
else
raise "Did not find #endplsql tag where expected:\n #{line}"
end
end
plsql_blob << line
end
end
end
end
end | gpl-2.0 |
jeremygeltman/ThinkThinly | wp-content/themes/nerocity/functions.php | 700 | <?php
include get_template_directory() . '/fw/main.php';
add_image_size( 'list-thumbnail' , 720 , 360 , true );
add_image_size( 'grid-thumbnail' , 555 , 440 , true );
add_action( 'after_setup_theme', array( 'myThemes' , 'setup' ) );
add_action( 'widgets_init' , array( 'myThemes' , 'reg_sidebars' ) );
add_action( 'wp_enqueue_scripts', array( 'myThemes' , 'init_scripts' ) );
add_filter( 'wp_title', array( 'myThemes' , 'title' ) , 10, 2 );
add_action( 'wp_head', array( 'myThemes' , 'favicon' ) );
add_filter('the_excerpt_rss', array( 'myThemes' , 'rssThumbnail' ) );
add_filter('the_content_feed', array( 'myThemes' , 'rssThumbnail' ) );
?> | gpl-2.0 |
Aventine/ktac | client/classes/KtacMesh.js | 4555 | function KtacMesh(actor, mesh) {
this.className = "KtacMesh";
this.actor = actor;
this.location = new KtacLocation();
this.locationOffset = new THREE.Vector3(0,0,0);
this.scale = null;
this.facingLongitudeOffset = 0; // in degrees, clockwise
this.mesh = mesh;
//this.graphicsJson = null;
this.animations = new Array();
//this.blendAnims = new Array();
this.lookTarget = null;
this.isColorized = false;
this.originalColors = new Array();
};
/*KtacMesh.prototype.onGraphicsLoaded = function(geometry, materials) {
};*/
KtacMesh.prototype.setLocationOffset = function(vector3) {
this.locationOffset = vector3;
};
KtacMesh.prototype.setlongitudeOffset = function(degrees) {
this.facingLongitudeOffset = degrees;
};
KtacMesh.prototype.lookNorth = function() {
this.mesh.rotation = new THREE.Euler( 0, 1, 0, 'XYZ');
this.resetUpwardAxis();
var facingLongitudeOffsetRadians = this.facingLongitudeOffset * Math.PI / 180.0;
this.mesh.rotateOnAxis(new THREE.Vector3(0,1,0), 0 - facingLongitudeOffsetRadians);
};
KtacMesh.prototype.lookAt = function(target) {
if(target == null) {
return;
}
if(target instanceof KtacLocation) {
target = target.getVector3();
}
this.mesh.lookAt(target);
this.resetUpwardAxis();
var facingLongitudeOffsetRadians = this.facingLongitudeOffset * Math.PI / 180.0;
this.mesh.rotateOnAxis(new THREE.Vector3(0,1,0), 0 - facingLongitudeOffsetRadians);
};
KtacMesh.prototype.resetUpwardAxis = function() {
var axis = new THREE.Vector3(0,1,0);
this.mesh.up = axis;
};
KtacMesh.prototype.setLocation = function(loc) {
this.location = loc;
if(this.actor.initState != INIT_STATE_READY) {
return;
}
this.mesh.position.x = loc.x + this.locationOffset.x;
this.mesh.position.y = loc.y + this.locationOffset.y;
this.mesh.position.z = loc.z + this.locationOffset.z;
};
KtacMesh.prototype.setScale = function(sca) {
this.scale = sca;
if(this.initState != INIT_STATE_READY) {
return;
}
this.mesh.scale.x = sca.x;
this.mesh.scale.y = sca.y;
this.mesh.scale.z = sca.z;
};
// setting color as boolean "false" decolorizes and restores original colors
KtacMesh.prototype.colorize = function(color) {
if(color === false) {
this.deColorize();
return;
}
// get our list of materials to colorize
var materials = new Array();
if(this.mesh.material.materials == undefined) {
// single material mesh
materials.push(this.mesh.material);
} else {
//multi material mesh
for(var i in this.mesh.material.materials) {
materials.push(this.mesh.material.materials[i]);
}
}
// if we still have our original colors, save them for later restoration
if(!this.isColorized) {
for(var i in materials) {
this.originalColors.push(materials[i].color.getHex());
}
}
// apply the colorization
for(var i in materials) {
materials[i].color.setHex(color);
}
this.isColorized = true;
};
KtacMesh.prototype.deColorize = function() {
if(!this.isColorized) {
return;
}
// get our list of materials to decolorize
var materials = new Array();
if(this.mesh.material.materials == undefined) {
// single material mesh
materials.push(this.mesh.material);
} else {
//multi material mesh
for(var i in this.mesh.material.materials) {
materials.push(this.mesh.material.materials[i]);
}
}
// apply the decolorization
for(var i in materials) {
materials[i].color.setHex(this.originalColors[i]);
}
this.isColorized = false;
};
KtacMesh.prototype.loadAnimations = function(geometryAnims, blendAnims) {
for(var i in blendAnims) {
var blendAnim = blendAnims[i];
var anim = new THREE.Animation(this.mesh, geometryAnims[blendAnim.blendIndex]);
this.animations[blendAnim.name] = anim;
}
};
KtacMesh.prototype.playAnimation = function(animName) {
if(this.animations[animName] == undefined) {
return;
}
this.animations[animName].play();
};
KtacMesh.prototype.stopAnimation = function(animName) {
if(this.animations[animName] == undefined) {
return;
}
this.animations[animName].stop();
};
KtacMesh.prototype.onGraphicsReady = function() {
scene1.add(this.mesh);
this.setLocation(this.location);
this.setScale(this.scale);
if(this.lookTarget != null) {
this.lookAt(this.lookTarget);
} else {
this.lookNorth();
}
};
KtacMesh.prototype.destruct = function() {
scene1.remove(this.mesh);
};
KtacMesh.prototype.getUuid = function() {
return this.mesh.uuid;
};
| gpl-2.0 |
bwallace722/SignMeUp2.0 | src/main/java/edu/brown/cs/signMeUpBeta/onhours/Hours.java | 4634 | package edu.brown.cs.signMeUpBeta.onhours;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;
import edu.brown.cs.signMeUpBeta.classSetup.Database;
import edu.brown.cs.signMeUpBeta.project.Question;
public class Hours {
private Map<String, Integer> questionCount;
private List<Question> questions;
private Map<String, List<String>> studentQuestions;
private int timeLim;
private Map<String, String> appointments;
private String currAss, courseId;
private Database db;
public Hours(String currAss, List<Question> questionList, String courseId, Database db) {
questions = questionList;
questionCount = new ConcurrentHashMap<String, Integer>();
timeLim = 10;
this.currAss = currAss;
appointments = new HashMap<String, String>();
studentQuestions = new ConcurrentHashMap<String, List<String>>();
this.courseId = courseId;
for (Question q : questionList) {
int count;
try {
count = db.getQuestionCount(q.content(), courseId, currAss);
} catch (Exception e) {
System.err.println(e);
count = 0;
}
questionCount.put(q.content(), count);
}
}
public List<Question> getQuestions() {
return questions;
}
public void addQuestion(Question newQuestion) {
questions.add(newQuestion);
questionCount.putIfAbsent(newQuestion.content(), 0);
}
public int getTimeLim() {
return timeLim;
}
public void setTimeLim(int newLim) {
timeLim = newLim;
}
public void setUpAppointments(Date currDate, int durationOfHours) {
long numberOfAppointments = durationOfHours * 2;
long millisecondsInAMinute = 60000;
for (long i = 1; i <= numberOfAppointments; i++) {
Date slot = new Date();
slot.setTime(currDate.getTime()
+ (i * 15 * millisecondsInAMinute));
DateFormat timeFormat = new SimpleDateFormat("h:mm a");
String time = timeFormat.format(slot.clone());
appointments.put(time, null);
}
}
public int scheduleAppointment(String time, String login) {
if (appointments.get(time) != null) {
return 0;
}
appointments.put(time, login);
return 1;
}
public int removeAppointment(String time) {
System.out.println(time);
if (appointments.get(time) == null) {
return 0;
}
appointments.put(time, null);
return 1;
}
public boolean alreadyMadeAppointment(String login) {
for (String k : appointments.keySet()) {
if (login.equals(appointments.get(k))) {
return true;
}
}
return false;
}
public int checkOffAppointment(String time) {
if (appointments.get(time) == null) {
return 0;
}
appointments.remove(time);
return 1;
}
public Map<String, String> getAppointments() {
return appointments;
}
public String getCurrAssessment() {
return currAss;
}
public void incrementQuestion(String q) {
if (questionCount.containsKey(q)) {
questionCount.put(q, questionCount.get(q) + 1);
} else {
questionCount.put(q, 1);
}
}
public void updateQuestions(String login, List<String> questions) {
if (login != null) {
studentQuestions.put(login, questions);
}
for (String q : questions) {
incrementQuestion(q);
}
}
private class CountComp implements Comparator<String> {
@Override
public int compare(String a, String b) {
return questionCount.get(b)
- questionCount.get(a);
}
}
public List<String> mostPopularQuestions() {
PriorityQueue<String> pq = new PriorityQueue<String>(new CountComp());
for (String q : questionCount.keySet()) {
pq.add(q);
}
List<String> ret = new ArrayList<String>();
for (int i = 0; i < 3; i++) {
if (!pq.isEmpty()) {
ret.add(pq.poll());
}
}
return ret;
}
public List<String> studentsWhoAsked(String question) {
List<String> ret = new ArrayList<String>();
for (String student : studentQuestions.keySet()) {
List<String> questions = studentQuestions.get(student);
if (questions.contains(question)) {
ret.add(student);
}
}
return ret;
}
public void removeStudent(String login) {
studentQuestions.remove(login);
}
//
// public List<QuestionInterface> currentQuestions() {
// return null;
// }
//
// public List<Appointment> currentAppointments() {
// return null;
// }
}
| gpl-2.0 |
egbot/Symbiota | api/vendor/zircote/swagger-php/Examples/using-traits/TrickyProduct.php | 291 | <?php
namespace UsingTraits;
use UsingTraits\Blink as TheBlink;
/**
* @OA\Schema(title="TrickyProduct model")
* )
*/
class TrickyProduct extends SimpleProduct {
use TheBlink;
/**
* The trick.
*
* @OA\Property(example="recite poem")
*/
public $trick;
}
| gpl-2.0 |
aarontc/kde-workspace | kwin/tabbox/tabboxhandler.cpp | 15116 | /********************************************************************
KWin - the KDE window manager
This file is part of the KDE project.
Copyright (C) 2009 Martin Gräßlin <[email protected]>
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/>.
*********************************************************************/
// own
#include "tabboxhandler.h"
#include <kwinglobals.h>
#include "xcbutils.h"
// tabbox
#include "clientmodel.h"
#include "declarative.h"
#include "desktopmodel.h"
#include "tabboxconfig.h"
// Qt
#include <QKeyEvent>
#include <QModelIndex>
#include <QTimer>
#include <QX11Info>
#include <X11/Xlib.h>
// KDE
#include <KProcess>
#include <KWindowSystem>
namespace KWin
{
namespace TabBox
{
class TabBoxHandlerPrivate
{
public:
TabBoxHandlerPrivate(TabBoxHandler *q);
~TabBoxHandlerPrivate();
/**
* Updates the current highlight window state
*/
void updateHighlightWindows();
/**
* Ends window highlighting
*/
void endHighlightWindows(bool abort = false);
ClientModel* clientModel() const;
DesktopModel* desktopModel() const;
TabBoxHandler *q; // public pointer
// members
TabBoxConfig config;
QScopedPointer<DeclarativeView> m_declarativeView;
QScopedPointer<DeclarativeView> m_declarativeDesktopView;
ClientModel* m_clientModel;
DesktopModel* m_desktopModel;
QModelIndex index;
/**
* Indicates if the tabbox is shown.
*/
bool isShown;
TabBoxClient *lastRaisedClient, *lastRaisedClientSucc;
WId m_embedded;
QPoint m_embeddedOffset;
QSize m_embeddedSize;
Qt::Alignment m_embeddedAlignment;
Xcb::Atom m_highlightWindowsAtom;
};
TabBoxHandlerPrivate::TabBoxHandlerPrivate(TabBoxHandler *q)
: m_declarativeView(NULL)
, m_declarativeDesktopView(NULL)
, m_embedded(0)
, m_embeddedOffset(QPoint(0, 0))
, m_embeddedSize(QSize(0, 0))
, m_highlightWindowsAtom(QByteArrayLiteral("_KDE_WINDOW_HIGHLIGHT"))
{
this->q = q;
isShown = false;
lastRaisedClient = 0;
lastRaisedClientSucc = 0;
config = TabBoxConfig();
m_clientModel = new ClientModel(q);
m_desktopModel = new DesktopModel(q);
}
TabBoxHandlerPrivate::~TabBoxHandlerPrivate()
{
}
ClientModel* TabBoxHandlerPrivate::clientModel() const
{
return m_clientModel;
}
DesktopModel* TabBoxHandlerPrivate::desktopModel() const
{
return m_desktopModel;
}
void TabBoxHandlerPrivate::updateHighlightWindows()
{
if (!isShown || config.tabBoxMode() != TabBoxConfig::ClientTabBox)
return;
TabBoxClient *currentClient = q->client(index);
QWindow *w = NULL;
if (m_declarativeView && m_declarativeView->isVisible()) {
w = m_declarativeView.data();
}
if (q->isKWinCompositing()) {
if (lastRaisedClient)
q->elevateClient(lastRaisedClient, m_declarativeView ? m_declarativeView->winId() : 0, false);
lastRaisedClient = currentClient;
if (currentClient)
q->elevateClient(currentClient, m_declarativeView ? m_declarativeView->winId() : 0, true);
} else {
if (lastRaisedClient) {
if (lastRaisedClientSucc)
q->restack(lastRaisedClient, lastRaisedClientSucc);
// TODO lastRaisedClient->setMinimized( lastRaisedClientWasMinimized );
}
lastRaisedClient = currentClient;
if (lastRaisedClient) {
// TODO if ( (lastRaisedClientWasMinimized = lastRaisedClient->isMinimized()) )
// lastRaisedClient->setMinimized( false );
TabBoxClientList order = q->stackingOrder();
int succIdx = order.count() + 1;
for (int i=0; i<order.count(); ++i) {
if (order.at(i).data() == lastRaisedClient) {
succIdx = i + 1;
break;
}
}
lastRaisedClientSucc = (succIdx < order.count()) ? order.at(succIdx).data() : 0;
q->raiseClient(lastRaisedClient);
}
}
xcb_window_t wId;
QVector< xcb_window_t > data;
if (config.isShowTabBox() && w) {
wId = w->winId();
data.resize(2);
data[ 1 ] = wId;
} else {
wId = QX11Info::appRootWindow();
data.resize(1);
}
data[ 0 ] = currentClient ? currentClient->window() : 0L;
xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, wId, m_highlightWindowsAtom,
m_highlightWindowsAtom, 32, data.size(), data.constData());
}
void TabBoxHandlerPrivate::endHighlightWindows(bool abort)
{
TabBoxClient *currentClient = q->client(index);
if (currentClient)
q->elevateClient(currentClient, m_declarativeView ? m_declarativeView->winId() : 0, false);
if (abort && lastRaisedClient && lastRaisedClientSucc)
q->restack(lastRaisedClient, lastRaisedClientSucc);
lastRaisedClient = 0;
lastRaisedClientSucc = 0;
// highlight windows
xcb_delete_property(connection(), config.isShowTabBox() && m_declarativeView ? m_declarativeView->winId() : rootWindow(), m_highlightWindowsAtom);
}
/***********************************************
* TabBoxHandler
***********************************************/
TabBoxHandler::TabBoxHandler()
: QObject()
{
KWin::TabBox::tabBox = this;
d = new TabBoxHandlerPrivate(this);
}
TabBoxHandler::~TabBoxHandler()
{
delete d;
}
const KWin::TabBox::TabBoxConfig& TabBoxHandler::config() const
{
return d->config;
}
void TabBoxHandler::setConfig(const TabBoxConfig& config)
{
d->config = config;
emit configChanged();
}
void TabBoxHandler::show()
{
d->isShown = true;
d->lastRaisedClient = 0;
d->lastRaisedClientSucc = 0;
if (d->config.isShowTabBox()) {
DeclarativeView *dv(NULL);
if (d->config.tabBoxMode() == TabBoxConfig::ClientTabBox) {
// use declarative view
if (!d->m_declarativeView) {
d->m_declarativeView.reset(new DeclarativeView(d->clientModel(), TabBoxConfig::ClientTabBox));
}
dv = d->m_declarativeView.data();
} else {
if (!d->m_declarativeDesktopView) {
d->m_declarativeDesktopView.reset(new DeclarativeView(d->desktopModel(), TabBoxConfig::DesktopTabBox));
}
dv = d->m_declarativeDesktopView.data();
}
if (dv->status() == QQuickView::Ready && dv->rootObject()) {
dv->show();
dv->setCurrentIndex(d->index, d->config.tabBoxMode() == TabBoxConfig::ClientTabBox);
} else {
QStringList args;
args << QStringLiteral("--passivepopup") << /*i18n*/QStringLiteral("The Window Switcher installation is broken, resources are missing.\n"
"Contact your distribution about this.") << QStringLiteral("20");
KProcess::startDetached(QStringLiteral("kdialog"), args);
hide();
return;
}
}
if (d->config.isHighlightWindows()) {
Xcb::sync();
// TODO this should be
// QMetaObject::invokeMethod(this, "updateHighlightWindows", Qt::QueuedConnection);
// but we somehow need to cross > 1 event cycle (likely because of queued invocation in the effects)
// to ensure the EffectWindow is present when updateHighlightWindows, thus elevating the window/tabbox
QTimer::singleShot(1, this, SLOT(updateHighlightWindows()));
}
}
void TabBoxHandler::updateHighlightWindows()
{
d->updateHighlightWindows();
}
void TabBoxHandler::hide(bool abort)
{
d->isShown = false;
if (d->config.isHighlightWindows()) {
d->endHighlightWindows(abort);
}
d->m_declarativeView.reset();
d->m_declarativeDesktopView.reset();
}
QModelIndex TabBoxHandler::nextPrev(bool forward) const
{
QModelIndex ret;
QAbstractItemModel* model;
switch(d->config.tabBoxMode()) {
case TabBoxConfig::ClientTabBox:
model = d->clientModel();
break;
case TabBoxConfig::DesktopTabBox:
model = d->desktopModel();
break;
default:
return d->index;
}
if (forward) {
int column = d->index.column() + 1;
int row = d->index.row();
if (column == model->columnCount()) {
column = 0;
row++;
if (row == model->rowCount())
row = 0;
}
ret = model->index(row, column);
if (!ret.isValid())
ret = model->index(0, 0);
} else {
int column = d->index.column() - 1;
int row = d->index.row();
if (column < 0) {
column = model->columnCount() - 1;
row--;
if (row < 0)
row = model->rowCount() - 1;
}
ret = model->index(row, column);
if (!ret.isValid()) {
row = model->rowCount() - 1;
for (int i = model->columnCount() - 1; i >= 0; i--) {
ret = model->index(row, i);
if (ret.isValid())
break;
}
}
}
if (ret.isValid())
return ret;
else
return d->index;
}
QModelIndex TabBoxHandler::desktopIndex(int desktop) const
{
if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox)
return QModelIndex();
return d->desktopModel()->desktopIndex(desktop);
}
QList< int > TabBoxHandler::desktopList() const
{
if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox)
return QList< int >();
return d->desktopModel()->desktopList();
}
int TabBoxHandler::desktop(const QModelIndex& index) const
{
if (!index.isValid() || (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox))
return -1;
QVariant ret = d->desktopModel()->data(index, DesktopModel::DesktopRole);
if (ret.isValid())
return ret.toInt();
else
return -1;
}
void TabBoxHandler::setCurrentIndex(const QModelIndex& index)
{
if (d->index == index) {
return;
}
if (!index.isValid()) {
return;
}
if (d->m_declarativeView) {
d->m_declarativeView->setCurrentIndex(index);
}
if (d->m_declarativeDesktopView) {
d->m_declarativeDesktopView->setCurrentIndex(index);
}
d->index = index;
if (d->config.tabBoxMode() == TabBoxConfig::ClientTabBox) {
if (d->config.isHighlightWindows()) {
d->updateHighlightWindows();
}
}
emit selectedIndexChanged();
}
const QModelIndex& TabBoxHandler::currentIndex() const
{
return d->index;
}
void TabBoxHandler::grabbedKeyEvent(QKeyEvent* event) const
{
if (d->m_declarativeView && d->m_declarativeView->isVisible()) {
d->m_declarativeView->sendKeyEvent(event);
} else if (d->m_declarativeDesktopView && d->m_declarativeDesktopView->isVisible()) {
d->m_declarativeDesktopView->sendKeyEvent(event);
}
}
bool TabBoxHandler::containsPos(const QPoint& pos) const
{
QWindow *w = NULL;
if (d->m_declarativeView && d->m_declarativeView->isVisible()) {
w = d->m_declarativeView.data();
} else if (d->m_declarativeDesktopView && d->m_declarativeDesktopView->isVisible()) {
w = d->m_declarativeDesktopView.data();
} else {
return false;
}
return w->geometry().contains(pos);
}
QModelIndex TabBoxHandler::index(QWeakPointer<KWin::TabBox::TabBoxClient> client) const
{
return d->clientModel()->index(client);
}
TabBoxClientList TabBoxHandler::clientList() const
{
if (d->config.tabBoxMode() != TabBoxConfig::ClientTabBox)
return TabBoxClientList();
return d->clientModel()->clientList();
}
TabBoxClient* TabBoxHandler::client(const QModelIndex& index) const
{
if ((!index.isValid()) ||
(d->config.tabBoxMode() != TabBoxConfig::ClientTabBox))
return NULL;
TabBoxClient* c = static_cast< TabBoxClient* >(
d->clientModel()->data(index, ClientModel::ClientRole).value<void *>());
return c;
}
void TabBoxHandler::createModel(bool partialReset)
{
switch(d->config.tabBoxMode()) {
case TabBoxConfig::ClientTabBox: {
d->clientModel()->createClientList(partialReset);
// TODO: C++11 use lambda function
bool lastRaised = false;
bool lastRaisedSucc = false;
foreach (const QWeakPointer<TabBoxClient> &clientPointer, stackingOrder()) {
QSharedPointer<TabBoxClient> client = clientPointer.toStrongRef();
if (!client) {
continue;
}
if (client.data() == d->lastRaisedClient) {
lastRaised = true;
}
if (client.data() == d->lastRaisedClientSucc) {
lastRaisedSucc = true;
}
}
if (d->lastRaisedClient && !lastRaised)
d->lastRaisedClient = 0;
if (d->lastRaisedClientSucc && !lastRaisedSucc)
d->lastRaisedClientSucc = 0;
break;
}
case TabBoxConfig::DesktopTabBox:
d->desktopModel()->createDesktopList();
break;
}
}
QModelIndex TabBoxHandler::first() const
{
QAbstractItemModel* model;
switch(d->config.tabBoxMode()) {
case TabBoxConfig::ClientTabBox:
model = d->clientModel();
break;
case TabBoxConfig::DesktopTabBox:
model = d->desktopModel();
break;
default:
return QModelIndex();
}
return model->index(0, 0);
}
WId TabBoxHandler::embedded() const
{
return d->m_embedded;
}
void TabBoxHandler::setEmbedded(WId wid)
{
d->m_embedded = wid;
emit embeddedChanged(wid != 0);
}
void TabBoxHandler::setEmbeddedOffset(const QPoint &offset)
{
d->m_embeddedOffset = offset;
}
void TabBoxHandler::setEmbeddedSize(const QSize &size)
{
d->m_embeddedSize = size;
}
const QPoint &TabBoxHandler::embeddedOffset() const
{
return d->m_embeddedOffset;
}
const QSize &TabBoxHandler::embeddedSize() const
{
return d->m_embeddedSize;
}
Qt::Alignment TabBoxHandler::embeddedAlignment() const
{
return d->m_embeddedAlignment;
}
void TabBoxHandler::setEmbeddedAlignment(Qt::Alignment alignment)
{
d->m_embeddedAlignment = alignment;
}
void TabBoxHandler::resetEmbedded()
{
if (d->m_embedded == 0) {
return;
}
d->m_embedded = 0;
d->m_embeddedOffset = QPoint(0, 0);
d->m_embeddedSize = QSize(0, 0);
emit embeddedChanged(false);
}
TabBoxHandler* tabBox = 0;
TabBoxClient::TabBoxClient()
{
}
TabBoxClient::~TabBoxClient()
{
}
} // namespace TabBox
} // namespace KWin
| gpl-2.0 |
kindprojects/workstation | ProfileCut/ImportService/Repository/Fb/RepCollection.cs | 2245 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FirebirdSql.Data.FirebirdClient;
namespace ImportService.Repository.Fb
{
internal class RepCollection
{
public int? Get(FbConnection conn, FbTransaction trans, int objectId, string code, bool createIfNotExist)
{
string query = "SELECT * FROM sp_get_collection(@objectid, @collectioncode, @createifnotexist)";
int? ret = null;
try
{
using (FbCommand cmd = new FbCommand(query, conn, trans))
{
cmd.Parameters.AddWithValue("@objectid", objectId);
cmd.Parameters.AddWithValue("@collectioncode", code);
cmd.Parameters.AddWithValue("@createifnotexist", createIfNotExist);
using (FbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret = !reader.IsDBNull(0) ? reader.GetInt32(0) as int? : null;
}
}
}
}
catch (Exception ex)
{
throw new Exception(String.Format("Ошибка SQL запроса. {0}", ex.Message));
}
return ret;
}
public void Delete(FbConnection conn, FbTransaction trans, int ownerObjectId, string code)
{
string query = "DELETE FROM collections WHERE owner_objectid = @owner_objectid AND collectioncode = UPPER(@collectioncode)";
try
{
using (FbCommand cmd = new FbCommand(query, conn, trans))
{
cmd.Parameters.AddWithValue("@owner_objectid", ownerObjectId);
cmd.Parameters.AddWithValue("@collectioncode", code);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw new Exception(String.Format("Ошибка SQL запроса. {0}", ex.Message));
}
}
}
}
| gpl-2.0 |
ivankliuk/cheat-sheets | python/iterators_and_generators.py | 1281 | __doc__ = """Iterator interface in Python
"""
class Iter(object):
def __init__(self, lst_obj):
self.list_obj = list(lst_obj)
def __iter__(self):
return self
def next(self):
try:
return self.list_obj.pop(0)
except IndexError:
raise StopIteration
class Container(object):
"""Container class which exposes different
approaches in implementation of iterator
"""
def __init__(self, lst_obj):
self.lst_obj = lst_obj
def proxy_iter(self):
return iter(self.lst_obj)
def custom_iter(self):
return Iter(self.lst_obj)
def generator_iter(self):
for i in self.lst_obj:
yield i
# Tests
if __name__ == "__main__":
lst = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
container = Container(lst)
proxy_iter = [i for i in container.proxy_iter()]
custom_iter = [i for i in container.custom_iter()]
generator_iter = [i for i in container.generator_iter()]
assert proxy_iter == custom_iter == generator_iter
# Whether object is iterable
import collections
assert isinstance(proxy_iter, collections.Iterable)
assert isinstance(custom_iter, collections.Iterable)
assert isinstance(generator_iter, collections.Iterable)
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Review/Ui/DataProvider/Product/Form/Modifier/Review.php | 4413 | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Review\Ui\DataProvider\Product\Form\Modifier;
/**
* Class Review
*/
use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Ui\Component\Form;
use Magento\Framework\UrlInterface;
use Magento\Framework\Module\Manager as ModuleManager;
use Magento\Framework\App\ObjectManager;
/**
* Review modifier for catalog product form
*
* @api
* @since 100.1.0
*/
class Review extends AbstractModifier
{
const GROUP_REVIEW = 'review';
const GROUP_CONTENT = 'content';
const DATA_SCOPE_REVIEW = 'grouped';
const SORT_ORDER = 20;
const LINK_TYPE = 'associated';
/**
* @var LocatorInterface
* @since 100.1.0
*/
protected $locator;
/**
* @var UrlInterface
* @since 100.1.0
*/
protected $urlBuilder;
/**
* @var ModuleManager
*/
private $moduleManager;
/**
* @param LocatorInterface $locator
* @param UrlInterface $urlBuilder
*/
public function __construct(
LocatorInterface $locator,
UrlInterface $urlBuilder
) {
$this->locator = $locator;
$this->urlBuilder = $urlBuilder;
}
/**
* {@inheritdoc}
* @since 100.1.0
*/
public function modifyMeta(array $meta)
{
if (!$this->locator->getProduct()->getId() || !$this->getModuleManager()->isOutputEnabled('Magento_Review')) {
return $meta;
}
$meta[static::GROUP_REVIEW] = [
'children' => [
'review_listing' => [
'arguments' => [
'data' => [
'config' => [
'autoRender' => true,
'componentType' => 'insertListing',
'dataScope' => 'review_listing',
'externalProvider' => 'review_listing.review_listing_data_source',
'selectionsProvider' => 'review_listing.review_listing.product_columns.ids',
'ns' => 'review_listing',
'render_url' => $this->urlBuilder->getUrl('mui/index/render'),
'realTimeLink' => false,
'behaviourType' => 'simple',
'externalFilterMode' => true,
'imports' => [
'productId' => '${ $.provider }:data.product.current_product_id'
],
'exports' => [
'productId' => '${ $.externalProvider }:params.current_product_id'
],
],
],
],
],
],
'arguments' => [
'data' => [
'config' => [
'label' => __('Product Reviews'),
'collapsible' => true,
'opened' => false,
'componentType' => Form\Fieldset::NAME,
'sortOrder' =>
$this->getNextGroupSortOrder(
$meta,
static::GROUP_CONTENT,
static::SORT_ORDER
),
],
],
],
];
return $meta;
}
/**
* {@inheritdoc}
* @since 100.1.0
*/
public function modifyData(array $data)
{
$productId = $this->locator->getProduct()->getId();
$data[$productId][self::DATA_SOURCE_DEFAULT]['current_product_id'] = $productId;
return $data;
}
/**
* Retrieve module manager instance using dependency lookup to keep this class backward compatible.
*
* @return ModuleManager
*
* @deprecated 100.2.0
*/
private function getModuleManager()
{
if ($this->moduleManager === null) {
$this->moduleManager = ObjectManager::getInstance()->get(ModuleManager::class);
}
return $this->moduleManager;
}
}
| gpl-2.0 |
AlexeyPopovUA/Learning-ExtJS-6-Classes | ext/packages/charts/classic/overrides/AbstractChart.js | 1173 | /**
* @class Ext.chart.overrides.AbstractChart
*/
Ext.define('Ext.chart.overrides.AbstractChart', {
override: 'Ext.chart.AbstractChart',
updateLegend: function (legend, oldLegend) {
var dock;
this.callParent([legend, oldLegend]);
if (legend) {
dock = legend.docked;
this.addDocked({
dock: dock,
xtype: 'panel',
shrinkWrap: true,
scrollable: true,
layout: {
type: dock === 'top' || dock === 'bottom' ? 'hbox' : 'vbox',
pack: 'center'
},
items: legend,
cls: Ext.baseCSSPrefix + 'legend-panel'
});
}
},
performLayout: function() {
if (this.isVisible(true)) {
return this.callParent();
}
this.cancelLayout();
return false;
},
afterComponentLayout: function(width, height, oldWidth, oldHeight) {
this.callParent([width, height, oldWidth, oldHeight]);
this.scheduleLayout();
},
allowSchedule: function() {
return this.rendered;
}
}); | gpl-2.0 |
carmark/vbox | src/VBox/Runtime/common/crypto/spc-core.cpp | 3198 | /* $Id: spc-core.cpp 56290 2015-06-09 14:01:31Z vboxsync $ */
/** @file
* IPRT - Crypto - Microsoft SPC / Authenticode, Core APIs.
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include "internal/iprt.h"
#include <iprt/crypto/spc.h>
#include <iprt/err.h>
#include <iprt/string.h>
#include <iprt/uuid.h>
#include "spc-internal.h"
RTDECL(int) RTCrSpcSerializedPageHashes_UpdateDerivedData(PRTCRSPCSERIALIZEDPAGEHASHES pThis)
{
pThis->pData = (PCRTCRSPCPEIMAGEPAGEHASHES)pThis->RawData.Asn1Core.uData.pv;
return VINF_SUCCESS;
}
/*
* SPC Indirect Data Content.
*/
RTDECL(PCRTCRSPCSERIALIZEDOBJECTATTRIBUTE)
RTCrSpcIndirectDataContent_GetPeImageObjAttrib(PCRTCRSPCINDIRECTDATACONTENT pThis,
RTCRSPCSERIALIZEDOBJECTATTRIBUTETYPE enmType)
{
if (pThis->Data.enmType == RTCRSPCAAOVTYPE_PE_IMAGE_DATA)
{
Assert(RTAsn1ObjId_CompareWithString(&pThis->Data.Type, RTCRSPCPEIMAGEDATA_OID) == 0);
if ( pThis->Data.uValue.pPeImage
&& pThis->Data.uValue.pPeImage->T0.File.enmChoice == RTCRSPCLINKCHOICE_MONIKER
&& RTCrSpcSerializedObject_IsPresent(pThis->Data.uValue.pPeImage->T0.File.u.pMoniker) )
{
if (pThis->Data.uValue.pPeImage->T0.File.u.pMoniker->enmType == RTCRSPCSERIALIZEDOBJECTTYPE_ATTRIBUTES)
{
Assert(RTUuidCompareStr(pThis->Data.uValue.pPeImage->T0.File.u.pMoniker->Uuid.Asn1Core.uData.pUuid,
RTCRSPCSERIALIZEDOBJECT_UUID_STR) == 0);
PCRTCRSPCSERIALIZEDOBJECTATTRIBUTES pData = pThis->Data.uValue.pPeImage->T0.File.u.pMoniker->u.pData;
if (pData)
for (uint32_t i = 0; i < pData->cItems; i++)
if (pData->paItems[i].enmType == enmType)
return &pData->paItems[i];
}
}
}
return NULL;
}
/*
* Generate the standard core code.
*/
#include <iprt/asn1-generator-core.h>
| gpl-2.0 |
russom-woldezghi/bmcg | wp-content/themes/tblog/admin/theme-options.php | 4919 | <?php
add_action('init','of_options');
if (!function_exists('of_options')) {
function of_options(){
//Access the WordPress Categories via an Array
$of_categories = array();
$of_categories_obj = get_categories('hide_empty=0');
foreach ($of_categories_obj as $of_cat) {
$of_categories[$of_cat->cat_ID] = $of_cat->cat_name;}
$categories_tmp = array_unshift($of_categories, "Select a category:");
//Access the WordPress Pages via an Array
$of_pages = array();
$of_pages_obj = get_pages('sort_column=post_parent,menu_order');
foreach ($of_pages_obj as $of_page) {
$of_pages[$of_page->ID] = $of_page->post_name; }
$of_pages_tmp = array_unshift($of_pages, "Select a page:");
//Options
$enable_disable = array('enable','disable');
$disable_enable = array('disable','enable');
$color_schemes = array('light','dark');
$cropped_full = array('cropped','full');
$service_cat_layout = array('full','sidebar');
$fixed_static = array('fixed','static');
$blank_self = array('blank','self');
$header_styles = array('one','two', 'three', 'four');
//Stylesheets Reader
$alt_stylesheet_path = LAYOUT_PATH;
$alt_stylesheets = array();
if ( is_dir($alt_stylesheet_path) ) {
if ($alt_stylesheet_dir = opendir($alt_stylesheet_path) ) {
while ( ($alt_stylesheet_file = readdir($alt_stylesheet_dir)) !== false ) {
if(stristr($alt_stylesheet_file, ".css") !== false) {
$alt_stylesheets[] = $alt_stylesheet_file;
}
}
}
}
//Background Images Reader
$bg_images_path = STYLESHEETPATH. '/images/bg/'; // change this to where you store your bg images
$bg_images_url = get_template_directory_uri().'/images/bg/'; // change this to where you store your bg images
$bg_images = array();
if ( is_dir($bg_images_path) ) {
if ($bg_images_dir = opendir($bg_images_path) ) {
while ( ($bg_images_file = readdir($bg_images_dir)) !== false ) {
if(stristr($bg_images_file, ".png") !== false || stristr($bg_images_file, ".jpg") !== false) {
$bg_images[] = $bg_images_url . $bg_images_file;
}
}
}
}
/*-----------------------------------------------------------------------------------*/
/* The Options Array */
/*-----------------------------------------------------------------------------------*/
// Set the Options Array
global $of_options;
$of_options = array();
$of_options[] = array( "name" => __('General', 'unique theme options'),
"type" => "heading");
$of_options[] = array( "name" => __('Main Logo Upload', 'unique'),
"desc" => __('Upload your custom logo using the native media uploader, or define the URL directly', 'unique'),
"id" => "custom_logo",
"std" => "",
"type" => "media");
$of_options[] = array( "name" => __('Custom Favicon', 'unique'),
"desc" => __('Upload or past the URL for your custom favicon image here.', 'unique'),
"id" => "custom_favicon",
"std" => "",
"type" => "upload");
$of_options[] = array( "name" => __('Tracking Code (Footer)', 'unique'),
"desc" => __('Paste your Google Analytics (or other) tracking code here. This will be added into the footer template of your theme.', 'unique'),
"id" => "tracking_footer",
"std" => "",
"type" => "textarea");
$of_options[] = array( "name" => __('Copyright (Footer)', 'unique'),
"desc" => __('Add your footer copyright message here.', 'unique'),
"id" => "coyright_footer",
"std" => "Copyright",
"type" => "text");
$of_options[] = array( "name" => __('Home', 'unique'),
"type" => "heading");
$of_options[] = array( "name" => __('H1 Tagline', 'unique'),
"desc" => __('Enter your custom about H1 tagline here.', 'unique'),
"id" => "h1_tagline",
"std" => '<h1>Lorem Ipsum #<br />Dolar sit amet</h1>',
"type" => "text");
$of_options[] = array( "name" => __('Tagline Message', 'unique'),
"desc" => __('Enter the text for your about tagline message section.', 'unique'),
"id" => "message_tagline",
"std" => "<p>The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p>",
"type" => "textarea");
$of_options[] = array( "name" => "Backup",
"type" => "heading");
$of_options[] = array( "name" => "Backup and Restore Options",
"desc" => __('You can use the two buttons below to backup your current options, and then restore it back at a later time. This is useful if you want to experiment on the options but would like to keep the old settings in case you need it back.','unique'),
"id" => "aq_backup",
"std" => "",
"type" => "backup",
"options" => "",
);
}
}
?>
| gpl-2.0 |
flyingghost/KeepKeepClean | src/main/java/proguard/classfile/attribute/annotation/visitor/AnnotatedClassVisitor.java | 1909 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2015 Eric Lafortune @ GuardSquare
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.attribute.annotation.visitor;
import proguard.classfile.Clazz;
import proguard.classfile.attribute.annotation.Annotation;
import proguard.classfile.util.SimplifiedVisitor;
import proguard.classfile.visitor.ClassVisitor;
/**
* This AnnotationVisitor delegates all visits to a given ClassVisitor.
* The latter visits the class of each visited annotation, although
* never twice in a row.
*
* @author Eric Lafortune
*/
public class AnnotatedClassVisitor
extends SimplifiedVisitor
implements AnnotationVisitor
{
private final ClassVisitor classVisitor;
private Clazz lastVisitedClass;
public AnnotatedClassVisitor(ClassVisitor classVisitor)
{
this.classVisitor = classVisitor;
}
// Implementations for AnnotationVisitor.
public void visitAnnotation(Clazz clazz, Annotation annotation)
{
if (!clazz.equals(lastVisitedClass))
{
clazz.accept(classVisitor);
lastVisitedClass = clazz;
}
}
}
| gpl-2.0 |
WopsS/SA-MP-Plus | Source/SharedLib/Settings/Settings.cpp | 1609 | #include <SharedLib.hpp>
#include <Singleton/Singleton.hpp>
Settings::Settings()
{
Add("logtimeformat", "[%H:%M:%S]");
}
void Settings::Add(const std::string& Key, const std::string& Value)
{
// If the setting's key doesn't exists add it with the value, otherwise replace the value.
if (m_settings.find(Key) == m_settings.end())
{
m_settings.emplace(Key, Value);
}
else
{
m_settings.at(Key) = Value;
}
}
const bool Settings::Exists(const std::string& Key) const
{
return m_settings.find(Key) != m_settings.end();
}
void Settings::Process(const std::string& Text, const char& Delimiter, const std::vector<std::string>& Excludes)
{
// Ignore the line if we don't have the specified separator in it.
if (Text.find(Delimiter) != std::string::npos)
{
// Check if we have something to exclude.
for (auto& i : Excludes)
{
if (Text.substr(0, i.length()) == i)
{
return;
}
}
auto Result = String::Split(Text, Delimiter);
// If we have more than one delimiter characters on the line we will combine all values because it may be "hostname SA-MP 0.3 Server", etc..
for (size_t i = 2; i < Result.size(); i++)
{
Result[1] += " " + Result[i];
}
// Add the option and the value(s) to the list.
Add(Result[0], Result.size() >= 2 ? Result[1] : "");
}
}
void Settings::Read(const std::string& Path, const char& Delimiter, const std::vector<std::string>& Excludes)
{
std::fstream File(Path.c_str(), std::ios::in);
std::string Line;
// Read every line from the file and process it.
while (std::getline(File, Line))
{
Process(Line, Delimiter, Excludes);
}
}
| gpl-2.0 |
A-Metaphysical-Drama/BloodyCore | src/server/game/Spells/SpellMgr.cpp | 162963 | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 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 "SpellMgr.h"
#include "ObjectMgr.h"
#include "SpellAuras.h"
#include "SpellAuraDefines.h"
#include "DBCStores.h"
#include "World.h"
#include "Chat.h"
#include "Spell.h"
#include "BattlegroundMgr.h"
#include "CreatureAI.h"
#include "MapManager.h"
#include "BattlegroundIC.h"
bool IsAreaEffectTarget[TOTAL_SPELL_TARGETS];
SpellEffectTargetTypes EffectTargetType[TOTAL_SPELL_EFFECTS];
SpellSelectTargetTypes SpellTargetType[TOTAL_SPELL_TARGETS];
SpellMgr::SpellMgr()
{
for (int i = 0; i < TOTAL_SPELL_EFFECTS; ++i)
{
switch(i)
{
case SPELL_EFFECT_PERSISTENT_AREA_AURA: //27
case SPELL_EFFECT_SUMMON: //28
case SPELL_EFFECT_TRIGGER_MISSILE: //32
case SPELL_EFFECT_TRANS_DOOR: //50 summon object
case SPELL_EFFECT_SUMMON_PET: //56
case SPELL_EFFECT_ADD_FARSIGHT: //72
case SPELL_EFFECT_SUMMON_OBJECT_WILD: //76
//case SPELL_EFFECT_SUMMON_CRITTER: //97 not 303
case SPELL_EFFECT_SUMMON_OBJECT_SLOT1: //104
case SPELL_EFFECT_SUMMON_OBJECT_SLOT2: //105
case SPELL_EFFECT_SUMMON_OBJECT_SLOT3: //106
case SPELL_EFFECT_SUMMON_OBJECT_SLOT4: //107
case SPELL_EFFECT_SUMMON_DEAD_PET: //109
case SPELL_EFFECT_TRIGGER_SPELL_2: //151 ritual of summon
EffectTargetType[i] = SPELL_REQUIRE_DEST;
break;
case SPELL_EFFECT_PARRY: // 0
case SPELL_EFFECT_BLOCK: // 0
case SPELL_EFFECT_SKILL: // always with dummy 3 as A
//case SPELL_EFFECT_LEARN_SPELL: // 0 may be 5 pet
case SPELL_EFFECT_TRADE_SKILL: // 0 or 1
case SPELL_EFFECT_PROFICIENCY: // 0
EffectTargetType[i] = SPELL_REQUIRE_NONE;
break;
case SPELL_EFFECT_ENCHANT_ITEM:
case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
case SPELL_EFFECT_DISENCHANT:
//in 243 this is 0, in 309 it is 1
//so both item target and unit target is pushed, and cause crash
//case SPELL_EFFECT_FEED_PET:
case SPELL_EFFECT_PROSPECTING:
case SPELL_EFFECT_MILLING:
case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
EffectTargetType[i] = SPELL_REQUIRE_ITEM;
break;
//caster must be pushed otherwise no sound
case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY:
case SPELL_EFFECT_APPLY_AREA_AURA_PET:
case SPELL_EFFECT_APPLY_AREA_AURA_OWNER:
case SPELL_EFFECT_APPLY_AREA_AURA_RAID:
case SPELL_EFFECT_CHARGE:
case SPELL_EFFECT_CHARGE_DEST:
case SPELL_EFFECT_JUMP:
case SPELL_EFFECT_JUMP_DEST:
case SPELL_EFFECT_LEAP_BACK:
EffectTargetType[i] = SPELL_REQUIRE_CASTER;
break;
//case SPELL_EFFECT_WMO_DAMAGE:
//case SPELL_EFFECT_WMO_REPAIR:
//case SPELL_EFFECT_WMO_CHANGE:
// EffectTargetType[i] = SPELL_REQUIRE_GOBJECT;
// break;
default:
EffectTargetType[i] = SPELL_REQUIRE_UNIT;
break;
}
}
for (int i = 0; i < TOTAL_SPELL_TARGETS; ++i)
{
switch(i)
{
case TARGET_UNIT_CASTER:
case TARGET_UNIT_CASTER_FISHING:
case TARGET_UNIT_MASTER:
case TARGET_UNIT_PET:
case TARGET_UNIT_PARTY_CASTER:
case TARGET_UNIT_RAID_CASTER:
case TARGET_UNIT_VEHICLE:
case TARGET_UNIT_PASSENGER_0:
case TARGET_UNIT_PASSENGER_1:
case TARGET_UNIT_PASSENGER_2:
case TARGET_UNIT_PASSENGER_3:
case TARGET_UNIT_PASSENGER_4:
case TARGET_UNIT_PASSENGER_5:
case TARGET_UNIT_PASSENGER_6:
case TARGET_UNIT_PASSENGER_7:
case TARGET_UNIT_SUMMONER:
SpellTargetType[i] = TARGET_TYPE_UNIT_CASTER;
break;
case TARGET_UNIT_TARGET_PUPPET:
case TARGET_UNIT_TARGET_ALLY:
case TARGET_UNIT_TARGET_RAID:
case TARGET_UNIT_TARGET_ANY:
case TARGET_UNIT_TARGET_ENEMY:
case TARGET_UNIT_TARGET_PARTY:
case TARGET_UNIT_PARTY_TARGET:
case TARGET_UNIT_CLASS_TARGET:
case TARGET_UNIT_CHAINHEAL:
SpellTargetType[i] = TARGET_TYPE_UNIT_TARGET;
break;
case TARGET_UNIT_NEARBY_ENEMY:
case TARGET_UNIT_NEARBY_ALLY:
case TARGET_UNIT_NEARBY_ALLY_UNK:
case TARGET_UNIT_NEARBY_ENTRY:
case TARGET_UNIT_NEARBY_RAID:
case TARGET_GAMEOBJECT_NEARBY_ENTRY:
SpellTargetType[i] = TARGET_TYPE_UNIT_NEARBY;
break;
case TARGET_UNIT_AREA_ENEMY_SRC:
case TARGET_UNIT_AREA_ALLY_SRC:
case TARGET_UNIT_AREA_ENTRY_SRC:
case TARGET_UNIT_AREA_PARTY_SRC:
case TARGET_GAMEOBJECT_AREA_SRC:
SpellTargetType[i] = TARGET_TYPE_AREA_SRC;
break;
case TARGET_UNIT_AREA_ENEMY_DST:
case TARGET_UNIT_AREA_ALLY_DST:
case TARGET_UNIT_AREA_ENTRY_DST:
case TARGET_UNIT_AREA_PARTY_DST:
case TARGET_GAMEOBJECT_AREA_DST:
SpellTargetType[i] = TARGET_TYPE_AREA_DST;
break;
case TARGET_UNIT_CONE_ENEMY:
case TARGET_UNIT_CONE_ALLY:
case TARGET_UNIT_CONE_ENTRY:
case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
case TARGET_UNIT_AREA_PATH:
case TARGET_GAMEOBJECT_AREA_PATH:
SpellTargetType[i] = TARGET_TYPE_AREA_CONE;
break;
case TARGET_DST_CASTER:
case TARGET_SRC_CASTER:
case TARGET_MINION:
case TARGET_DEST_CASTER_FRONT_LEAP:
case TARGET_DEST_CASTER_FRONT:
case TARGET_DEST_CASTER_BACK:
case TARGET_DEST_CASTER_RIGHT:
case TARGET_DEST_CASTER_LEFT:
case TARGET_DEST_CASTER_FRONT_LEFT:
case TARGET_DEST_CASTER_BACK_LEFT:
case TARGET_DEST_CASTER_BACK_RIGHT:
case TARGET_DEST_CASTER_FRONT_RIGHT:
case TARGET_DEST_CASTER_RANDOM:
case TARGET_DEST_CASTER_RADIUS:
SpellTargetType[i] = TARGET_TYPE_DEST_CASTER;
break;
case TARGET_DST_TARGET_ENEMY:
case TARGET_DEST_TARGET_ANY:
case TARGET_DEST_TARGET_FRONT:
case TARGET_DEST_TARGET_BACK:
case TARGET_DEST_TARGET_RIGHT:
case TARGET_DEST_TARGET_LEFT:
case TARGET_DEST_TARGET_FRONT_LEFT:
case TARGET_DEST_TARGET_BACK_LEFT:
case TARGET_DEST_TARGET_BACK_RIGHT:
case TARGET_DEST_TARGET_FRONT_RIGHT:
case TARGET_DEST_TARGET_RANDOM:
case TARGET_DEST_TARGET_RADIUS:
SpellTargetType[i] = TARGET_TYPE_DEST_TARGET;
break;
case TARGET_DEST_DYNOBJ_ENEMY:
case TARGET_DEST_DYNOBJ_ALLY:
case TARGET_DEST_DYNOBJ_NONE:
case TARGET_DEST_DEST:
case TARGET_DEST_TRAJ:
case TARGET_DEST_DEST_FRONT_LEFT:
case TARGET_DEST_DEST_BACK_LEFT:
case TARGET_DEST_DEST_BACK_RIGHT:
case TARGET_DEST_DEST_FRONT_RIGHT:
case TARGET_DEST_DEST_FRONT:
case TARGET_DEST_DEST_BACK:
case TARGET_DEST_DEST_RIGHT:
case TARGET_DEST_DEST_LEFT:
case TARGET_DEST_DEST_RANDOM:
case TARGET_DEST_DEST_RANDOM_DIR_DIST:
SpellTargetType[i] = TARGET_TYPE_DEST_DEST;
break;
case TARGET_DST_DB:
case TARGET_DST_HOME:
case TARGET_DST_NEARBY_ENTRY:
SpellTargetType[i] = TARGET_TYPE_DEST_SPECIAL;
break;
case TARGET_UNIT_CHANNEL_TARGET:
case TARGET_DEST_CHANNEL_TARGET:
case TARGET_DEST_CHANNEL_CASTER:
SpellTargetType[i] = TARGET_TYPE_CHANNEL;
break;
default:
SpellTargetType[i] = TARGET_TYPE_DEFAULT;
}
}
for (int32 i = 0; i < TOTAL_SPELL_TARGETS; ++i)
{
switch(i)
{
case TARGET_UNIT_AREA_ENEMY_DST:
case TARGET_UNIT_AREA_ENEMY_SRC:
case TARGET_UNIT_AREA_ALLY_DST:
case TARGET_UNIT_AREA_ALLY_SRC:
case TARGET_UNIT_AREA_ENTRY_DST:
case TARGET_UNIT_AREA_ENTRY_SRC:
case TARGET_UNIT_AREA_PARTY_DST:
case TARGET_UNIT_AREA_PARTY_SRC:
case TARGET_UNIT_PARTY_TARGET:
case TARGET_UNIT_PARTY_CASTER:
case TARGET_UNIT_CONE_ENEMY:
case TARGET_UNIT_CONE_ALLY:
case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
case TARGET_UNIT_AREA_PATH:
case TARGET_GAMEOBJECT_AREA_PATH:
case TARGET_UNIT_RAID_CASTER:
IsAreaEffectTarget[i] = true;
break;
default:
IsAreaEffectTarget[i] = false;
break;
}
}
}
SpellMgr::~SpellMgr()
{
}
bool SpellMgr::IsSrcTargetSpell(SpellEntry const *spellInfo) const
{
for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
{
if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_AREA_SRC || SpellTargetType[spellInfo->EffectImplicitTargetB[i]] == TARGET_TYPE_AREA_SRC)
return true;
}
return false;
}
int32 GetSpellDuration(SpellEntry const *spellInfo)
{
if (!spellInfo)
return 0;
SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
if (!du)
return 0;
return (du->Duration[0] == -1) ? -1 : abs(du->Duration[0]);
}
int32 GetSpellMaxDuration(SpellEntry const *spellInfo)
{
if (!spellInfo)
return 0;
SpellDurationEntry const *du = sSpellDurationStore.LookupEntry(spellInfo->DurationIndex);
if (!du)
return 0;
return (du->Duration[2] == -1) ? -1 : abs(du->Duration[2]);
}
uint32 GetDispelChance(Unit* auraCaster, Unit* target, uint32 spellId, bool offensive, bool *result)
{
// we assume that aura dispel chance is 100% on start
// need formula for level difference based chance
int32 resist_chance = 0;
// Apply dispel mod from aura caster
if (auraCaster)
if (Player* modOwner = auraCaster->GetSpellModOwner())
modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_DISPEL_CHANCE, resist_chance);
// Dispel resistance from target SPELL_AURA_MOD_DISPEL_RESIST
// Only affects offensive dispels
if (offensive && target)
resist_chance += target->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
// Try dispel
if (result)
*result = !roll_chance_i(resist_chance);
resist_chance = resist_chance < 0 ? 0 : resist_chance;
resist_chance = resist_chance > 100 ? 100 : resist_chance;
return 100 - resist_chance;
}
uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell * spell)
{
SpellCastTimesEntry const *spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->CastingTimeIndex);
// not all spells have cast time index and this is all is pasiive abilities
if (!spellCastTimeEntry)
return 0;
int32 castTime = spellCastTimeEntry->CastTime;
if (spell && spell->GetCaster())
spell->GetCaster()->ModSpellCastTime(spellInfo, castTime, spell);
if (spellInfo->Attributes & SPELL_ATTR0_REQ_AMMO && (!spell || !(spell->IsAutoRepeat())))
castTime += 500;
return (castTime > 0) ? uint32(castTime) : 0;
}
bool IsPassiveSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
return IsPassiveSpell(spellInfo);
}
bool IsPassiveSpell(SpellEntry const * spellInfo)
{
if (spellInfo->Attributes & SPELL_ATTR0_PASSIVE)
return true;
return false;
}
bool IsAutocastableSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
if (spellInfo->Attributes & SPELL_ATTR0_PASSIVE)
return false;
if (spellInfo->AttributesEx & SPELL_ATTR1_UNAUTOCASTABLE_BY_PET)
return false;
return true;
}
bool IsHigherHankOfSpell(uint32 spellId_1, uint32 spellId_2)
{
return sSpellMgr->GetSpellRank(spellId_1) < sSpellMgr->GetSpellRank(spellId_2);
}
uint32 CalculatePowerCost(SpellEntry const * spellInfo, Unit const * caster, SpellSchoolMask schoolMask)
{
// Spell drain all exist power on cast (Only paladin lay of Hands)
if (spellInfo->AttributesEx & SPELL_ATTR1_DRAIN_ALL_POWER)
{
// If power type - health drain all
if (spellInfo->powerType == POWER_HEALTH)
return caster->GetHealth();
// Else drain all power
if (spellInfo->powerType < MAX_POWERS)
return caster->GetPower(Powers(spellInfo->powerType));
sLog->outError("CalculateManaCost: Unknown power type '%d' in spell %d", spellInfo->powerType, spellInfo->Id);
return 0;
}
// Base powerCost
int32 powerCost = spellInfo->manaCost;
// PCT cost from total amount
if (spellInfo->ManaCostPercentage)
{
switch (spellInfo->powerType)
{
// health as power used
case POWER_HEALTH:
powerCost += int32(CalculatePctU(caster->GetCreateHealth(), spellInfo->ManaCostPercentage));
break;
case POWER_MANA:
powerCost += int32(CalculatePctU(caster->GetCreateMana(), spellInfo->ManaCostPercentage));
break;
case POWER_RAGE:
case POWER_FOCUS:
case POWER_ENERGY:
case POWER_HAPPINESS:
powerCost += int32(CalculatePctU(caster->GetMaxPower(Powers(spellInfo->powerType)), spellInfo->ManaCostPercentage));
break;
case POWER_RUNE:
case POWER_RUNIC_POWER:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "CalculateManaCost: Not implemented yet!");
break;
default:
sLog->outError("CalculateManaCost: Unknown power type '%d' in spell %d", spellInfo->powerType, spellInfo->Id);
return 0;
}
}
SpellSchools school = GetFirstSchoolInMask(schoolMask);
// Flat mod from caster auras by spell school
powerCost += caster->GetInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + school);
// Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost)
if (spellInfo->AttributesEx4 & SPELL_ATTR4_SPELL_VS_EXTEND_COST)
powerCost += caster->GetAttackTime(OFF_ATTACK)/100;
// Apply cost mod by spell
if (Player* modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COST, powerCost);
if (spellInfo->Attributes & SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION)
powerCost = int32(powerCost/ (1.117f* spellInfo->spellLevel / caster->getLevel() -0.1327f));
// PCT mod from user auras by school
powerCost = int32(powerCost * (1.0f+caster->GetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+school)));
if (powerCost < 0)
powerCost = 0;
return powerCost;
}
Unit* GetTriggeredSpellCaster(SpellEntry const * spellInfo, Unit * caster, Unit * target)
{
for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i)
{
if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET
|| SpellTargetType[spellInfo->EffectImplicitTargetB[i]] == TARGET_TYPE_UNIT_TARGET
|| SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_CHANNEL
|| SpellTargetType[spellInfo->EffectImplicitTargetB[i]] == TARGET_TYPE_CHANNEL
|| SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_DEST_TARGET
|| SpellTargetType[spellInfo->EffectImplicitTargetB[i]] == TARGET_TYPE_DEST_TARGET)
return caster;
}
return target;
}
AuraState GetSpellAuraState(SpellEntry const * spellInfo)
{
// Seals
if (IsSealSpell(spellInfo))
return AURA_STATE_JUDGEMENT;
// Conflagrate aura state on Immolate and Shadowflame
if (spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK &&
// Immolate
((spellInfo->SpellFamilyFlags[0] & 4) ||
// Shadowflame
(spellInfo->SpellFamilyFlags[2] & 2)))
return AURA_STATE_CONFLAGRATE;
// Faerie Fire (druid versions)
if (spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && spellInfo->SpellFamilyFlags[0] & 0x400)
return AURA_STATE_FAERIE_FIRE;
// Sting (hunter's pet ability)
if (spellInfo->Category == 1133)
return AURA_STATE_FAERIE_FIRE;
// Victorious
if (spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellFamilyFlags[1] & 0x00040000)
return AURA_STATE_WARRIOR_VICTORY_RUSH;
// Swiftmend state on Regrowth & Rejuvenation
if (spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && spellInfo->SpellFamilyFlags[0] & 0x50)
return AURA_STATE_SWIFTMEND;
// Deadly poison aura state
if (spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && spellInfo->SpellFamilyFlags[0] & 0x10000)
return AURA_STATE_DEADLY_POISON;
// Enrage aura state
if (spellInfo->Dispel == DISPEL_ENRAGE)
return AURA_STATE_ENRAGE;
// Bleeding aura state
if (GetAllSpellMechanicMask(spellInfo) & 1<<MECHANIC_BLEED)
return AURA_STATE_BLEEDING;
if (GetSpellSchoolMask(spellInfo) & SPELL_SCHOOL_MASK_FROST)
{
for (uint8 i = 0; i<MAX_SPELL_EFFECTS; ++i)
{
if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STUN
|| spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_ROOT)
return AURA_STATE_FROZEN;
}
}
return AURA_STATE_NONE;
}
SpellSpecific GetSpellSpecific(SpellEntry const * spellInfo)
{
switch(spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
// Food / Drinks (mostly)
if (spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
bool food = false;
bool drink = false;
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch(spellInfo->EffectApplyAuraName[i])
{
// Food
case SPELL_AURA_MOD_REGEN:
case SPELL_AURA_OBS_MOD_HEALTH:
food = true;
break;
// Drink
case SPELL_AURA_MOD_POWER_REGEN:
case SPELL_AURA_OBS_MOD_POWER:
drink = true;
break;
default:
break;
}
}
if (food && drink)
return SPELL_SPECIFIC_FOOD_AND_DRINK;
else if (food)
return SPELL_SPECIFIC_FOOD;
else if (drink)
return SPELL_SPECIFIC_DRINK;
}
// scrolls effects
else
{
uint32 firstSpell = sSpellMgr->GetFirstSpellInChain(spellInfo->Id);
switch (firstSpell)
{
case 8118: // Strength
case 8099: // Stamina
case 8112: // Spirit
case 8096: // Intellect
case 8115: // Agility
case 8091: // Armor
return SPELL_SPECIFIC_SCROLL;
case 12880: // Enrage (Enrage)
case 57518: // Enrage (Wrecking Crew)
return SPELL_SPECIFIC_WARRIOR_ENRAGE;
}
}
break;
}
case SPELLFAMILY_MAGE:
{
// family flags 18(Molten), 25(Frost/Ice), 28(Mage)
if (spellInfo->SpellFamilyFlags[0] & 0x12040000)
return SPELL_SPECIFIC_MAGE_ARMOR;
// Arcane brillance and Arcane intelect (normal check fails because of flags difference)
if (spellInfo->SpellFamilyFlags[0] & 0x400)
return SPELL_SPECIFIC_MAGE_ARCANE_BRILLANCE;
if ((spellInfo->SpellFamilyFlags[0] & 0x1000000) && spellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOD_CONFUSE)
return SPELL_SPECIFIC_MAGE_POLYMORPH;
break;
}
case SPELLFAMILY_WARRIOR:
{
if (spellInfo->Id == 12292) // Death Wish
return SPELL_SPECIFIC_WARRIOR_ENRAGE;
break;
}
case SPELLFAMILY_WARLOCK:
{
// only warlock curses have this
if (spellInfo->Dispel == DISPEL_CURSE)
return SPELL_SPECIFIC_CURSE;
// Warlock (Demon Armor | Demon Skin | Fel Armor)
if (spellInfo->SpellFamilyFlags[1] & 0x20000020 || spellInfo->SpellFamilyFlags[2] & 0x00000010)
return SPELL_SPECIFIC_WARLOCK_ARMOR;
//seed of corruption and corruption
if (spellInfo->SpellFamilyFlags[1] & 0x10 || spellInfo->SpellFamilyFlags[0] & 0x2)
return SPELL_SPECIFIC_WARLOCK_CORRUPTION;
break;
}
case SPELLFAMILY_PRIEST:
{
// Divine Spirit and Prayer of Spirit
if (spellInfo->SpellFamilyFlags[0] & 0x20)
return SPELL_SPECIFIC_PRIEST_DIVINE_SPIRIT;
break;
}
case SPELLFAMILY_HUNTER:
{
// only hunter stings have this
if (spellInfo->Dispel == DISPEL_POISON)
return SPELL_SPECIFIC_STING;
// only hunter aspects have this (but not all aspects in hunter family)
if (spellInfo->SpellFamilyFlags.HasFlag(0x00380000, 0x00440000, 0x00001010))
return SPELL_SPECIFIC_ASPECT;
break;
}
case SPELLFAMILY_PALADIN:
{
if (IsSealSpell(spellInfo))
return SPELL_SPECIFIC_SEAL;
if (spellInfo->SpellFamilyFlags[0] & 0x00002190)
return SPELL_SPECIFIC_HAND;
// Judgement of Wisdom, Judgement of Light, Judgement of Justice
if (spellInfo->Id == 20184 || spellInfo->Id == 20185 || spellInfo->Id == 20186)
return SPELL_SPECIFIC_JUDGEMENT;
// only paladin auras have this (for palaldin class family)
if (spellInfo->SpellFamilyFlags[2] & 0x00000020)
return SPELL_SPECIFIC_AURA;
break;
}
case SPELLFAMILY_SHAMAN:
{
if (IsElementalShield(spellInfo))
return SPELL_SPECIFIC_ELEMENTAL_SHIELD;
break;
}
case SPELLFAMILY_DEATHKNIGHT:
if (spellInfo->Id == 48266 || spellInfo->Id == 48263 || spellInfo->Id == 48265)
//if (spellInfo->Category == 47)
return SPELL_SPECIFIC_PRESENCE;
break;
}
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
{
switch(spellInfo->EffectApplyAuraName[i])
{
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_MOD_POSSESS_PET:
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_AOE_CHARM:
return SPELL_SPECIFIC_CHARM;
case SPELL_AURA_TRACK_CREATURES:
case SPELL_AURA_TRACK_RESOURCES:
case SPELL_AURA_TRACK_STEALTHED:
return SPELL_SPECIFIC_TRACKER;
case SPELL_AURA_PHASE:
return SPELL_SPECIFIC_PHASE;
}
}
}
return SPELL_SPECIFIC_NORMAL;
}
// target not allow have more one spell specific from same caster
bool IsSingleFromSpellSpecificPerCaster(SpellSpecific spellSpec1,SpellSpecific spellSpec2)
{
switch(spellSpec1)
{
case SPELL_SPECIFIC_SEAL:
case SPELL_SPECIFIC_HAND:
case SPELL_SPECIFIC_AURA:
case SPELL_SPECIFIC_STING:
case SPELL_SPECIFIC_CURSE:
case SPELL_SPECIFIC_ASPECT:
case SPELL_SPECIFIC_JUDGEMENT:
case SPELL_SPECIFIC_WARLOCK_CORRUPTION:
return spellSpec1 == spellSpec2;
default:
return false;
}
}
bool IsSingleFromSpellSpecificPerTarget(SpellSpecific spellSpec1, SpellSpecific spellSpec2)
{
switch(spellSpec1)
{
case SPELL_SPECIFIC_PHASE:
case SPELL_SPECIFIC_TRACKER:
case SPELL_SPECIFIC_WARLOCK_ARMOR:
case SPELL_SPECIFIC_MAGE_ARMOR:
case SPELL_SPECIFIC_ELEMENTAL_SHIELD:
case SPELL_SPECIFIC_MAGE_POLYMORPH:
case SPELL_SPECIFIC_PRESENCE:
case SPELL_SPECIFIC_CHARM:
case SPELL_SPECIFIC_SCROLL:
case SPELL_SPECIFIC_WARRIOR_ENRAGE:
case SPELL_SPECIFIC_MAGE_ARCANE_BRILLANCE:
case SPELL_SPECIFIC_PRIEST_DIVINE_SPIRIT:
return spellSpec1 == spellSpec2;
case SPELL_SPECIFIC_FOOD:
return spellSpec2 == SPELL_SPECIFIC_FOOD
|| spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK;
case SPELL_SPECIFIC_DRINK:
return spellSpec2 == SPELL_SPECIFIC_DRINK
|| spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK;
case SPELL_SPECIFIC_FOOD_AND_DRINK:
return spellSpec2 == SPELL_SPECIFIC_FOOD
|| spellSpec2 == SPELL_SPECIFIC_DRINK
|| spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK;
default:
return false;
}
}
bool IsPositiveTarget(uint32 targetA, uint32 targetB)
{
// non-positive targets
switch(targetA)
{
case TARGET_UNIT_NEARBY_ENEMY:
case TARGET_UNIT_TARGET_ENEMY:
case TARGET_UNIT_AREA_ENEMY_SRC:
case TARGET_UNIT_AREA_ENEMY_DST:
case TARGET_UNIT_CONE_ENEMY:
case TARGET_DEST_DYNOBJ_ENEMY:
case TARGET_DST_TARGET_ENEMY:
return false;
default:
break;
}
if (targetB)
return IsPositiveTarget(targetB, 0);
return true;
}
bool SpellMgr::_isPositiveEffect(uint32 spellId, uint32 effIndex, bool deep) const
{
SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
if (!spellproto) return false;
// not found a single positive spell with this attribute
if (spellproto->Attributes & SPELL_ATTR0_NEGATIVE_1)
return false;
switch (spellproto->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (spellId)
{
case 34700: // Allergic Reaction
case 61987: // Avenging Wrath Marker
case 61988: // Divine Shield exclude aura
case 63322: // Saronite Vapors
return false;
case 30877: // Tag Murloc
return true;
default:
break;
}
break;
case SPELLFAMILY_MAGE:
// Amplify Magic, Dampen Magic
if (spellproto->SpellFamilyFlags[0] == 0x00002000)
return true;
// Ignite
if (spellproto->SpellIconID == 45)
return true;
break;
case SPELLFAMILY_WARRIOR:
// Shockwave
if (spellId == 46968)
return false;
break;
case SPELLFAMILY_PRIEST:
switch (spellId)
{
case 64844: // Divine Hymn
case 64904: // Hymn of Hope
case 47585: // Dispersion
return true;
default:
break;
}
break;
case SPELLFAMILY_HUNTER:
// Aspect of the Viper
if (spellId == 34074)
return true;
break;
case SPELLFAMILY_SHAMAN:
if (spellId == 30708)
return false;
break;
default:
break;
}
switch (spellproto->Mechanic)
{
case MECHANIC_IMMUNE_SHIELD:
return true;
default:
break;
}
// Special case: effects which determine positivity of whole spell
for (uint8 i = 0; i<MAX_SPELL_EFFECTS; ++i)
{
if (spellproto->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
return true;
}
switch(spellproto->Effect[effIndex])
{
case SPELL_EFFECT_DUMMY:
// some explicitly required dummy effect sets
switch(spellId)
{
case 28441: return false; // AB Effect 000
default:
break;
}
break;
// always positive effects (check before target checks that provided non-positive result in some case for positive effects)
case SPELL_EFFECT_HEAL:
case SPELL_EFFECT_LEARN_SPELL:
case SPELL_EFFECT_SKILL_STEP:
case SPELL_EFFECT_HEAL_PCT:
case SPELL_EFFECT_ENERGIZE_PCT:
return true;
// non-positive aura use
case SPELL_EFFECT_APPLY_AURA:
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
{
switch(spellproto->EffectApplyAuraName[effIndex])
{
case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from bas point sign (negative -> negative)
case SPELL_AURA_MOD_STAT:
case SPELL_AURA_MOD_SKILL:
case SPELL_AURA_MOD_DODGE_PERCENT:
case SPELL_AURA_MOD_HEALING_PCT:
case SPELL_AURA_MOD_HEALING_DONE:
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE:
if (SpellMgr::CalculateSpellEffectAmount(spellproto, effIndex) < 0)
return false;
break;
case SPELL_AURA_MOD_DAMAGE_TAKEN: // dependent from bas point sign (positive -> negative)
if (SpellMgr::CalculateSpellEffectAmount(spellproto, effIndex) > 0)
return false;
break;
case SPELL_AURA_MOD_CRIT_PCT:
case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
if (SpellMgr::CalculateSpellEffectAmount(spellproto, effIndex) > 0)
return true; // some expected positive spells have SPELL_ATTR1_NEGATIVE
break;
case SPELL_AURA_ADD_TARGET_TRIGGER:
return true;
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
if (!deep)
{
uint32 spellTriggeredId = spellproto->EffectTriggerSpell[effIndex];
SpellEntry const *spellTriggeredProto = sSpellStore.LookupEntry(spellTriggeredId);
if (spellTriggeredProto)
{
// non-positive targets of main spell return early
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!spellTriggeredProto->Effect[i])
continue;
// if non-positive trigger cast targeted to positive target this main cast is non-positive
// this will place this spell auras as debuffs
if (IsPositiveTarget(spellTriggeredProto->EffectImplicitTargetA[effIndex],spellTriggeredProto->EffectImplicitTargetB[effIndex]) && !_isPositiveEffect(spellTriggeredId,i, true))
return false;
}
}
}
case SPELL_AURA_PROC_TRIGGER_SPELL:
// many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example)
break;
case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment.
if (effIndex == 0 && spellproto->Effect[1] == 0 && spellproto->Effect[2] == 0)
return false; // but all single stun aura spells is negative
break;
case SPELL_AURA_MOD_PACIFY_SILENCE:
if (spellproto->Id == 24740) // Wisp Costume
return true;
return false;
case SPELL_AURA_MOD_ROOT:
case SPELL_AURA_MOD_SILENCE:
case SPELL_AURA_GHOST:
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_MOD_STALKED:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
case SPELL_AURA_PREVENT_RESSURECTION:
return false;
case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also.
// part of negative spell if casted at self (prevent cancel)
if (spellproto->EffectImplicitTargetA[effIndex] == TARGET_UNIT_CASTER)
return false;
break;
case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also
// part of positive spell if casted at self
if (spellproto->EffectImplicitTargetA[effIndex] != TARGET_UNIT_CASTER)
return false;
// but not this if this first effect (didn't find better check)
if (spellproto->Attributes & SPELL_ATTR0_NEGATIVE_1 && effIndex == 0)
return false;
break;
case SPELL_AURA_MECHANIC_IMMUNITY:
{
// non-positive immunities
switch(spellproto->EffectMiscValue[effIndex])
{
case MECHANIC_BANDAGE:
case MECHANIC_SHIELD:
case MECHANIC_MOUNT:
case MECHANIC_INVULNERABILITY:
return false;
default:
break;
}
} break;
case SPELL_AURA_ADD_FLAT_MODIFIER: // mods
case SPELL_AURA_ADD_PCT_MODIFIER:
{
// non-positive mods
switch(spellproto->EffectMiscValue[effIndex])
{
case SPELLMOD_COST: // dependent from bas point sign (negative -> positive)
if (SpellMgr::CalculateSpellEffectAmount(spellproto, effIndex) > 0)
{
if (!deep)
{
bool negative = true;
for (uint8 i=0; i<MAX_SPELL_EFFECTS; ++i)
{
if (i != effIndex)
if (_isPositiveEffect(spellId, i, true))
{
negative = false;
break;
}
}
if (negative)
return false;
}
}
break;
default:
break;
}
} break;
default:
break;
}
break;
}
default:
break;
}
// non-positive targets
if (!IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex]))
return false;
// AttributesEx check
if (spellproto->AttributesEx & SPELL_ATTR1_NEGATIVE)
return false;
if (!deep && spellproto->EffectTriggerSpell[effIndex]
&& !spellproto->EffectApplyAuraName[effIndex]
&& IsPositiveTarget(spellproto->EffectImplicitTargetA[effIndex],spellproto->EffectImplicitTargetB[effIndex])
&& !_isPositiveSpell(spellproto->EffectTriggerSpell[effIndex], true))
return false;
// ok, positive
return true;
}
bool IsPositiveSpell(uint32 spellId)
{
if (!sSpellStore.LookupEntry(spellId)) // non-existing spells
return false;
return !(sSpellMgr->GetSpellCustomAttr(spellId) & SPELL_ATTR0_CU_NEGATIVE);
}
bool IsPositiveEffect(uint32 spellId, uint32 effIndex)
{
if (!sSpellStore.LookupEntry(spellId))
return false;
switch(effIndex)
{
default:
case 0: return !(sSpellMgr->GetSpellCustomAttr(spellId) & SPELL_ATTR0_CU_NEGATIVE_EFF0);
case 1: return !(sSpellMgr->GetSpellCustomAttr(spellId) & SPELL_ATTR0_CU_NEGATIVE_EFF1);
case 2: return !(sSpellMgr->GetSpellCustomAttr(spellId) & SPELL_ATTR0_CU_NEGATIVE_EFF2);
}
}
bool SpellMgr::_isPositiveSpell(uint32 spellId, bool deep) const
{
SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
if (!spellproto) return false;
// spells with at least one negative effect are considered negative
// some self-applied spells have negative effects but in self casting case negative check ignored.
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (!_isPositiveEffect(spellId, i, deep))
return false;
return true;
}
bool IsSingleTargetSpell(SpellEntry const *spellInfo)
{
// all other single target spells have if it has AttributesEx5
if (spellInfo->AttributesEx5 & SPELL_ATTR5_SINGLE_TARGET_SPELL)
return true;
switch(GetSpellSpecific(spellInfo))
{
case SPELL_SPECIFIC_JUDGEMENT:
return true;
default:
break;
}
return false;
}
bool IsSingleTargetSpells(SpellEntry const *spellInfo1, SpellEntry const *spellInfo2)
{
// TODO - need better check
// Equal icon and spellfamily
if (spellInfo1->SpellFamilyName == spellInfo2->SpellFamilyName &&
spellInfo1->SpellIconID == spellInfo2->SpellIconID)
return true;
// TODO - need found Judgements rule
SpellSpecific spec1 = GetSpellSpecific(spellInfo1);
// spell with single target specific types
switch(spec1)
{
case SPELL_SPECIFIC_JUDGEMENT:
case SPELL_SPECIFIC_MAGE_POLYMORPH:
if (GetSpellSpecific(spellInfo2) == spec1)
return true;
break;
default:
break;
}
return false;
}
SpellCastResult GetErrorAtShapeshiftedCast (SpellEntry const *spellInfo, uint32 form)
{
// talents that learn spells can have stance requirements that need ignore
// (this requirement only for client-side stance show in talent description)
if (GetTalentSpellCost(spellInfo->Id) > 0 &&
(spellInfo->Effect[0] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[1] == SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[2] == SPELL_EFFECT_LEARN_SPELL))
return SPELL_CAST_OK;
uint32 stanceMask = (form ? 1 << (form - 1) : 0);
if (stanceMask & spellInfo->StancesNot) // can explicitly not be casted in this stance
return SPELL_FAILED_NOT_SHAPESHIFT;
if (stanceMask & spellInfo->Stances) // can explicitly be casted in this stance
return SPELL_CAST_OK;
bool actAsShifted = false;
SpellShapeshiftEntry const *shapeInfo = NULL;
if (form > 0)
{
shapeInfo = sSpellShapeshiftStore.LookupEntry(form);
if (!shapeInfo)
{
sLog->outError("GetErrorAtShapeshiftedCast: unknown shapeshift %u", form);
return SPELL_CAST_OK;
}
actAsShifted = !(shapeInfo->flags1 & 1); // shapeshift acts as normal form for spells
}
if (actAsShifted)
{
if (spellInfo->Attributes & SPELL_ATTR0_NOT_SHAPESHIFT) // not while shapeshifted
return SPELL_FAILED_NOT_SHAPESHIFT;
else if (spellInfo->Stances != 0) // needs other shapeshift
return SPELL_FAILED_ONLY_SHAPESHIFT;
}
else
{
// needs shapeshift
if (!(spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_NEED_SHAPESHIFT) && spellInfo->Stances != 0)
return SPELL_FAILED_ONLY_SHAPESHIFT;
}
// Check if stance disables cast of not-stance spells
// Example: cannot cast any other spells in zombie or ghoul form
// TODO: Find a way to disable use of these spells clientside
if (shapeInfo && shapeInfo->flags1 & 0x400)
{
if (!(stanceMask & spellInfo->Stances))
return SPELL_FAILED_ONLY_SHAPESHIFT;
}
return SPELL_CAST_OK;
}
void SpellMgr::LoadSpellTargetPositions()
{
uint32 oldMSTime = getMSTime();
mSpellTargetPositions.clear(); // need for reload case
// 0 1 2 3 4 5
QueryResult result = WorldDatabase.Query("SELECT id, target_map, target_position_x, target_position_y, target_position_z, target_orientation FROM spell_target_position");
if (!result)
{
sLog->outString(">> Loaded 0 spell target coordinates. DB table `spell_target_position` is empty.");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field *fields = result->Fetch();
uint32 Spell_ID = fields[0].GetUInt32();
SpellTargetPosition st;
st.target_mapId = fields[1].GetUInt32();
st.target_X = fields[2].GetFloat();
st.target_Y = fields[3].GetFloat();
st.target_Z = fields[4].GetFloat();
st.target_Orientation = fields[5].GetFloat();
MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId);
if (!mapEntry)
{
sLog->outErrorDb("Spell (ID:%u) target map (ID: %u) does not exist in `Map.dbc`.",Spell_ID,st.target_mapId);
continue;
}
if (st.target_X==0 && st.target_Y==0 && st.target_Z==0)
{
sLog->outErrorDb("Spell (ID:%u) target coordinates not provided.",Spell_ID);
continue;
}
SpellEntry const* spellInfo = sSpellStore.LookupEntry(Spell_ID);
if (!spellInfo)
{
sLog->outErrorDb("Spell (ID:%u) listed in `spell_target_position` does not exist.",Spell_ID);
continue;
}
bool found = false;
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spellInfo->EffectImplicitTargetA[i] == TARGET_DST_DB || spellInfo->EffectImplicitTargetB[i] == TARGET_DST_DB)
{
// additional requirements
if (spellInfo->Effect[i]==SPELL_EFFECT_BIND && spellInfo->EffectMiscValue[i])
{
uint32 area_id = sMapMgr->GetAreaId(st.target_mapId, st.target_X, st.target_Y, st.target_Z);
if (area_id != uint32(spellInfo->EffectMiscValue[i]))
{
sLog->outErrorDb("Spell (Id: %u) listed in `spell_target_position` expected point to zone %u bit point to zone %u.",Spell_ID, spellInfo->EffectMiscValue[i], area_id);
break;
}
}
found = true;
break;
}
}
if (!found)
{
sLog->outErrorDb("Spell (Id: %u) listed in `spell_target_position` does not have target TARGET_DST_DB (17).",Spell_ID);
continue;
}
mSpellTargetPositions[Spell_ID] = st;
++count;
} while (result->NextRow());
// Check all spells
for (uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
{
SpellEntry const * spellInfo = sSpellStore.LookupEntry(i);
if (!spellInfo)
continue;
bool found = false;
for (int j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
switch(spellInfo->EffectImplicitTargetA[j])
{
case TARGET_DST_DB:
found = true;
break;
}
if (found)
break;
switch(spellInfo->EffectImplicitTargetB[j])
{
case TARGET_DST_DB:
found = true;
break;
}
if (found)
break;
}
if (found)
{
// if (!sSpellMgr->GetSpellTargetPosition(i))
// sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) does not have record in `spell_target_position`", i);
}
}
sLog->outString(">> Loaded %u spell teleport coordinates in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
bool SpellMgr::IsAffectedByMod(SpellEntry const *spellInfo, SpellModifier *mod) const
{
// false for spellInfo == NULL
if (!spellInfo || !mod)
return false;
SpellEntry const *affect_spell = sSpellStore.LookupEntry(mod->spellId);
// False if affect_spell == NULL or spellFamily not equal
if (!affect_spell || affect_spell->SpellFamilyName != spellInfo->SpellFamilyName)
return false;
// true
if (mod->mask & spellInfo->SpellFamilyFlags)
return true;
return false;
}
void SpellMgr::LoadSpellProcEvents()
{
uint32 oldMSTime = getMSTime();
mSpellProcEventMap.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3 4 5 6 7 8 9 10
QueryResult result = WorldDatabase.Query("SELECT entry, SchoolMask, SpellFamilyName, SpellFamilyMask0, SpellFamilyMask1, SpellFamilyMask2, procFlags, procEx, ppmRate, CustomChance, Cooldown FROM spell_proc_event");
if (!result)
{
sLog->outString(">> Loaded %u spell proc event conditions", count);
sLog->outString();
return;
}
uint32 customProc = 0;
do
{
Field *fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
const SpellEntry *spell = sSpellStore.LookupEntry(entry);
if (!spell)
{
sLog->outErrorDb("Spell %u listed in `spell_proc_event` does not exist", entry);
continue;
}
SpellProcEventEntry spe;
spe.schoolMask = fields[1].GetUInt32();
spe.spellFamilyName = fields[2].GetUInt32();
spe.spellFamilyMask[0] = fields[3].GetUInt32();
spe.spellFamilyMask[1] = fields[4].GetUInt32();
spe.spellFamilyMask[2] = fields[5].GetUInt32();
spe.procFlags = fields[6].GetUInt32();
spe.procEx = fields[7].GetUInt32();
spe.ppmRate = fields[8].GetFloat();
spe.customChance = fields[9].GetFloat();
spe.cooldown = fields[10].GetUInt32();
mSpellProcEventMap[entry] = spe;
if (spell->procFlags == 0)
{
if (spe.procFlags == 0)
{
sLog->outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell", entry);
continue;
}
customProc++;
}
++count;
} while (result->NextRow());
if (customProc)
sLog->outString(">> Loaded %u extra and %u custom spell proc event conditions in %u ms", count, customProc, GetMSTimeDiffToNow(oldMSTime));
else
sLog->outString(">> Loaded %u extra spell proc event conditions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellBonusess()
{
uint32 oldMSTime = getMSTime();
mSpellBonusMap.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3 4
QueryResult result = WorldDatabase.Query("SELECT entry, direct_bonus, dot_bonus, ap_bonus, ap_dot_bonus FROM spell_bonus_data");
if (!result)
{
sLog->outString(">> Loaded %u spell bonus data", count);
sLog->outString();
return;
}
do
{
Field *fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
const SpellEntry *spell = sSpellStore.LookupEntry(entry);
if (!spell)
{
sLog->outErrorDb("Spell %u listed in `spell_bonus_data` does not exist", entry);
continue;
}
SpellBonusEntry sbe;
sbe.direct_damage = fields[1].GetFloat();
sbe.dot_damage = fields[2].GetFloat();
sbe.ap_bonus = fields[3].GetFloat();
sbe.ap_dot_bonus = fields[4].GetFloat();
mSpellBonusMap[entry] = sbe;
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u extra spell bonus data in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellProcEventEntry const* spellProcEvent, uint32 EventProcFlag, SpellEntry const * procSpell, uint32 procFlags, uint32 procExtra, bool active)
{
// No extra req need
uint32 procEvent_procEx = PROC_EX_NONE;
// check prockFlags for condition
if ((procFlags & EventProcFlag) == 0)
return false;
bool hasFamilyMask = false;
/* Check Periodic Auras
*Dots can trigger if spell has no PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL
nor PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL
*Only Hots can trigger if spell has PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL
*Only dots can trigger if spell has both positivity flags or PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL
*Aura has to have PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL or spellfamily specified to trigger from Hot
*/
if (procFlags & PROC_FLAG_DONE_PERIODIC)
{
if (EventProcFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG)
{
if (!(procExtra & PROC_EX_INTERNAL_DOT))
return false;
}
else if (procExtra & PROC_EX_INTERNAL_HOT)
procExtra |= PROC_EX_INTERNAL_REQ_FAMILY;
else if (EventProcFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS)
return false;
}
if (procFlags & PROC_FLAG_TAKEN_PERIODIC)
{
if (EventProcFlag & PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS)
{
if (!(procExtra & PROC_EX_INTERNAL_DOT))
return false;
}
else if (procExtra & PROC_EX_INTERNAL_HOT)
procExtra |= PROC_EX_INTERNAL_REQ_FAMILY;
else if (EventProcFlag & PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS)
return false;
}
// Trap casts are active by default
if (procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION)
active = true;
// Always trigger for this
if (procFlags & (PROC_FLAG_KILLED | PROC_FLAG_KILL | PROC_FLAG_DEATH))
return true;
if (spellProcEvent) // Exist event data
{
// Store extra req
procEvent_procEx = spellProcEvent->procEx;
// For melee triggers
if (procSpell == NULL)
{
// Check (if set) for school (melee attack have Normal school)
if (spellProcEvent->schoolMask && (spellProcEvent->schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
return false;
}
else // For spells need check school/spell family/family mask
{
// Check (if set) for school
if (spellProcEvent->schoolMask && (spellProcEvent->schoolMask & procSpell->SchoolMask) == 0)
return false;
// Check (if set) for spellFamilyName
if (spellProcEvent->spellFamilyName && (spellProcEvent->spellFamilyName != procSpell->SpellFamilyName))
return false;
// spellFamilyName is Ok need check for spellFamilyMask if present
if (spellProcEvent->spellFamilyMask)
{
if ((spellProcEvent->spellFamilyMask & procSpell->SpellFamilyFlags) == 0)
return false;
hasFamilyMask = true;
// Some spells are not considered as active even with have spellfamilyflags
if (!(procEvent_procEx & PROC_EX_ONLY_ACTIVE_SPELL))
active = true;
}
}
}
if (procExtra & (PROC_EX_INTERNAL_REQ_FAMILY))
{
if (!hasFamilyMask)
return false;
}
// Check for extra req (if none) and hit/crit
if (procEvent_procEx == PROC_EX_NONE)
{
// No extra req, so can trigger only for hit/crit - spell has to be active
if ((procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) && active)
return true;
}
else // Passive spells hits here only if resist/reflect/immune/evade
{
if (procExtra & AURA_SPELL_PROC_EX_MASK)
{
// if spell marked as procing only from not active spells
if (active && procEvent_procEx & PROC_EX_NOT_ACTIVE_SPELL)
return false;
// if spell marked as procing only from active spells
if (!active && procEvent_procEx & PROC_EX_ONLY_ACTIVE_SPELL)
return false;
// Exist req for PROC_EX_EX_TRIGGER_ALWAYS
if (procEvent_procEx & PROC_EX_EX_TRIGGER_ALWAYS)
return true;
// PROC_EX_NOT_ACTIVE_SPELL and PROC_EX_ONLY_ACTIVE_SPELL flags handle: if passed checks before
if ((procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) && ((procEvent_procEx & (AURA_SPELL_PROC_EX_MASK)) == 0))
return true;
}
// Check Extra Requirement like (hit/crit/miss/resist/parry/dodge/block/immune/reflect/absorb and other)
if (procEvent_procEx & procExtra)
return true;
}
return false;
}
void SpellMgr::LoadSpellGroups()
{
uint32 oldMSTime = getMSTime();
mSpellSpellGroup.clear(); // need for reload case
mSpellGroupSpell.clear();
uint32 count = 0;
// 0 1
QueryResult result = WorldDatabase.Query("SELECT id, spell_id FROM spell_group");
if (!result)
{
sLog->outString();
sLog->outString(">> Loaded %u spell group definitions", count);
return;
}
std::set<uint32> groups;
do
{
Field *fields = result->Fetch();
uint32 group_id = fields[0].GetUInt32();
if (group_id <= SPELL_GROUP_DB_RANGE_MIN && group_id >= SPELL_GROUP_CORE_RANGE_MAX)
{
sLog->outErrorDb("SpellGroup id %u listed in `spell_groups` is in core range, but is not defined in core!", group_id);
continue;
}
int32 spell_id = fields[1].GetInt32();
groups.insert(std::set<uint32>::value_type(group_id));
mSpellGroupSpell.insert(SpellGroupSpellMap::value_type((SpellGroup)group_id, spell_id));
} while (result->NextRow());
for (SpellGroupSpellMap::iterator itr = mSpellGroupSpell.begin(); itr!= mSpellGroupSpell.end() ;)
{
if (itr->second < 0)
{
if (groups.find(abs(itr->second)) == groups.end())
{
sLog->outErrorDb("SpellGroup id %u listed in `spell_groups` does not exist", abs(itr->second));
mSpellGroupSpell.erase(itr++);
}
else
++itr;
}
else
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->second);
if (!spellInfo)
{
sLog->outErrorDb("Spell %u listed in `spell_group` does not exist", itr->second);
mSpellGroupSpell.erase(itr++);
}
else if (GetSpellRank(itr->second) > 1)
{
sLog->outErrorDb("Spell %u listed in `spell_group` is not first rank of spell", itr->second);
mSpellGroupSpell.erase(itr++);
}
else
++itr;
}
}
for (std::set<uint32>::iterator groupItr = groups.begin() ; groupItr != groups.end() ; ++groupItr)
{
std::set<uint32> spells;
GetSetOfSpellsInSpellGroup(SpellGroup(*groupItr), spells);
for (std::set<uint32>::iterator spellItr = spells.begin() ; spellItr != spells.end() ; ++spellItr)
{
++count;
mSpellSpellGroup.insert(SpellSpellGroupMap::value_type(*spellItr, SpellGroup(*groupItr)));
}
}
sLog->outString(">> Loaded %u spell group definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellGroupStackRules()
{
uint32 oldMSTime = getMSTime();
mSpellGroupStack.clear(); // need for reload case
uint32 count = 0;
// 0 1
QueryResult result = WorldDatabase.Query("SELECT group_id, stack_rule FROM spell_group_stack_rules");
if (!result)
{
sLog->outString(">> Loaded 0 spell group stack rules");
sLog->outString();
return;
}
do
{
Field *fields = result->Fetch();
uint32 group_id = fields[0].GetUInt32();
uint8 stack_rule = fields[1].GetUInt32();
if (stack_rule >= SPELL_GROUP_STACK_RULE_MAX)
{
sLog->outErrorDb("SpellGroupStackRule %u listed in `spell_group_stack_rules` does not exist", stack_rule);
continue;
}
SpellGroupSpellMapBounds spellGroup = GetSpellGroupSpellMapBounds((SpellGroup)group_id);
if (spellGroup.first == spellGroup.second)
{
sLog->outErrorDb("SpellGroup id %u listed in `spell_group_stack_rules` does not exist", group_id);
continue;
}
mSpellGroupStack[(SpellGroup)group_id] = (SpellGroupStackRule)stack_rule;
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u spell group stack rules in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellThreats()
{
uint32 oldMSTime = getMSTime();
mSpellThreatMap.clear(); // need for reload case
uint32 count = 0;
// 0 1
QueryResult result = WorldDatabase.Query("SELECT entry, Threat FROM spell_threat");
if (!result)
{
sLog->outString(">> Loaded %u aggro generating spells", count);
sLog->outString();
return;
}
do
{
Field *fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
uint16 Threat = fields[1].GetUInt16();
if (!sSpellStore.LookupEntry(entry))
{
sLog->outErrorDb("Spell %u listed in `spell_threat` does not exist", entry);
continue;
}
mSpellThreatMap[entry] = Threat;
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u aggro generating spells in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const
{
SpellEntry const *spellInfo_2 = sSpellStore.LookupEntry(spellId_2);
if (!spellInfo_1 || !spellInfo_2) return false;
if (spellInfo_1->Id == spellId_2) return false;
return GetFirstSpellInChain(spellInfo_1->Id) == GetFirstSpellInChain(spellId_2);
}
bool SpellMgr::canStackSpellRanks(SpellEntry const *spellInfo)
{
if (IsPassiveSpell(spellInfo->Id)) // ranked passive spell
return false;
if (spellInfo->powerType != POWER_MANA && spellInfo->powerType != POWER_HEALTH)
return false;
if (IsProfessionOrRidingSpell(spellInfo->Id))
return false;
if (sSpellMgr->IsSkillBonusSpell(spellInfo->Id))
return false;
// All stance spells. if any better way, change it.
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch(spellInfo->SpellFamilyName)
{
case SPELLFAMILY_PALADIN:
// Paladin aura Spell
if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID)
return false;
break;
case SPELLFAMILY_DRUID:
// Druid form Spell
if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA &&
spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
return false;
break;
case SPELLFAMILY_ROGUE:
// Rogue Stealth
if (spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA &&
spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT)
return false;
}
}
return true;
}
bool SpellMgr::IsProfessionOrRidingSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS ; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_SKILL)
{
uint32 skill = spellInfo->EffectMiscValue[i];
bool found = IsProfessionOrRidingSkill(skill);
if (found)
return true;
}
}
return false;
}
bool SpellMgr::IsProfessionSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS ; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_SKILL)
{
uint32 skill = spellInfo->EffectMiscValue[i];
bool found = IsProfessionSkill(skill);
if (found)
return true;
}
}
return false;
}
bool SpellMgr::IsPrimaryProfessionSpell(uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return false;
for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS ; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_SKILL)
{
uint32 skill = spellInfo->EffectMiscValue[i];
bool found = IsPrimaryProfessionSkill(skill);
if (found)
return true;
}
}
return false;
}
bool SpellMgr::IsPrimaryProfessionFirstRankSpell(uint32 spellId) const
{
return IsPrimaryProfessionSpell(spellId) && GetSpellRank(spellId) == 1;
}
bool SpellMgr::IsSkillBonusSpell(uint32 spellId) const
{
SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineAbilityEntry const *pAbility = _spell_idx->second;
if (!pAbility || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
continue;
if (pAbility->req_skill_value > 0)
return true;
}
return false;
}
bool SpellMgr::IsSkillTypeSpell(uint32 spellId, SkillType type) const
{
SkillLineAbilityMapBounds bounds = GetSkillLineAbilityMapBounds(spellId);
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
if (_spell_idx->second->skillId == uint32(type))
return true;
return false;
}
// basepoints provided here have to be valid basepoints (use SpellMgr::CalculateSpellEffectBaseAmount)
int32 SpellMgr::CalculateSpellEffectAmount(SpellEntry const * spellEntry, uint8 effIndex, Unit const * caster, int32 const * effBasePoints, Unit const * /*target*/)
{
float basePointsPerLevel = spellEntry->EffectRealPointsPerLevel[effIndex];
int32 basePoints = effBasePoints ? *effBasePoints : spellEntry->EffectBasePoints[effIndex];
int32 randomPoints = int32(spellEntry->EffectDieSides[effIndex]);
// base amount modification based on spell lvl vs caster lvl
if (caster)
{
int32 level = int32(caster->getLevel());
if (level > int32(spellEntry->maxLevel) && spellEntry->maxLevel > 0)
level = int32(spellEntry->maxLevel);
else if (level < int32(spellEntry->baseLevel))
level = int32(spellEntry->baseLevel);
level -= int32(spellEntry->spellLevel);
basePoints += int32(level * basePointsPerLevel);
}
// roll in a range <1;EffectDieSides> as of patch 3.3.3
switch(randomPoints)
{
case 0: break;
case 1: basePoints += 1; break; // range 1..1
default:
// range can have positive (1..rand) and negative (rand..1) values, so order its for irand
int32 randvalue = (randomPoints >= 1)
? irand(1, randomPoints)
: irand(randomPoints, 1);
basePoints += randvalue;
break;
}
float value = float(basePoints);
// random damage
if (caster)
{
// bonus amount from combo points
if (caster->m_movedPlayer)
if (uint8 comboPoints = caster->m_movedPlayer->GetComboPoints())
if (float comboDamage = spellEntry->EffectPointsPerComboPoint[effIndex])
value += comboDamage * comboPoints;
value = caster->ApplyEffectModifiers(spellEntry, effIndex, value);
// amount multiplication based on caster's level
if (!basePointsPerLevel && (spellEntry->Attributes & SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION && spellEntry->spellLevel) &&
spellEntry->Effect[effIndex] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
spellEntry->Effect[effIndex] != SPELL_EFFECT_KNOCK_BACK &&
spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_SPEED_ALWAYS &&
spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_SPEED_NOT_STACK &&
spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_INCREASE_SPEED &&
spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_DECREASE_SPEED)
//there are many more: slow speed, -healing pct
value *= 0.25f * exp(caster->getLevel() * (70 - spellEntry->spellLevel) / 1000.0f);
//value = int32(value * (int32)getLevel() / (int32)(spellProto->spellLevel ? spellProto->spellLevel : 1));
}
return int32(value);
}
int32 SpellMgr::CalculateSpellEffectBaseAmount(int32 value, SpellEntry const * spellEntry, uint8 effIndex)
{
if (spellEntry->EffectDieSides[effIndex] == 0)
return value;
else
return value - 1;
}
float SpellMgr::CalculateSpellEffectValueMultiplier(SpellEntry const * spellEntry, uint8 effIndex, Unit * caster, Spell * spell)
{
float multiplier = spellEntry->EffectValueMultiplier[effIndex];
if (caster)
if (Player * modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(spellEntry->Id, SPELLMOD_VALUE_MULTIPLIER, multiplier, spell);
return multiplier;
}
float SpellMgr::CalculateSpellEffectDamageMultiplier(SpellEntry const * spellEntry, uint8 effIndex, Unit * caster, Spell * spell)
{
float multiplier = spellEntry->EffectDamageMultiplier[effIndex];
if (caster)
if (Player * modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(spellEntry->Id, SPELLMOD_DAMAGE_MULTIPLIER, multiplier, spell);
return multiplier;
}
SpellEntry const* SpellMgr::SelectAuraRankForPlayerLevel(SpellEntry const* spellInfo, uint32 playerLevel) const
{
// ignore passive spells
if (IsPassiveSpell(spellInfo->Id))
return spellInfo;
bool needRankSelection = false;
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (IsPositiveEffect(spellInfo->Id, i) && (
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PARTY ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID
))
{
needRankSelection = true;
break;
}
}
// not required
if (!needRankSelection)
return spellInfo;
for (uint32 nextSpellId = spellInfo->Id; nextSpellId != 0; nextSpellId = GetPrevSpellInChain(nextSpellId))
{
SpellEntry const *nextSpellInfo = sSpellStore.LookupEntry(nextSpellId);
if (!nextSpellInfo)
break;
// if found appropriate level
if (playerLevel + 10 >= nextSpellInfo->spellLevel)
return nextSpellInfo;
// one rank less then
}
// not found
return NULL;
}
void SpellMgr::LoadSpellLearnSkills()
{
uint32 oldMSTime = getMSTime();
mSpellLearnSkills.clear(); // need for reload case
// search auto-learned skills and add its to map also for use in unlearn spells/talents
uint32 dbc_count = 0;
for (uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
{
SpellEntry const* entry = sSpellStore.LookupEntry(spell);
if (!entry)
continue;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (entry->Effect[i] == SPELL_EFFECT_SKILL)
{
SpellLearnSkillNode dbc_node;
dbc_node.skill = entry->EffectMiscValue[i];
dbc_node.step = SpellMgr::CalculateSpellEffectAmount(entry, i);
if (dbc_node.skill != SKILL_RIDING)
dbc_node.value = 1;
else
dbc_node.value = dbc_node.step * 75;
dbc_node.maxvalue = dbc_node.step * 75;
mSpellLearnSkills[spell] = dbc_node;
++dbc_count;
break;
}
}
}
sLog->outString(">> Loaded %u Spell Learn Skills from DBC in %u ms", dbc_count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellLearnSpells()
{
uint32 oldMSTime = getMSTime();
mSpellLearnSpells.clear(); // need for reload case
// 0 1 2
QueryResult result = WorldDatabase.Query("SELECT entry, SpellID, Active FROM spell_learn_spell");
if (!result)
{
sLog->outString(">> Loaded 0 spell learn spells");
sLog->outString();
sLog->outErrorDb("`spell_learn_spell` table is empty!");
return;
}
uint32 count = 0;
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
SpellLearnSpellNode node;
node.spell = fields[1].GetUInt32();
node.active = fields[2].GetBool();
node.autoLearned= false;
if (!sSpellStore.LookupEntry(spell_id))
{
sLog->outErrorDb("Spell %u listed in `spell_learn_spell` does not exist", spell_id);
continue;
}
if (!sSpellStore.LookupEntry(node.spell))
{
sLog->outErrorDb("Spell %u listed in `spell_learn_spell` learning not existed spell %u", spell_id, node.spell);
continue;
}
if (GetTalentSpellCost(node.spell))
{
sLog->outErrorDb("Spell %u listed in `spell_learn_spell` attempt learning talent spell %u, skipped", spell_id, node.spell);
continue;
}
mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell_id,node));
++count;
} while (result->NextRow());
// search auto-learned spells and add its to map also for use in unlearn spells/talents
uint32 dbc_count = 0;
for (uint32 spell = 0; spell < sSpellStore.GetNumRows(); ++spell)
{
SpellEntry const* entry = sSpellStore.LookupEntry(spell);
if (!entry)
continue;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (entry->Effect[i] == SPELL_EFFECT_LEARN_SPELL)
{
SpellLearnSpellNode dbc_node;
dbc_node.spell = entry->EffectTriggerSpell[i];
dbc_node.active = true; // all dbc based learned spells is active (show in spell book or hide by client itself)
// ignore learning not existed spells (broken/outdated/or generic learnig spell 483
if (!sSpellStore.LookupEntry(dbc_node.spell))
continue;
// talent or passive spells or skill-step spells auto-casted and not need dependent learning,
// pet teaching spells don't must be dependent learning (casted)
// other required explicit dependent learning
dbc_node.autoLearned = entry->EffectImplicitTargetA[i] == TARGET_UNIT_PET || GetTalentSpellCost(spell) > 0 || IsPassiveSpell(spell) || IsSpellHaveEffect(entry,SPELL_EFFECT_SKILL_STEP);
SpellLearnSpellMapBounds db_node_bounds = GetSpellLearnSpellMapBounds(spell);
bool found = false;
for (SpellLearnSpellMap::const_iterator itr = db_node_bounds.first; itr != db_node_bounds.second; ++itr)
{
if (itr->second.spell == dbc_node.spell)
{
sLog->outErrorDb("Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.",
spell,dbc_node.spell);
found = true;
break;
}
}
if (!found) // add new spell-spell pair if not found
{
mSpellLearnSpells.insert(SpellLearnSpellMap::value_type(spell,dbc_node));
++dbc_count;
}
}
}
}
sLog->outString(">> Loaded %u spell learn spells + %u found in DBC in %u ms", count, dbc_count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellPetAuras()
{
uint32 oldMSTime = getMSTime();
mSpellPetAuraMap.clear(); // need for reload case
// 0 1 2 3
QueryResult result = WorldDatabase.Query("SELECT spell, effectId, pet, aura FROM spell_pet_auras");
if (!result)
{
sLog->outString(">> Loaded 0 spell pet auras. DB table `spell_pet_auras` is empty.");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field *fields = result->Fetch();
uint32 spell = fields[0].GetUInt32();
uint8 eff = fields[1].GetUInt8();
uint32 pet = fields[2].GetUInt32();
uint32 aura = fields[3].GetUInt32();
SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find((spell<<8) + eff);
if (itr != mSpellPetAuraMap.end())
itr->second.AddAura(pet, aura);
else
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
if (!spellInfo)
{
sLog->outErrorDb("Spell %u listed in `spell_pet_auras` does not exist", spell);
continue;
}
if (spellInfo->Effect[eff] != SPELL_EFFECT_DUMMY &&
(spellInfo->Effect[eff] != SPELL_EFFECT_APPLY_AURA ||
spellInfo->EffectApplyAuraName[eff] != SPELL_AURA_DUMMY))
{
sLog->outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell);
continue;
}
SpellEntry const* spellInfo2 = sSpellStore.LookupEntry(aura);
if (!spellInfo2)
{
sLog->outErrorDb("Aura %u listed in `spell_pet_auras` does not exist", aura);
continue;
}
PetAura pa(pet, aura, spellInfo->EffectImplicitTargetA[eff] == TARGET_UNIT_PET, SpellMgr::CalculateSpellEffectAmount(spellInfo, eff));
mSpellPetAuraMap[(spell<<8) + eff] = pa;
}
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u spell pet auras in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadPetLevelupSpellMap()
{
uint32 oldMSTime = getMSTime();
mPetLevelupSpellMap.clear(); // need for reload case
uint32 count = 0;
uint32 family_count = 0;
for (uint32 i = 0; i < sCreatureFamilyStore.GetNumRows(); ++i)
{
CreatureFamilyEntry const *creatureFamily = sCreatureFamilyStore.LookupEntry(i);
if (!creatureFamily) // not exist
continue;
for (uint8 j = 0; j < 2; ++j)
{
if (!creatureFamily->skillLine[j])
continue;
for (uint32 k = 0; k < sSkillLineAbilityStore.GetNumRows(); ++k)
{
SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(k);
if (!skillLine)
continue;
//if (skillLine->skillId != creatureFamily->skillLine[0] &&
// (!creatureFamily->skillLine[1] || skillLine->skillId != creatureFamily->skillLine[1]))
// continue;
if (skillLine->skillId != creatureFamily->skillLine[j])
continue;
if (skillLine->learnOnGetSkill != ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL)
continue;
SpellEntry const *spell = sSpellStore.LookupEntry(skillLine->spellId);
if (!spell) // not exist or triggered or talent
continue;
if (!spell->spellLevel)
continue;
PetLevelupSpellSet& spellSet = mPetLevelupSpellMap[creatureFamily->ID];
if (spellSet.empty())
++family_count;
spellSet.insert(PetLevelupSpellSet::value_type(spell->spellLevel,spell->Id));
++count;
}
}
}
sLog->outString(">> Loaded %u pet levelup and default spells for %u families in %u ms", count, family_count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
bool LoadPetDefaultSpells_helper(CreatureInfo const* cInfo, PetDefaultSpellsEntry& petDefSpells)
{
// skip empty list;
bool have_spell = false;
for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if (petDefSpells.spellid[j])
{
have_spell = true;
break;
}
}
if (!have_spell)
return false;
// remove duplicates with levelupSpells if any
if (PetLevelupSpellSet const *levelupSpells = cInfo->family ? sSpellMgr->GetPetLevelupSpellList(cInfo->family) : NULL)
{
for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if (!petDefSpells.spellid[j])
continue;
for (PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr)
{
if (itr->second == petDefSpells.spellid[j])
{
petDefSpells.spellid[j] = 0;
break;
}
}
}
}
// skip empty list;
have_spell = false;
for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
{
if (petDefSpells.spellid[j])
{
have_spell = true;
break;
}
}
return have_spell;
}
void SpellMgr::LoadPetDefaultSpells()
{
uint32 oldMSTime = getMSTime();
mPetDefaultSpellsMap.clear();
uint32 countCreature = 0;
uint32 countData = 0;
for (uint32 i = 0; i < sCreatureStorage.MaxEntry; ++i)
{
CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(i);
if (!cInfo)
continue;
if (!cInfo->PetSpellDataId)
continue;
// for creature with PetSpellDataId get default pet spells from dbc
CreatureSpellDataEntry const* spellDataEntry = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId);
if (!spellDataEntry)
continue;
int32 petSpellsId = -int32(cInfo->PetSpellDataId);
PetDefaultSpellsEntry petDefSpells;
for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
petDefSpells.spellid[j] = spellDataEntry->spellId[j];
if (LoadPetDefaultSpells_helper(cInfo, petDefSpells))
{
mPetDefaultSpellsMap[petSpellsId] = petDefSpells;
++countData;
}
}
sLog->outString(">> Loaded addition spells for %u pet spell data entries in %u ms", countData, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
sLog->outString("Loading summonable creature templates...");
oldMSTime = getMSTime();
// different summon spells
for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
{
SpellEntry const* spellEntry = sSpellStore.LookupEntry(i);
if (!spellEntry)
continue;
for (uint8 k = 0; k < MAX_SPELL_EFFECTS; ++k)
{
if (spellEntry->Effect[k] == SPELL_EFFECT_SUMMON || spellEntry->Effect[k] == SPELL_EFFECT_SUMMON_PET)
{
uint32 creature_id = spellEntry->EffectMiscValue[k];
CreatureInfo const *cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(creature_id);
if (!cInfo)
continue;
// already loaded
if (cInfo->PetSpellDataId)
continue;
// for creature without PetSpellDataId get default pet spells from creature_template
int32 petSpellsId = cInfo->Entry;
if (mPetDefaultSpellsMap.find(cInfo->Entry) != mPetDefaultSpellsMap.end())
continue;
PetDefaultSpellsEntry petDefSpells;
for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j)
petDefSpells.spellid[j] = cInfo->spells[j];
if (LoadPetDefaultSpells_helper(cInfo, petDefSpells))
{
mPetDefaultSpellsMap[petSpellsId] = petDefSpells;
++countCreature;
}
}
}
}
sLog->outString(">> Loaded %u summonable creature templates in %u ms", countCreature, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
/// Some checks for spells, to prevent adding deprecated/broken spells for trainers, spell book, etc
bool SpellMgr::IsSpellValid(SpellEntry const *spellInfo, Player *pl, bool msg)
{
// not exist
if (!spellInfo)
return false;
bool need_check_reagents = false;
// check effects
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (spellInfo->Effect[i])
{
case 0:
continue;
// craft spell for crafting non-existed item (break client recipes list show)
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_CREATE_ITEM_2:
{
if (spellInfo->EffectItemType[i] == 0)
{
// skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime)
if (!IsLootCraftingSpell(spellInfo))
{
if (msg)
{
if (pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u not have create item entry.",spellInfo->Id);
else
sLog->outErrorDb("Craft spell %u not have create item entry.",spellInfo->Id);
}
return false;
}
}
// also possible IsLootCraftingSpell case but fake item must exist anyway
else if (!ObjectMgr::GetItemPrototype(spellInfo->EffectItemType[i]))
{
if (msg)
{
if (pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
else
sLog->outErrorDb("Craft spell %u create not-exist in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->EffectItemType[i]);
}
return false;
}
need_check_reagents = true;
break;
}
case SPELL_EFFECT_LEARN_SPELL:
{
SpellEntry const *spellInfo2 = sSpellStore.LookupEntry(spellInfo->EffectTriggerSpell[i]);
if (!IsSpellValid(spellInfo2,pl,msg))
{
if (msg)
{
if (pl)
ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]);
else
sLog->outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellInfo->EffectTriggerSpell[i]);
}
return false;
}
break;
}
}
}
if (need_check_reagents)
{
for (uint8 j = 0; j < MAX_SPELL_REAGENTS; ++j)
{
if (spellInfo->Reagent[j] > 0 && !ObjectMgr::GetItemPrototype(spellInfo->Reagent[j]))
{
if (msg)
{
if (pl)
ChatHandler(pl).PSendSysMessage("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
else
sLog->outErrorDb("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...",spellInfo->Id,spellInfo->Reagent[j]);
}
return false;
}
}
}
return true;
}
void SpellMgr::LoadSpellAreas()
{
uint32 oldMSTime = getMSTime();
mSpellAreaMap.clear(); // need for reload case
mSpellAreaForQuestMap.clear();
mSpellAreaForActiveQuestMap.clear();
mSpellAreaForQuestEndMap.clear();
mSpellAreaForAuraMap.clear();
// 0 1 2 3 4 5 6 7 8
QueryResult result = WorldDatabase.Query("SELECT spell, area, quest_start, quest_start_active, quest_end, aura_spell, racemask, gender, autocast FROM spell_area");
if (!result)
{
sLog->outString(">> Loaded 0 spell area requirements. DB table `spell_area` is empty.");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field *fields = result->Fetch();
uint32 spell = fields[0].GetUInt32();
SpellArea spellArea;
spellArea.spellId = spell;
spellArea.areaId = fields[1].GetUInt32();
spellArea.questStart = fields[2].GetUInt32();
spellArea.questStartCanActive = fields[3].GetBool();
spellArea.questEnd = fields[4].GetUInt32();
spellArea.auraSpell = fields[5].GetInt32();
spellArea.raceMask = fields[6].GetUInt32();
spellArea.gender = Gender(fields[7].GetUInt8());
spellArea.autocast = fields[8].GetBool();
if (const SpellEntry* spellInfo = sSpellStore.LookupEntry(spell))
{
if (spellArea.autocast)
const_cast<SpellEntry*>(spellInfo)->Attributes |= SPELL_ATTR0_CANT_CANCEL;
}
else
{
sLog->outErrorDb("Spell %u listed in `spell_area` does not exist", spell);
continue;
}
{
bool ok = true;
SpellAreaMapBounds sa_bounds = GetSpellAreaMapBounds(spellArea.spellId);
for (SpellAreaMap::const_iterator itr = sa_bounds.first; itr != sa_bounds.second; ++itr)
{
if (spellArea.spellId != itr->second.spellId)
continue;
if (spellArea.areaId != itr->second.areaId)
continue;
if (spellArea.questStart != itr->second.questStart)
continue;
if (spellArea.auraSpell != itr->second.auraSpell)
continue;
if ((spellArea.raceMask & itr->second.raceMask) == 0)
continue;
if (spellArea.gender != itr->second.gender)
continue;
// duplicate by requirements
ok =false;
break;
}
if (!ok)
{
sLog->outErrorDb("Spell %u listed in `spell_area` already listed with similar requirements.", spell);
continue;
}
}
if (spellArea.areaId && !GetAreaEntryByAreaID(spellArea.areaId))
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong area (%u) requirement", spell,spellArea.areaId);
continue;
}
if (spellArea.questStart && !sObjectMgr->GetQuestTemplate(spellArea.questStart))
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong start quest (%u) requirement", spell,spellArea.questStart);
continue;
}
if (spellArea.questEnd)
{
if (!sObjectMgr->GetQuestTemplate(spellArea.questEnd))
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong end quest (%u) requirement", spell,spellArea.questEnd);
continue;
}
if (spellArea.questEnd == spellArea.questStart && !spellArea.questStartCanActive)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have quest (%u) requirement for start and end in same time", spell,spellArea.questEnd);
continue;
}
}
if (spellArea.auraSpell)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(spellArea.auraSpell));
if (!spellInfo)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong aura spell (%u) requirement", spell,abs(spellArea.auraSpell));
continue;
}
if (uint32(abs(spellArea.auraSpell)) == spellArea.spellId)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement for itself", spell,abs(spellArea.auraSpell));
continue;
}
// not allow autocast chains by auraSpell field (but allow use as alternative if not present)
if (spellArea.autocast && spellArea.auraSpell > 0)
{
bool chain = false;
SpellAreaForAuraMapBounds saBound = GetSpellAreaForAuraMapBounds(spellArea.spellId);
for (SpellAreaForAuraMap::const_iterator itr = saBound.first; itr != saBound.second; ++itr)
{
if (itr->second->autocast && itr->second->auraSpell > 0)
{
chain = true;
break;
}
}
if (chain)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell);
continue;
}
SpellAreaMapBounds saBound2 = GetSpellAreaMapBounds(spellArea.auraSpell);
for (SpellAreaMap::const_iterator itr2 = saBound2.first; itr2 != saBound2.second; ++itr2)
{
if (itr2->second.autocast && itr2->second.auraSpell > 0)
{
chain = true;
break;
}
}
if (chain)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell,spellArea.auraSpell);
continue;
}
}
}
if (spellArea.raceMask && (spellArea.raceMask & RACEMASK_ALL_PLAYABLE) == 0)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong race mask (%u) requirement", spell,spellArea.raceMask);
continue;
}
if (spellArea.gender != GENDER_NONE && spellArea.gender != GENDER_FEMALE && spellArea.gender != GENDER_MALE)
{
sLog->outErrorDb("Spell %u listed in `spell_area` have wrong gender (%u) requirement", spell, spellArea.gender);
continue;
}
SpellArea const* sa = &mSpellAreaMap.insert(SpellAreaMap::value_type(spell,spellArea))->second;
// for search by current zone/subzone at zone/subzone change
if (spellArea.areaId)
mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(spellArea.areaId,sa));
// for search at quest start/reward
if (spellArea.questStart)
{
if (spellArea.questStartCanActive)
mSpellAreaForActiveQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa));
else
mSpellAreaForQuestMap.insert(SpellAreaForQuestMap::value_type(spellArea.questStart,sa));
}
// for search at quest start/reward
if (spellArea.questEnd)
mSpellAreaForQuestEndMap.insert(SpellAreaForQuestMap::value_type(spellArea.questEnd,sa));
// for search at aura apply
if (spellArea.auraSpell)
mSpellAreaForAuraMap.insert(SpellAreaForAuraMap::value_type(abs(spellArea.auraSpell),sa));
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u spell area requirements in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
SpellCastResult SpellMgr::GetSpellAllowedInLocationError(SpellEntry const *spellInfo, uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player)
{
// normal case
if (spellInfo->AreaGroupId > 0)
{
bool found = false;
AreaGroupEntry const* groupEntry = sAreaGroupStore.LookupEntry(spellInfo->AreaGroupId);
while (groupEntry)
{
for (uint8 i = 0; i < MAX_GROUP_AREA_IDS; ++i)
if (groupEntry->AreaId[i] == zone_id || groupEntry->AreaId[i] == area_id)
found = true;
if (found || !groupEntry->nextGroup)
break;
// Try search in next group
groupEntry = sAreaGroupStore.LookupEntry(groupEntry->nextGroup);
}
if (!found)
return SPELL_FAILED_INCORRECT_AREA;
}
// continent limitation (virtual continent)
if (spellInfo->AttributesEx4 & SPELL_ATTR4_CAST_ONLY_IN_OUTLAND)
{
uint32 v_map = GetVirtualMapForMapAndZone(map_id, zone_id);
MapEntry const *mapEntry = sMapStore.LookupEntry(v_map);
if (!mapEntry || mapEntry->addon < 1 || !mapEntry->IsContinent())
return SPELL_FAILED_INCORRECT_AREA;
}
// raid instance limitation
if (spellInfo->AttributesEx6 & SPELL_ATTR6_NOT_IN_RAID_INSTANCE)
{
MapEntry const *mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry || mapEntry->IsRaid())
return SPELL_FAILED_NOT_IN_RAID_INSTANCE;
}
// DB base check (if non empty then must fit at least single for allow)
SpellAreaMapBounds saBounds = sSpellMgr->GetSpellAreaMapBounds(spellInfo->Id);
if (saBounds.first != saBounds.second)
{
for (SpellAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
{
if (itr->second.IsFitToRequirements(player,zone_id,area_id))
return SPELL_CAST_OK;
}
return SPELL_FAILED_INCORRECT_AREA;
}
// bg spell checks
switch(spellInfo->Id)
{
case 23333: // Warsong Flag
case 23335: // Silverwing Flag
return map_id == 489 && player && player->InBattleground() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
case 34976: // Netherstorm Flag
return map_id == 566 && player && player->InBattleground() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
case 2584: // Waiting to Resurrect
case 22011: // Spirit Heal Channel
case 22012: // Spirit Heal
case 24171: // Resurrection Impact Visual
case 42792: // Recently Dropped Flag
case 43681: // Inactive
case 44535: // Spirit Heal (mana)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry)
return SPELL_FAILED_INCORRECT_AREA;
return zone_id == 4197 || (mapEntry->IsBattleground() && player && player->InBattleground()) ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
}
case 44521: // Preparation
{
if (!player)
return SPELL_FAILED_REQUIRES_AREA;
MapEntry const *mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry)
return SPELL_FAILED_INCORRECT_AREA;
if (!mapEntry->IsBattleground())
return SPELL_FAILED_REQUIRES_AREA;
Battleground* bg = player->GetBattleground();
return bg && bg->GetStatus() == STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
}
case 32724: // Gold Team (Alliance)
case 32725: // Green Team (Alliance)
case 35774: // Gold Team (Horde)
case 35775: // Green Team (Horde)
{
MapEntry const *mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry)
return SPELL_FAILED_INCORRECT_AREA;
return mapEntry->IsBattleArena() && player && player->InBattleground() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
}
case 32727: // Arena Preparation
{
if (!player)
return SPELL_FAILED_REQUIRES_AREA;
MapEntry const *mapEntry = sMapStore.LookupEntry(map_id);
if (!mapEntry)
return SPELL_FAILED_INCORRECT_AREA;
if (!mapEntry->IsBattleArena())
return SPELL_FAILED_REQUIRES_AREA;
Battleground *bg = player->GetBattleground();
return bg && bg->GetStatus() == STATUS_WAIT_JOIN ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA;
}
}
// aura limitations
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (spellInfo->EffectApplyAuraName[i])
{
case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
case SPELL_AURA_FLY:
{
if (player && !player->IsKnowHowFlyIn(map_id, zone_id))
return SPELL_FAILED_INCORRECT_AREA;
}
}
}
return SPELL_CAST_OK;
}
void SpellMgr::LoadSkillLineAbilityMap()
{
uint32 oldMSTime = getMSTime();
mSkillLineAbilityMap.clear();
uint32 count = 0;
for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
{
SkillLineAbilityEntry const *SkillInfo = sSkillLineAbilityStore.LookupEntry(i);
if (!SkillInfo)
continue;
mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId,SkillInfo));
++count;
}
sLog->outString(">> Loaded %u SkillLineAbility MultiMap Data in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto, bool triggered)
{
if (IsPositiveSpell(spellproto->Id))
return DIMINISHING_NONE;
// Explicit Diminishing Groups
switch (spellproto->SpellFamilyName)
{
// Event spells
case SPELLFAMILY_UNK1:
return DIMINISHING_NONE;
case SPELLFAMILY_GENERIC:
// some generic arena related spells have by some strange reason MECHANIC_TURN
if (spellproto->Mechanic == MECHANIC_TURN)
return DIMINISHING_NONE;
break;
case SPELLFAMILY_MAGE:
{
// Frostbite
if (spellproto->SpellFamilyFlags[1] & 0x80000000)
return DIMINISHING_TRIGGER_ROOT;
//Shattered Barrier: only flag SpellFamilyFlags[0] = 0x00080000 shared
//by most frost spells, using id instead
if (spellproto->Id == 55080)
return DIMINISHING_TRIGGER_ROOT;
// Frost Nova / Freeze (Water Elemental)
if (spellproto->SpellIconID == 193)
return DIMINISHING_CONTROL_ROOT;
break;
}
case SPELLFAMILY_ROGUE:
{
// Sap 0x80 Gouge 0x8
if (spellproto->SpellFamilyFlags[0] & 0x88)
return DIMINISHING_POLYMORPH;
// Blind
else if (spellproto->SpellFamilyFlags[0] & 0x1000000)
return DIMINISHING_FEAR_BLIND;
// Cheap Shot
else if (spellproto->SpellFamilyFlags[0] & 0x400)
return DIMINISHING_CHEAPSHOT_POUNCE;
// Crippling poison - Limit to 10 seconds in PvP (No SpellFamilyFlags)
else if (spellproto->SpellIconID == 163)
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_WARLOCK:
{
// Death Coil
if (spellproto->SpellFamilyFlags[0] & 0x80000)
return DIMINISHING_DEATHCOIL;
// Curses/etc
else if (spellproto->SpellFamilyFlags[0] & 0x80000000)
return DIMINISHING_LIMITONLY;
// Howl of Terror
else if (spellproto->SpellFamilyFlags[1] & 0x8)
return DIMINISHING_FEAR_BLIND;
// Seduction
else if (spellproto->SpellFamilyFlags[1] & 0x10000000)
return DIMINISHING_FEAR_BLIND;
break;
}
case SPELLFAMILY_DRUID:
{
// Pounce
if (spellproto->SpellFamilyFlags[0] & 0x20000)
return DIMINISHING_CHEAPSHOT_POUNCE;
// Cyclone
else if (spellproto->SpellFamilyFlags[1] & 0x20)
return DIMINISHING_CYCLONE;
// Entangling Roots: to force natures grasp proc to be control root
else if (spellproto->SpellFamilyFlags[0] & 0x00000200)
return DIMINISHING_CONTROL_ROOT;
// Faerie Fire
else if (spellproto->SpellFamilyFlags[0] & 0x400)
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_WARRIOR:
{
// Hamstring - limit duration to 10s in PvP
if (spellproto->SpellFamilyFlags[0] & 0x2)
return DIMINISHING_LIMITONLY;
// Intimidating Shout
else if (spellproto->SpellFamilyFlags[0] & 0x40000)
return DIMINISHING_FEAR_BLIND;
// Charge Stun
else if (spellproto->SpellFamilyFlags[0] & 0x01000000)
return DIMINISHING_NONE;
break;
}
case SPELLFAMILY_PALADIN:
{
// Repentance
if (spellproto->SpellFamilyFlags[0] & 0x4)
return DIMINISHING_POLYMORPH;
// Judgement of Justice
if (spellproto->SpellFamilyFlags[0] & 0x100000)
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Hungering Cold (no flags)
if (spellproto->SpellIconID == 2797)
return DIMINISHING_POLYMORPH;
// Mark of Blood
else if ((spellproto->SpellFamilyFlags[0] & 0x10000000)
&& spellproto->SpellIconID == 2285)
return DIMINISHING_LIMITONLY;
break;
}
case SPELLFAMILY_HUNTER:
{
// Hunter's mark
if ((spellproto->SpellFamilyFlags[0] & 0x400) && spellproto->SpellIconID == 538)
return DIMINISHING_LIMITONLY;
// Scatter Shot
if ((spellproto->SpellFamilyFlags[0] & 0x40000) && spellproto->SpellIconID == 132)
return DIMINISHING_NONE;
break;
}
default:
break;
}
// Get by mechanic
uint32 mechanic = GetAllSpellMechanicMask(spellproto);
if (mechanic == MECHANIC_NONE) return DIMINISHING_NONE;
if (mechanic & ((1<<MECHANIC_STUN) |
(1<<MECHANIC_SHACKLE))) return triggered ? DIMINISHING_TRIGGER_STUN : DIMINISHING_CONTROL_STUN;
if (mechanic & ((1<<MECHANIC_SLEEP) |
(1<<MECHANIC_FREEZE))) return DIMINISHING_FREEZE_SLEEP;
if (mechanic & (1<<MECHANIC_POLYMORPH)) return DIMINISHING_POLYMORPH;
if (mechanic & (1<<MECHANIC_ROOT)) return triggered ? DIMINISHING_TRIGGER_ROOT : DIMINISHING_CONTROL_ROOT;
if (mechanic & ((1<<MECHANIC_FEAR) |
(1<<MECHANIC_TURN))) return DIMINISHING_FEAR_BLIND;
if (mechanic & (1<<MECHANIC_CHARM)) return DIMINISHING_CHARM;
if (mechanic & (1<<MECHANIC_SILENCE)) return DIMINISHING_SILENCE;
if (mechanic & (1<<MECHANIC_DISARM)) return DIMINISHING_DISARM;
if (mechanic & (1<<MECHANIC_FREEZE)) return DIMINISHING_FREEZE_SLEEP;
if (mechanic & ((1<<MECHANIC_KNOCKOUT) |
(1<<MECHANIC_SAPPED))) return DIMINISHING_KNOCKOUT;
if (mechanic & (1<<MECHANIC_BANISH)) return DIMINISHING_BANISH;
if (mechanic & (1<<MECHANIC_HORROR)) return DIMINISHING_DEATHCOIL;
// Get by effect
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spellproto->EffectApplyAuraName[i] == SPELL_AURA_MOD_TAUNT)
return DIMINISHING_TAUNT;
}
return DIMINISHING_NONE;
}
int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellEntry const* spellproto)
{
if (!IsDiminishingReturnsGroupDurationLimited(group))
return 0;
// Explicit diminishing duration
switch(spellproto->SpellFamilyName)
{
case SPELLFAMILY_HUNTER:
{
// Wyvern Sting
if (spellproto->SpellFamilyFlags[1] & 0x1000)
return 6 * IN_MILLISECONDS;
// Hunter's Mark
if (spellproto->SpellFamilyFlags[0] & 0x400)
return 120 * IN_MILLISECONDS;
break;
}
case SPELLFAMILY_PALADIN:
{
// Repentance - limit to 6 seconds in PvP
if (spellproto->SpellFamilyFlags[0] & 0x4)
return 6 * IN_MILLISECONDS;
break;
}
case SPELLFAMILY_DRUID:
{
// Faerie Fire - limit to 40 seconds in PvP (3.1)
if (spellproto->SpellFamilyFlags[0] & 0x400)
return 40 * IN_MILLISECONDS;
break;
}
default:
break;
}
return 10 * IN_MILLISECONDS;
}
bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group)
{
switch(group)
{
case DIMINISHING_CONTROL_STUN:
case DIMINISHING_TRIGGER_STUN:
case DIMINISHING_FREEZE_SLEEP:
case DIMINISHING_CONTROL_ROOT:
case DIMINISHING_TRIGGER_ROOT:
case DIMINISHING_FEAR_BLIND:
case DIMINISHING_CHARM:
case DIMINISHING_POLYMORPH:
case DIMINISHING_KNOCKOUT:
case DIMINISHING_CYCLONE:
case DIMINISHING_BANISH:
case DIMINISHING_LIMITONLY:
case DIMINISHING_CHEAPSHOT_POUNCE:
return true;
default:
return false;
}
}
DiminishingLevels GetDiminishingReturnsMaxLevel(DiminishingGroup group)
{
switch(group)
{
case DIMINISHING_TAUNT:
return DIMINISHING_LEVEL_TAUNT_IMMUNE;
default:
return DIMINISHING_LEVEL_IMMUNE;
}
}
DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group)
{
switch(group)
{
case DIMINISHING_TAUNT:
case DIMINISHING_CONTROL_STUN:
case DIMINISHING_TRIGGER_STUN:
case DIMINISHING_CHEAPSHOT_POUNCE:
case DIMINISHING_CYCLONE:
return DRTYPE_ALL;
case DIMINISHING_FEAR_BLIND:
case DIMINISHING_CONTROL_ROOT:
case DIMINISHING_TRIGGER_ROOT:
case DIMINISHING_CHARM:
case DIMINISHING_POLYMORPH:
case DIMINISHING_SILENCE:
case DIMINISHING_DISARM:
case DIMINISHING_DEATHCOIL:
case DIMINISHING_FREEZE_SLEEP:
case DIMINISHING_BANISH:
case DIMINISHING_KNOCKOUT:
return DRTYPE_PLAYER;
default:
break;
}
return DRTYPE_NONE;
}
bool IsPartOfSkillLine(uint32 skillId, uint32 spellId)
{
SkillLineAbilityMapBounds skillBounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId);
for (SkillLineAbilityMap::const_iterator itr = skillBounds.first; itr != skillBounds.second; ++itr)
if (itr->second->skillId == skillId)
return true;
return false;
}
bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 newArea) const
{
if (gender != GENDER_NONE) // not in expected gender
if (!player || gender != player->getGender())
return false;
if (raceMask) // not in expected race
if (!player || !(raceMask & player->getRaceMask()))
return false;
if (areaId) // not in expected zone
if (newZone != areaId && newArea != areaId)
return false;
if (questStart) // not in expected required quest state
if (!player || ((!questStartCanActive || !player->IsActiveQuest(questStart)) && !player->GetQuestRewardStatus(questStart)))
return false;
if (questEnd) // not in expected forbidden quest state
if (!player || player->GetQuestRewardStatus(questEnd))
return false;
if (auraSpell) // not have expected aura
if (!player || (auraSpell > 0 && !player->HasAura(auraSpell)) || (auraSpell < 0 && player->HasAura(-auraSpell)))
return false;
// Extra conditions -- leaving the possibility add extra conditions...
switch(spellId)
{
case 58600: // No fly Zone - Dalaran
{
if (!player)
return false;
AreaTableEntry const* pArea = GetAreaEntryByAreaID(player->GetAreaId());
if (!(pArea && pArea->flags & AREA_FLAG_NO_FLY_ZONE))
return false;
if (!player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !player->HasAuraType(SPELL_AURA_FLY))
return false;
break;
}
case SPELL_OIL_REFINERY: // Oil Refinery - Isle of Conquest.
case SPELL_QUARRY: // Quarry - Isle of Conquest.
{
if (player->GetBattlegroundTypeId() != BATTLEGROUND_IC || !player->GetBattleground())
return false;
uint8 nodeType = spellId == SPELL_OIL_REFINERY ? NODE_TYPE_REFINERY : NODE_TYPE_QUARRY;
uint8 nodeState = player->GetTeamId() == TEAM_ALLIANCE ? NODE_STATE_CONTROLLED_A : NODE_STATE_CONTROLLED_H;
BattlegroundIC* pIC = static_cast<BattlegroundIC*>(player->GetBattleground());
if (pIC->GetNodeState(nodeType) == nodeState)
return true;
return false;
}
}
return true;
}
//-----------TRINITY-------------
bool SpellMgr::CanAurasStack(Aura const *aura1, Aura const *aura2, bool sameCaster) const
{
SpellEntry const *spellInfo_1 = aura1->GetSpellProto();
SpellEntry const *spellInfo_2 = aura2->GetSpellProto();
SpellSpecific spellSpec_1 = GetSpellSpecific(spellInfo_1);
SpellSpecific spellSpec_2 = GetSpellSpecific(spellInfo_2);
if (spellSpec_1 && spellSpec_2)
if (IsSingleFromSpellSpecificPerTarget(spellSpec_1, spellSpec_2)
|| (sameCaster && IsSingleFromSpellSpecificPerCaster(spellSpec_1, spellSpec_2)))
return false;
SpellGroupStackRule stackRule = CheckSpellGroupStackRules(spellInfo_1->Id, spellInfo_2->Id);
if (stackRule)
{
if (stackRule == SPELL_GROUP_STACK_RULE_EXCLUSIVE)
return false;
if (sameCaster && stackRule == SPELL_GROUP_STACK_RULE_EXCLUSIVE_FROM_SAME_CASTER)
return false;
}
if (spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName)
return true;
if (!sameCaster)
{
if (spellInfo_1->AttributesEx & SPELL_ATTR1_STACK_FOR_DIFF_CASTERS
|| spellInfo_1->AttributesEx3 & SPELL_ATTR3_STACK_FOR_DIFF_CASTERS)
return true;
// check same periodic auras
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch(spellInfo_1->EffectApplyAuraName[i])
{
// DOT or HOT from different casters will stack
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DUMMY:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
case SPELL_AURA_PERIODIC_ENERGIZE:
case SPELL_AURA_PERIODIC_MANA_LEECH:
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_POWER_BURN_MANA:
case SPELL_AURA_OBS_MOD_POWER:
case SPELL_AURA_OBS_MOD_HEALTH:
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
// periodic auras which target areas are not allowed to stack this way (replenishment for example)
if (IsAreaOfEffectSpellEffect(spellInfo_1, i) || IsAreaOfEffectSpellEffect(spellInfo_2, i))
break;
return true;
default:
break;
}
}
}
bool isVehicleAura1 = false;
bool isVehicleAura2 = false;
uint8 i = 0;
while (i < MAX_SPELL_EFFECTS && !(isVehicleAura1 && isVehicleAura2))
{
if (spellInfo_1->EffectApplyAuraName[i] == SPELL_AURA_CONTROL_VEHICLE)
isVehicleAura1 = true;
if (spellInfo_2->EffectApplyAuraName[i] == SPELL_AURA_CONTROL_VEHICLE)
isVehicleAura2 = true;
++i;
}
if (isVehicleAura1 && isVehicleAura2)
{
Vehicle* veh = NULL;
if (aura1->GetOwner()->ToUnit())
veh = aura1->GetOwner()->ToUnit()->GetVehicleKit();
if (!veh) // We should probably just let it stack. Vehicle system will prevent undefined behaviour later
return true;
if (!veh->GetAvailableSeatCount())
return false; // No empty seat available
return true; // Empty seat available (skip rest)
}
uint32 spellId_1 = GetLastSpellInChain(spellInfo_1->Id);
uint32 spellId_2 = GetLastSpellInChain(spellInfo_2->Id);
// same spell
if (spellId_1 == spellId_2)
{
// Hack for Incanter's Absorption
if (spellId_1 == 44413)
return true;
if (aura1->GetCastItemGUID() && aura2->GetCastItemGUID())
if (aura1->GetCastItemGUID() != aura2->GetCastItemGUID() && (GetSpellCustomAttr(spellId_1) & SPELL_ATTR0_CU_ENCHANT_PROC))
return true;
// same spell with same caster should not stack
return false;
}
return true;
}
bool CanSpellDispelAura(SpellEntry const * dispelSpell, SpellEntry const * aura)
{
// These auras (like ressurection sickness) can't be dispelled
if (aura->Attributes & SPELL_ATTR0_NEGATIVE_1)
return false;
// These spells (like Mass Dispel) can dispell all auras
if (dispelSpell->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return true;
// These auras (like Divine Shield) can't be dispelled
if (aura->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return false;
// These auras (Cyclone for example) are not dispelable
if (aura->AttributesEx & SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE)
return false;
return true;
}
bool CanSpellPierceImmuneAura(SpellEntry const * pierceSpell, SpellEntry const * aura)
{
// these spells pierce all avalible spells (Resurrection Sickness for example)
if (pierceSpell->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return true;
// these spells (Cyclone for example) can pierce all...
if ((pierceSpell->AttributesEx & SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE)
// ...but not these (Divine shield for example)
&& !(aura && (aura->Mechanic == MECHANIC_IMMUNE_SHIELD || aura->Mechanic == MECHANIC_INVULNERABILITY)))
return true;
return false;
}
void SpellMgr::LoadSpellEnchantProcData()
{
uint32 oldMSTime = getMSTime();
mSpellEnchantProcEventMap.clear(); // need for reload case
uint32 count = 0;
// 0 1 2 3
QueryResult result = WorldDatabase.Query("SELECT entry, customChance, PPMChance, procEx FROM spell_enchant_proc_data");
if (!result)
{
sLog->outString(">> Loaded %u spell enchant proc event conditions", count);
sLog->outString();
return;
}
do
{
Field *fields = result->Fetch();
uint32 enchantId = fields[0].GetUInt32();
SpellItemEnchantmentEntry const *ench = sSpellItemEnchantmentStore.LookupEntry(enchantId);
if (!ench)
{
sLog->outErrorDb("Enchancment %u listed in `spell_enchant_proc_data` does not exist", enchantId);
continue;
}
SpellEnchantProcEntry spe;
spe.customChance = fields[1].GetUInt32();
spe.PPMChance = fields[2].GetFloat();
spe.procEx = fields[3].GetUInt32();
mSpellEnchantProcEventMap[enchantId] = spe;
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u enchant proc data definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellRequired()
{
uint32 oldMSTime = getMSTime();
mSpellsReqSpell.clear(); // need for reload case
mSpellReq.clear(); // need for reload case
QueryResult result = WorldDatabase.Query("SELECT spell_id, req_spell from spell_required");
if (!result)
{
sLog->outString(">> Loaded 0 spell required records");
sLog->outString();
sLog->outErrorDb("`spell_required` table is empty!");
return;
}
uint32 rows = 0;
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
uint32 spell_req = fields[1].GetUInt32();
// check if chain is made with valid first spell
SpellEntry const * spell = sSpellStore.LookupEntry(spell_id);
if (!spell)
{
sLog->outErrorDb("spell_id %u in `spell_required` table is not found in dbcs, skipped", spell_id);
continue;
}
SpellEntry const * req_spell = sSpellStore.LookupEntry(spell_req);
if (!req_spell)
{
sLog->outErrorDb("req_spell %u in `spell_required` table is not found in dbcs, skipped", spell_req);
continue;
}
if (GetFirstSpellInChain(spell_id) == GetFirstSpellInChain(spell_req))
{
sLog->outErrorDb("req_spell %u and spell_id %u in `spell_required` table are ranks of the same spell, entry not needed, skipped", spell_req, spell_id);
continue;
}
if (IsSpellRequiringSpell(spell_id, spell_req))
{
sLog->outErrorDb("duplicated entry of req_spell %u and spell_id %u in `spell_required`, skipped", spell_req, spell_id);
continue;
}
mSpellReq.insert (std::pair<uint32, uint32>(spell_id, spell_req));
mSpellsReqSpell.insert (std::pair<uint32, uint32>(spell_req, spell_id));
++rows;
} while (result->NextRow());
sLog->outString(">> Loaded %u spell required records in %u ms", rows, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellRanks()
{
uint32 oldMSTime = getMSTime();
mSpellChains.clear(); // need for reload case
QueryResult result = WorldDatabase.Query("SELECT first_spell_id, spell_id, rank from spell_ranks ORDER BY first_spell_id , rank");
if (!result)
{
sLog->outString(">> Loaded 0 spell rank records");
sLog->outString();
sLog->outErrorDb("`spell_ranks` table is empty!");
return;
}
uint32 rows = 0;
bool finished = false;
do
{
// spellid, rank
std::list < std::pair < int32, int32 > > rankChain;
int32 currentSpell = -1;
int32 lastSpell = -1;
// fill one chain
while (currentSpell == lastSpell && !finished)
{
Field *fields = result->Fetch();
currentSpell = fields[0].GetUInt32();
if (lastSpell == -1)
lastSpell = currentSpell;
uint32 spell_id = fields[1].GetUInt32();
uint32 rank = fields[2].GetUInt32();
// don't drop the row if we're moving to the next rank
if (currentSpell == lastSpell)
{
rankChain.push_back(std::make_pair(spell_id, rank));
if (!result->NextRow())
finished = true;
}
else
break;
}
// check if chain is made with valid first spell
SpellEntry const * first = sSpellStore.LookupEntry(lastSpell);
if (!first)
{
sLog->outErrorDb("Spell rank identifier(first_spell_id) %u listed in `spell_ranks` does not exist!", lastSpell);
continue;
}
// check if chain is long enough
if (rankChain.size() < 2)
{
sLog->outErrorDb("There is only 1 spell rank for identifier(first_spell_id) %u in `spell_ranks`, entry is not needed!", lastSpell);
continue;
}
int32 curRank = 0;
bool valid = true;
// check spells in chain
for (std::list<std::pair<int32, int32> >::iterator itr = rankChain.begin() ; itr!= rankChain.end(); ++itr)
{
SpellEntry const * spell = sSpellStore.LookupEntry(itr->first);
if (!spell)
{
sLog->outErrorDb("Spell %u (rank %u) listed in `spell_ranks` for chain %u does not exist!", itr->first, itr->second, lastSpell);
valid = false;
break;
}
++curRank;
if (itr->second != curRank)
{
sLog->outErrorDb("Spell %u (rank %u) listed in `spell_ranks` for chain %u does not have proper rank value(should be %u)!", itr->first, itr->second, lastSpell, curRank);
valid = false;
break;
}
}
if (!valid)
continue;
int32 prevRank = 0;
// insert the chain
std::list<std::pair<int32, int32> >::iterator itr = rankChain.begin();
do
{
++rows;
int32 addedSpell = itr->first;
mSpellChains[addedSpell].first = lastSpell;
mSpellChains[addedSpell].last = rankChain.back().first;
mSpellChains[addedSpell].rank = itr->second;
mSpellChains[addedSpell].prev = prevRank;
prevRank = addedSpell;
++itr;
if (itr == rankChain.end())
{
mSpellChains[addedSpell].next = 0;
break;
}
else
mSpellChains[addedSpell].next = itr->first;
}
while (true);
} while (!finished);
sLog->outString(">> Loaded %u spell rank records in %u ms", rows, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
// set data in core for now
void SpellMgr::LoadSpellCustomAttr()
{
uint32 oldMSTime = getMSTime();
mSpellCustomAttr.resize(GetSpellStore()->GetNumRows(), 0); // initialize with 0 values
uint32 count = 0;
SpellEntry* spellInfo = NULL;
for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i)
{
spellInfo = (SpellEntry*)sSpellStore.LookupEntry(i);
if (!spellInfo)
continue;
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
switch (spellInfo->Effect[j])
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
case SPELL_EFFECT_HEAL:
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_DIRECT_DAMAGE;
count++;
break;
case SPELL_EFFECT_CHARGE:
case SPELL_EFFECT_CHARGE_DEST:
case SPELL_EFFECT_JUMP:
case SPELL_EFFECT_JUMP_DEST:
case SPELL_EFFECT_LEAP_BACK:
if (!spellInfo->speed && !spellInfo->SpellFamilyName)
spellInfo->speed = SPEED_CHARGE;
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_CHARGE;
count++;
break;
case SPELL_EFFECT_PICKPOCKET:
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_PICKPOCKET;
break;
case SPELL_EFFECT_TRIGGER_SPELL:
if (IsPositionTarget(spellInfo->EffectImplicitTargetA[j]) ||
spellInfo->Targets & (TARGET_FLAG_SOURCE_LOCATION|TARGET_FLAG_DEST_LOCATION))
spellInfo->Effect[j] = SPELL_EFFECT_TRIGGER_MISSILE;
count++;
break;
case SPELL_EFFECT_ENCHANT_ITEM:
case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
case SPELL_EFFECT_ENCHANT_HELD_ITEM:
{
// only enchanting profession enchantments procs can stack
if (IsPartOfSkillLine(SKILL_ENCHANTING, i))
{
uint32 enchantId = spellInfo->EffectMiscValue[j];
SpellItemEnchantmentEntry const *enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId);
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
if (enchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEntry const *procInfo = sSpellStore.LookupEntry(enchant->spellid[s]);
if (!procInfo)
continue;
// if proced directly from enchantment, not via proc aura
// NOTE: Enchant Weapon - Blade Ward also has proc aura spell and is proced directly
// however its not expected to stack so this check is good
if (IsSpellHaveAura(procInfo, SPELL_AURA_PROC_TRIGGER_SPELL))
continue;
mSpellCustomAttr[enchant->spellid[s]] |= SPELL_ATTR0_CU_ENCHANT_PROC;
}
}
break;
}
}
switch (SpellTargetType[spellInfo->EffectImplicitTargetA[j]])
{
case TARGET_TYPE_UNIT_TARGET:
case TARGET_TYPE_DEST_TARGET:
spellInfo->Targets |= TARGET_FLAG_UNIT;
count++;
break;
default:
break;
}
}
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
switch (spellInfo->EffectApplyAuraName[j])
{
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CONFUSE:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_AOE_CHARM:
case SPELL_AURA_MOD_FEAR:
case SPELL_AURA_MOD_STUN:
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_AURA_CC;
count++;
break;
}
}
if (!_isPositiveEffect(i, 0, false))
{
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_NEGATIVE_EFF0;
count++;
}
if (!_isPositiveEffect(i, 1, false))
{
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_NEGATIVE_EFF1;
count++;
}
if (!_isPositiveEffect(i, 2, false))
{
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_NEGATIVE_EFF2;
count++;
}
if (spellInfo->SpellVisual[0] == 3879)
{
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_CONE_BACK;
count++;
}
if (spellInfo->activeIconID == 2158) // flight
{
spellInfo->Attributes |= SPELL_ATTR0_PASSIVE;
count++;
}
switch (i)
{
case 36350: //They Must Burn Bomb Aura (self)
spellInfo->EffectTriggerSpell[0] = 36325; // They Must Burn Bomb Drop (DND)
count++;
break;
case 49838: // Stop Time
case 50526: // Wandering Plague
case 52916: // Honor Among Thieves
spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO;
count++;
break;
case 61407: // Energize Cores
case 62136: // Energize Cores
case 54069: // Energize Cores
case 56251: // Energize Cores
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_AREA_ENTRY_SRC;
count++;
break;
case 50785: // Energize Cores
case 59372: // Energize Cores
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_AREA_ENEMY_SRC;
count++;
break;
// Bind
case 3286:
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY;
spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ENEMY;
count++;
break;
// Heroism
case 32182:
spellInfo->excludeCasterAuraSpell = 57723; // Exhaustion
count++;
break;
// Blazing Harpoon
case 61588:
spellInfo->MaxAffectedTargets = 1;
count++;
break;
// Bloodlust
case 2825:
spellInfo->excludeCasterAuraSpell = 57724; // Sated
count++;
break;
// Heart of the Crusader
case 20335:
case 20336:
case 20337:
// Glyph of Life Tap
case 63320:
// Entries were not updated after spell effect change, we have to do that manually :/
spellInfo->AttributesEx3 |= SPELL_ATTR3_CAN_PROC_TRIGGERED;
count++;
break;
case 16007: // Draco-Incarcinatrix 900
// was 46, but effect is aura effect
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_NEARBY_ENTRY;
spellInfo->EffectImplicitTargetB[0] = TARGET_DST_NEARBY_ENTRY;
count++;
break;
case 26029: // dark glare
case 37433: // spout
case 43140: case 43215: // flame breath
case 70461: // Coldflame Trap
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_CONE_LINE;
count++;
break;
case 24340: case 26558: case 28884: // Meteor
case 36837: case 38903: case 41276: // Meteor
case 57467: // Meteor
case 26789: // Shard of the Fallen Star
case 31436: // Malevolent Cleave
case 35181: // Dive Bomb
case 40810: case 43267: case 43268: // Saber Lash
case 42384: // Brutal Swipe
case 45150: // Meteor Slash
case 64422: case 64688: // Sonic Screech
case 72373: // Shared Suffering
case 71904: // Chaos Bane
case 70492: case 72505: // Ooze Eruption
case 72624: case 72625: // Ooze Eruption
// ONLY SPELLS WITH SPELLFAMILY_GENERIC and EFFECT_SCHOOL_DAMAGE
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_SHARE_DAMAGE;
count++;
break;
case 59725: // Improved Spell Reflection - aoe aura
// Target entry seems to be wrong for this spell :/
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_PARTY_CASTER;
spellInfo->EffectRadiusIndex[0] = 45;
count++;
break;
case 27820: // Mana Detonation
//case 28062: case 39090: // Positive/Negative Charge
//case 28085: case 39093:
case 69782: case 69796: // Ooze Flood
case 69798: case 69801: // Ooze Flood
case 69538: case 69553: case 69610: // Ooze Combine
case 71447: case 71481: // Bloodbolt Splash
case 71482: case 71483: // Bloodbolt Splash
case 71390: // Pact of the Darkfallen
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_EXCLUDE_SELF;
count++;
break;
case 44978: case 45001: case 45002: // Wild Magic
case 45004: case 45006: case 45010: // Wild Magic
case 31347: // Doom
case 41635: // Prayer of Mending
case 44869: // Spectral Blast
case 45027: // Revitalize
case 45976: // Muru Portal Channel
case 39365: // Thundering Storm
case 41071: // Raise Dead (HACK)
case 52124: // Sky Darkener Assault
case 42442: // Vengeance Landing Cannonfire
case 45863: // Cosmetic - Incinerate to Random Target
case 25425: // Shoot
case 45761: // Shoot
case 42611: // Shoot
case 62374: // Pursued
spellInfo->MaxAffectedTargets = 1;
count++;
break;
case 52479: // Gift of the Harvester
spellInfo->MaxAffectedTargets = 1;
// a trap always has dst = src?
spellInfo->EffectImplicitTargetA[0] = TARGET_DST_CASTER;
spellInfo->EffectImplicitTargetA[1] = TARGET_DST_CASTER;
count++;
break;
case 41376: // Spite
case 39992: // Needle Spine
case 29576: // Multi-Shot
case 40816: // Saber Lash
case 37790: // Spread Shot
case 46771: // Flame Sear
case 45248: // Shadow Blades
case 41303: // Soul Drain
case 54172: // Divine Storm (heal)
case 29213: // Curse of the Plaguebringer - Noth
case 28542: // Life Drain - Sapphiron
case 66588: // Flaming Spear
case 54171: // Divine Storm
spellInfo->MaxAffectedTargets = 3;
count++;
break;
case 38310: // Multi-Shot
case 53385: // Divine Storm (Damage)
spellInfo->MaxAffectedTargets = 4;
count++;
break;
case 42005: // Bloodboil
case 38296: // Spitfire Totem
case 37676: // Insidious Whisper
case 46008: // Negative Energy
case 45641: // Fire Bloom
case 55665: // Life Drain - Sapphiron (H)
case 28796: // Poison Bolt Volly - Faerlina
spellInfo->MaxAffectedTargets = 5;
count++;
break;
case 40827: // Sinful Beam
case 40859: // Sinister Beam
case 40860: // Vile Beam
case 40861: // Wicked Beam
case 54835: // Curse of the Plaguebringer - Noth (H)
case 54098: // Poison Bolt Volly - Faerlina (H)
spellInfo->MaxAffectedTargets = 10;
count++;
break;
case 50312: // Unholy Frenzy
spellInfo->MaxAffectedTargets = 15;
count++;
break;
case 38794: case 33711: //Murmur's Touch
spellInfo->MaxAffectedTargets = 1;
spellInfo->EffectTriggerSpell[0] = 33760;
count++;
break;
case 17941: // Shadow Trance
case 22008: // Netherwind Focus
case 31834: // Light's Grace
case 34754: // Clearcasting
case 34936: // Backlash
case 48108: // Hot Streak
case 51124: // Killing Machine
case 54741: // Firestarter
case 57761: // Fireball!
case 39805: // Lightning Overload
case 64823: // Item - Druid T8 Balance 4P Bonus
case 44401:
spellInfo->procCharges = 1;
count++;
break;
case 53390: // Tidal Wave
spellInfo->procCharges = 2;
count++;
break;
case 44544: // Fingers of Frost
spellInfo->EffectSpellClassMask[0] = flag96(685904631, 1151048, 0);
count++;
break;
case 74396: // Fingers of Frost visual buff
spellInfo->procCharges = 2;
spellInfo->StackAmount = 0;
count++;
break;
case 28200: // Ascendance (Talisman of Ascendance trinket)
spellInfo->procCharges = 6;
count++;
break;
case 47201: // Everlasting Affliction
case 47202:
case 47203:
case 47204:
case 47205:
// add corruption to affected spells
spellInfo->EffectSpellClassMask[1][0] |= 2;
count++;
break;
case 49305:
spellInfo->EffectImplicitTargetB[0] = 1;
count++;
break;
case 51852: // The Eye of Acherus (no spawn in phase 2 in db)
spellInfo->EffectMiscValue[0] |= 1;
count++;
break;
case 52025: // Cleansing Totem Effect
spellInfo->EffectDieSides[1] = 1;
count++;
break;
case 51904: // Summon Ghouls On Scarlet Crusade (core does not know the triggered spell is summon spell)
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
count++;
break;
case 29809: // Desecration Arm - 36 instead of 37 - typo? :/
spellInfo->EffectRadiusIndex[0] = 37;
count++;
break;
// Master Shapeshifter: missing stance data for forms other than bear - bear version has correct data
// To prevent aura staying on target after talent unlearned
case 48420:
spellInfo->Stances = 1 << (FORM_CAT - 1);
count++;
break;
case 48421:
spellInfo->Stances = 1 << (FORM_MOONKIN - 1);
count++;
break;
case 48422:
spellInfo->Stances = 1 << (FORM_TREE - 1);
count++;
break;
case 30421: // Nether Portal - Perseverence
spellInfo->EffectBasePoints[2] += 30000;
count++;
break;
case 62324: // Throw Passenger
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
count++;
break;
case 66665: // Burning Breath
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY;
count++;
break;
case 62907: // Freya's Ward
case 62947:
spellInfo->DurationIndex = 0;
count++;
break;
case 62713: // Ironbranch's Essence
case 62968: // Brightleaf's Essence
spellInfo->DurationIndex = 39;
count++;
break;
case 62661: // Searing Flames
case 61915: // Lightning Whirl 10
case 63483: // Lightning Whirl 25
spellInfo->InterruptFlags = 47;
count++;
break;
case 16834: // Natural shapeshifter
case 16835:
spellInfo->DurationIndex = 21;
count++;
break;
case 51735: // Ebon Plague
case 51734:
case 51726:
spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS;
spellInfo->SpellFamilyFlags[2] = 0x10;
count++;
break;
case 41013: // Parasitic Shadowfiend Passive
spellInfo->EffectApplyAuraName[0] = 4; // proc debuff, and summon infinite fiends
count++;
break;
case 27892: // To Anchor 1
case 27928: // To Anchor 1
case 27935: // To Anchor 1
case 27915: // Anchor to Skulls
case 27931: // Anchor to Skulls
case 27937: // Anchor to Skulls
spellInfo->rangeIndex = 13;
count++;
break;
case 48743: // Death Pact
spellInfo->AttributesEx &= ~SPELL_ATTR1_CANT_TARGET_SELF;
count++;
break;
// target allys instead of enemies, target A is src_caster, spells with effect like that have ally target
// this is the only known exception, probably just wrong data
case 29214: // Wrath of the Plaguebringer
case 54836: // Wrath of the Plaguebringer
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_AREA_ALLY_SRC;
spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_AREA_ALLY_SRC;
count++;
break;
case 31687: // Summon Water Elemental
// 322-330 switch - effect changed to dummy, target entry not changed in client:(
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
count++;
break;
case 25771: // Forbearance - wrong mechanic immunity in DBC since 3.0.x
spellInfo->EffectMiscValue[0] = MECHANIC_IMMUNE_SHIELD;
count++;
break;
case 64321: // Potent Pheromones
// spell should dispel area aura, but doesn't have the attribute
// may be db data bug, or blizz may keep reapplying area auras every update with checking immunity
// that will be clear if we get more spells with problem like this
spellInfo->AttributesEx |= SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY;
count++;
break;
case 18500: // Wing Buffet
case 33086: // Wild Bite
case 49749: // Piercing Blow
case 52890: // Penetrating Strike
case 53454: // Impale
case 59446: // Impale
case 62383: // Shatter
case 64777: // Machine Gun
case 65239: // Machine Gun
case 65919: // Impale
case 67858: // Impale
case 67859: // Impale
case 67860: // Impale
case 69293: // Wing Buffet
case 74439: // Machine Gun
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_IGNORE_ARMOR;
count++;
break;
// Strength of the Pack
case 64381:
spellInfo->StackAmount = 4;
count++;
break;
case 63675: // Improved Devouring Plague
spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS;
count++;
break;
case 33206: // Pain Suppression
spellInfo->AttributesEx5 &= ~SPELL_ATTR5_USABLE_WHILE_STUNNED;
count++;
break;
case 53241: // Marked for Death (Rank 1)
case 53243: // Marked for Death (Rank 2)
case 53244: // Marked for Death (Rank 3)
case 53245: // Marked for Death (Rank 4)
case 53246: // Marked for Death (Rank 5)
spellInfo->EffectSpellClassMask[0] = flag96(423937, 276955137, 2049);
count++;
break;
case 70728: // Exploit Weakness
case 70840: // Devious Minds
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_PET;
count++;
break;
case 70893: // Culling The Herd
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_MASTER;
count++;
break;
// ULDUAR SPELLS
//
case 63342: // Focused Eyebeam Summon Trigger
spellInfo->MaxAffectedTargets = 1;
count++;
break;
case 64145: // Diminish Power
case 63882: // Death Ray Warning Visual
case 63886: // Death Ray Damage Visual
spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS;
count++;
break;
case 64172: // Titanic Storm
spellInfo->excludeTargetAuraSpell = 65294; // Empowered
count++;
break;
case 63830: // Malady of the Mind
case 63881: // Malady of the Mind proc
case 63795: // Psychosis
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ANY;
spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_TARGET_ANY;
spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_TARGET_ANY;
count++;
break;
case 63802: // Brain Link
spellInfo->MaxAffectedTargets = 2;
spellInfo->EffectRadiusIndex[0] = 12; // 100 yard
count++;
break;
case 63050: // Sanity
spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT;
count++;
break;
// ENDOF ULDUAR SPELLS
//
// ICECROWN CITADEL SPELLS
//
// THESE SPELLS ARE WORKING CORRECTLY EVEN WITHOUT THIS HACK
// THE ONLY REASON ITS HERE IS THAT CURRENT GRID SYSTEM
// DOES NOT ALLOW FAR OBJECT SELECTION (dist > 333)
case 70781: // Light's Hammer Teleport
case 70856: // Oratory of the Damned Teleport
case 70857: // Rampart of Skulls Teleport
case 70858: // Deathbringer's Rise Teleport
case 70859: // Upper Spire Teleport
case 70860: // Frozen Throne Teleport
case 70861: // Sindragosa's Lair Teleport
spellInfo->EffectImplicitTargetA[0] = TARGET_DST_DB;
count++;
break;
case 69055: // Saber Lash (Lord Marrowgar)
case 70814: // Saber Lash (Lord Marrowgar)
spellInfo->EffectRadiusIndex[0] = 8;
count++;
break;
case 69075: // Bone Storm (Lord Marrowgar)
case 70834: // Bone Storm (Lord Marrowgar)
case 70835: // Bone Storm (Lord Marrowgar)
case 70836: // Bone Storm (Lord Marrowgar)
case 72864: // Death Plague (Rotting Frost Giant)
case 72378: // Blood Nova (Deathbringer Saurfang)
case 73058: // Blood Nova (Deathbringer Saurfang)
spellInfo->EffectRadiusIndex[0] = 12;
count++;
break;
case 72385: // Boiling Blood (Deathbringer Saurfang)
case 72441: // Boiling Blood (Deathbringer Saurfang)
case 72442: // Boiling Blood (Deathbringer Saurfang)
case 72443: // Boiling Blood (Deathbringer Saurfang)
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY;
spellInfo->EffectImplicitTargetB[0] = 0;
count++;
break;
case 70460: // Coldflame Jets (Traps after Saurfang)
spellInfo->DurationIndex = 1; // 10 seconds
count++;
break;
case 71413: // Green Ooze Summon (Professor Putricide)
case 71414: // Orange Ooze Summon (Professor Putricide)
spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST;
count++;
break;
// this is here until targetAuraSpell and alike support SpellDifficulty.dbc
case 70459: // Ooze Eruption Search Effect (Professor Putricide)
spellInfo->targetAuraSpell = 0;
count++;
break;
// THIS IS HERE BECAUSE COOLDOWN ON CREATURE PROCS IS NOT IMPLEMENTED
case 71604: // Mutated Strength (Professor Putricide)
case 72673: // Mutated Strength (Professor Putricide)
case 72674: // Mutated Strength (Professor Putricide)
case 72675: // Mutated Strength (Professor Putricide)
spellInfo->Effect[1] = 0;
count++;
break;
case 70447: // Volatile Ooze Adhesive (Professor Putricide)
case 72836: // Volatile Ooze Adhesive (Professor Putricide)
case 72837: // Volatile Ooze Adhesive (Professor Putricide)
case 72838: // Volatile Ooze Adhesive (Professor Putricide)
case 70672: // Gaseous Bloat (Professor Putricide)
case 72455: // Gaseous Bloat (Professor Putricide)
case 72832: // Gaseous Bloat (Professor Putricide)
case 72833: // Gaseous Bloat (Professor Putricide)
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ENEMY;
spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_TARGET_ENEMY;
spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_TARGET_ENEMY;
count++;
break;
case 70911: // Unbound Plague (Professor Putricide)
case 72854: // Unbound Plague (Professor Putricide)
case 72855: // Unbound Plague (Professor Putricide)
case 72856: // Unbound Plague (Professor Putricide)
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ENEMY;
count++;
break;
case 71518: // Unholy Infusion Quest Credit (Professor Putricide)
case 72934: // Blood Infusion Quest Credit (Blood-Queen Lana'thel)
case 72289: // Frost Infusion Quest Credit (Sindragosa)
spellInfo->EffectRadiusIndex[0] = 28; // another missing radius
count++;
break;
case 71708: // Empowered Flare (Blood Prince Council)
case 72785: // Empowered Flare (Blood Prince Council)
case 72786: // Empowered Flare (Blood Prince Council)
case 72787: // Empowered Flare (Blood Prince Council)
spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS;
count++;
break;
case 71340: // Pact of the Darkfallen (Blood-Queen Lana'thel)
spellInfo->DurationIndex = 21;
count++;
break;
case 71266: // Swarming Shadows
spellInfo->AreaGroupId = 0;
count++;
break;
case 71357: // Order Whelp
spellInfo->EffectRadiusIndex[0] = 22;
count++;
break;
case 70598: // Sindragosa's Fury
spellInfo->EffectImplicitTargetA[0] = TARGET_DST_CASTER;
count++;
break;
case 69846: // Frost Bomb
spellInfo->speed = 10;
spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_TARGET_ANY;
spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ANY;
spellInfo->Effect[1] = 0;
count++;
break;
case 51590: // Toss Ice Boulder
spellInfo->MaxAffectedTargets = 1;
count++;
break;
case 49224: // Magic Suppression
case 49611:
case 57935: // Twilight Torment
spellInfo->procCharges = 0;
count++;
break;
case 45524: // Chains of Ice
spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ENEMY;
count++;
break;
case 18754: // Improved Seduction
case 18755:
case 18756:
spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER;
count++;
break;
case 20467: // Judgement of Command
spellInfo->EffectBasePoints[1] = 19;
count++;
break;
case 59630:
spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT;
count++;
break;
case 64936:
spellInfo->EffectBasePoints[0] = 99;
count++;
break;
case 29175: // Ribbon Dance Customization
spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT;
spellInfo->Effect[0] = 6;
spellInfo->Effect[1] = 6;
spellInfo->EffectApplyAuraName[0] = SPELL_AURA_MOD_XP_PCT;
spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_XP_QUEST_PCT;
spellInfo->EffectBasePoints[0] = 10;
spellInfo->EffectBasePoints[1] = 10;
spellInfo->EffectImplicitTargetA[0] = 1;
spellInfo->EffectImplicitTargetA[1] = 1;
spellInfo->EffectImplicitTargetB[0] = 0;
spellInfo->EffectImplicitTargetB[1] = 0;
spellInfo->EffectRadiusIndex[0] = 0;
spellInfo->EffectRadiusIndex[1] = 0;
spellInfo->StackAmount = 5;
spellInfo->DurationIndex = 30;
count++;
break;
case 53480: // Roar of Sacrifice Split damage
spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA;
spellInfo->EffectApplyAuraName[1] = SPELL_AURA_SPLIT_DAMAGE_PCT;
spellInfo->EffectMiscValue[1] = 127;
count++;
break;
case 23126: // World Enlarger
spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_SPELL_ATTACK;
count++;
break;
case 70890: // Scourge Strike Triggered
spellInfo->AttributesEx2 |= SPELL_ATTR2_TRIGGERED_CAN_TRIGGER;
count++;
break;
case 49206: // Summon Gargoyle
spellInfo->DurationIndex = 587;
count++;
break;
default:
break;
}
switch (spellInfo->SpellFamilyName)
{
case SPELLFAMILY_WARRIOR:
// Shout
if (spellInfo->SpellFamilyFlags[0] & 0x20000 || spellInfo->SpellFamilyFlags[1] & 0x20)
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_AURA_CC;
else
break;
count++;
break;
case SPELLFAMILY_DRUID:
// Starfall Target Selection
if (spellInfo->SpellFamilyFlags[2] & 0x100)
spellInfo->MaxAffectedTargets = 2;
// Starfall AOE Damage
else if (spellInfo->SpellFamilyFlags[2] & 0x800000)
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_EXCLUDE_SELF;
// Roar
else if (spellInfo->SpellFamilyFlags[0] & 0x8)
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_AURA_CC;
// Entangling Roots
else if (spellInfo->SpellFamilyFlags[0] & 0x200 && spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_SITTING)
spellInfo->CastingTimeIndex = 1;
// Rake
else if (spellInfo->SpellFamilyFlags[0] & 0x1000)
mSpellCustomAttr[i] |= SPELL_ATTR0_CU_IGNORE_ARMOR;
else
break;
count++;
break;
// Do not allow Deadly throw and Slice and Dice to proc twice
case SPELLFAMILY_ROGUE:
if (spellInfo->SpellFamilyFlags[1] & 0x1 || spellInfo->SpellFamilyFlags[0] & 0x40000)
spellInfo->AttributesEx4 |= SPELL_ATTR4_CANT_PROC_FROM_SELFCAST;
else
break;
count++;
break;
}
}
SummonPropertiesEntry *properties = const_cast<SummonPropertiesEntry*>(sSummonPropertiesStore.LookupEntry(121));
properties->Type = SUMMON_TYPE_TOTEM;
properties = const_cast<SummonPropertiesEntry*>(sSummonPropertiesStore.LookupEntry(647)); // 52893
properties->Type = SUMMON_TYPE_TOTEM;
CreatureAI::FillAISpellInfo();
sLog->outString(">> Loaded %u custom spell attributes in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
// Fill custom data about enchancments
void SpellMgr::LoadEnchantCustomAttr()
{
uint32 oldMSTime = getMSTime();
uint32 size = sSpellItemEnchantmentStore.GetNumRows();
mEnchantCustomAttr.resize(size);
uint32 count = 0;
for (uint32 i = 0; i < size; ++i)
mEnchantCustomAttr[i] = 0;
for (uint32 i = 0; i < GetSpellStore()->GetNumRows(); ++i)
{
SpellEntry * spellInfo = (SpellEntry*)GetSpellStore()->LookupEntry(i);
if (!spellInfo)
continue;
// TODO: find a better check
if (!(spellInfo->AttributesEx2 & SPELL_ATTR2_UNK13) || !(spellInfo->Attributes & SPELL_ATTR0_NOT_SHAPESHIFT))
continue;
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (spellInfo->Effect[j] == SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY)
{
uint32 enchId = spellInfo->EffectMiscValue[j];
SpellItemEnchantmentEntry const *ench = sSpellItemEnchantmentStore.LookupEntry(enchId);
if (!ench)
continue;
mEnchantCustomAttr[enchId] = true;
count++;
break;
}
}
}
sLog->outString(">> Loaded %u custom enchant attributes in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void SpellMgr::LoadSpellLinked()
{
uint32 oldMSTime = getMSTime();
mSpellLinkedMap.clear(); // need for reload case
// 0 1 2
QueryResult result = WorldDatabase.Query("SELECT spell_trigger, spell_effect, type FROM spell_linked_spell");
if (!result)
{
sLog->outString(">> Loaded 0 linked spells. DB table `spell_linked_spell` is empty.");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field *fields = result->Fetch();
int32 trigger = fields[0].GetInt32();
int32 effect = fields[1].GetInt32();
int32 type = fields[2].GetInt32();
SpellEntry const* spellInfo = sSpellStore.LookupEntry(abs(trigger));
if (!spellInfo)
{
sLog->outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(trigger));
continue;
}
spellInfo = sSpellStore.LookupEntry(abs(effect));
if (!spellInfo)
{
sLog->outErrorDb("Spell %u listed in `spell_linked_spell` does not exist", abs(effect));
continue;
}
if (trigger > 0)
{
switch(type)
{
case 0: mSpellCustomAttr[trigger] |= SPELL_ATTR0_CU_LINK_CAST; break;
case 1: mSpellCustomAttr[trigger] |= SPELL_ATTR0_CU_LINK_HIT; break;
case 2: mSpellCustomAttr[trigger] |= SPELL_ATTR0_CU_LINK_AURA; break;
}
}
else
{
mSpellCustomAttr[-trigger] |= SPELL_ATTR0_CU_LINK_REMOVE;
}
if (type) //we will find a better way when more types are needed
{
if (trigger > 0)
trigger += SPELL_LINKED_MAX_SPELLS * type;
else
trigger -= SPELL_LINKED_MAX_SPELLS * type;
}
mSpellLinkedMap[trigger].push_back(effect);
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u linked spells in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
| gpl-2.0 |
wconsumer/wconsumer | tests/Unit/Service/LinkedinTest.php | 545 | <?php
namespace Drupal\wconsumer\Tests\Unit\Service;
use Drupal\wconsumer\Authentication\Oauth2\Oauth2;
use Drupal\wconsumer\Service\Linkedin;
class LinkedinTest extends AbstractServiceTest {
public function testAuthentication() {
$linkedin = $this->service();
$this->assertInstanceOf(Oauth2::getClass(), $linkedin->authentication);
}
public function testName() {
$linkedin = $this->service();
$this->assertSame('linkedin', $linkedin->getName());
}
protected function service() {
return new Linkedin();
}
} | gpl-2.0 |
vicarius123/100 | administrator/components/com_catering/controllers/reserves.php | 2335 | <?php
/**
* @version CVS: 1.0.0
* @package Com_Catering
* @author Cristopher Chong <[email protected]>
* @copyright 2017 nOne
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
jimport('joomla.application.component.controlleradmin');
use Joomla\Utilities\ArrayHelper;
/**
* Reserves list controller class.
*
* @since 1.6
*/
class CateringControllerReserves extends JControllerAdmin
{
/**
* Method to clone existing Reserves
*
* @return void
*/
public function duplicate()
{
// Check for request forgeries
Jsession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Get id(s)
$pks = $this->input->post->get('cid', array(), 'array');
try
{
if (empty($pks))
{
throw new Exception(JText::_('COM_CATERING_NO_ELEMENT_SELECTED'));
}
ArrayHelper::toInteger($pks);
$model = $this->getModel();
$model->duplicate($pks);
$this->setMessage(Jtext::_('COM_CATERING_ITEMS_SUCCESS_DUPLICATED'));
}
catch (Exception $e)
{
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'warning');
}
$this->setRedirect('index.php?option=com_catering&view=reserves');
}
/**
* Proxy for getModel.
*
* @param string $name Optional. Model name
* @param string $prefix Optional. Class prefix
* @param array $config Optional. Configuration array for model
*
* @return object The Model
*
* @since 1.6
*/
public function getModel($name = 'reserve', $prefix = 'CateringModel', $config = array())
{
$model = parent::getModel($name, $prefix, array('ignore_request' => true));
return $model;
}
/**
* Method to save the submitted ordering values for records via AJAX.
*
* @return void
*
* @since 3.0
*/
public function saveOrderAjax()
{
// Get the input
$input = JFactory::getApplication()->input;
$pks = $input->post->get('cid', array(), 'array');
$order = $input->post->get('order', array(), 'array');
// Sanitize the input
ArrayHelper::toInteger($pks);
ArrayHelper::toInteger($order);
// Get the model
$model = $this->getModel();
// Save the ordering
$return = $model->saveorder($pks, $order);
if ($return)
{
echo "1";
}
// Close the application
JFactory::getApplication()->close();
}
}
| gpl-2.0 |
admrbsn/Opolis-Theme | search.php | 1140 | <?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package Opolis
*/
get_header(); ?>
<section id="primary" class="content-area">
<main id="main" class="site-main">
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php
/* translators: %s: search query. */
printf( esc_html__( 'Search Results for: %s', 'opolis' ), '<span>' . get_search_query() . '</span>' );
?></h1>
</header><!-- .page-header -->
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
| gpl-2.0 |
abhinavjain241/acousticbrainz-server | db/stats.py | 10177 | """Module for working with statistics on data stored in AcousticBrainz.
Values are stored in `statistics` table and are referenced by <name, timestamp>
pair.
"""
import db
import db.cache
import db.exceptions
import datetime
import pytz
import calendar
import six
from sqlalchemy import text
STATS_CACHE_TIMEOUT = 60 * 10 # 10 minutes
LAST_MBIDS_CACHE_TIMEOUT = 60 # 1 minute (this query is cheap)
STATS_MEMCACHE_KEY = "recent-stats"
STATS_MEMCACHE_LAST_UPDATE_KEY = "recent-stats-last-updated"
STATS_MEMCACHE_NAMESPACE = "statistics"
LOWLEVEL_LOSSY = "lowlevel-lossy"
LOWLEVEL_LOSSY_UNIQUE = "lowlevel-lossy-unique"
LOWLEVEL_LOSSLESS = "lowlevel-lossless"
LOWLEVEL_LOSSLESS_UNIQUE = "lowlevel-lossless-unique"
LOWLEVEL_TOTAL = "lowlevel-total"
LOWLEVEL_TOTAL_UNIQUE = "lowlevel-total-unique"
stats_key_map = {
LOWLEVEL_LOSSY: "Lossy (all)",
LOWLEVEL_LOSSY_UNIQUE: "Lossy (unique)",
LOWLEVEL_LOSSLESS: "Lossless (all)",
LOWLEVEL_LOSSLESS_UNIQUE: "Lossless (unique)",
LOWLEVEL_TOTAL: "Total (all)",
LOWLEVEL_TOTAL_UNIQUE: "Total (unique)",
}
def get_last_submitted_recordings():
"""Get list of last submitted recordings.
Returns:
List of dictionaries with basic info about last submitted recordings:
mbid (MusicBrainz ID), artist (name), and title.
"""
cache_key = "last-submitted-recordings"
last_submissions = db.cache.get(cache_key)
if not last_submissions:
with db.engine.connect() as connection:
# We are getting results with of offset of 10 rows because we'd
# prefer to show recordings for which we already calculated
# high-level data. This might not be the best way to do that.
result = connection.execute("""SELECT ll.mbid,
llj.data->'metadata'->'tags'->'artist'->>0,
llj.data->'metadata'->'tags'->'title'->>0
FROM lowlevel ll
JOIN lowlevel_json llj
ON ll.id = llj.id
ORDER BY ll.id DESC
LIMIT 5
OFFSET 10""")
last_submissions = result.fetchall()
last_submissions = [
{
"mbid": r[0],
"artist": r[1],
"title": r[2],
} for r in last_submissions if r[1] and r[2]
]
db.cache.set(cache_key, last_submissions, time=LAST_MBIDS_CACHE_TIMEOUT)
return last_submissions
def compute_stats(to_date):
"""Compute hourly stats to a given date and write them to
the database.
Take the date of most recent statistics, or if no statistics
are added, the earliest date of a submission, and compute and write
for every hour from that date to `to_date` the number of items
in the database.
Args:
to_date: the date to compute statistics up to
"""
with db.engine.connect() as connection:
stats_date = _get_most_recent_stats_date(connection)
if not stats_date:
# If there have been no statistics, we start from the
# earliest date in the lowlevel table
stats_date = _get_earliest_submission_date(connection)
if not stats_date:
# If there are no lowlevel submissions, we stop
return
next_date = _get_next_hour(stats_date)
while next_date < to_date:
stats = _count_submissions_to_date(connection, next_date)
_write_stats(connection, next_date, stats)
next_date = _get_next_hour(next_date)
def _write_stats(connection, date, stats):
"""Records a value with a given name and current timestamp."""
for name, value in six.iteritems(stats):
q = text("""
INSERT INTO statistics (collected, name, value)
VALUES (:collected, :name, :value)""")
connection.execute(q, {"collected": date, "name": name, "value": value})
def add_stats_to_cache():
"""Compute the most recent statistics and add them to memcache"""
now = datetime.datetime.now(pytz.utc)
with db.engine.connect() as connection:
stats = _count_submissions_to_date(connection, now)
db.cache.set(STATS_MEMCACHE_KEY, stats,
time=STATS_CACHE_TIMEOUT, namespace=STATS_MEMCACHE_NAMESPACE)
db.cache.set(STATS_MEMCACHE_LAST_UPDATE_KEY, now,
time=STATS_CACHE_TIMEOUT, namespace=STATS_MEMCACHE_NAMESPACE)
def get_stats_summary():
"""Load a summary of statistics to show on the homepage.
If no statistics exist in the cache, use the most recently
computed statistics from the database
"""
last_collected, stats = _get_stats_from_cache()
if not stats:
recent_database = load_statistics_data(1)
if recent_database:
stats = recent_database[0]["stats"]
last_collected = recent_database[0]["collected"]
else:
stats = {k: 0 for k in stats_key_map.keys()}
return stats, last_collected
def _get_stats_from_cache():
"""Get submission statistics from memcache"""
stats = db.cache.get(STATS_MEMCACHE_KEY, namespace=STATS_MEMCACHE_NAMESPACE)
last_collected = db.cache.get(STATS_MEMCACHE_LAST_UPDATE_KEY,
namespace=STATS_MEMCACHE_NAMESPACE)
return last_collected, stats
def format_statistics_for_highcharts(data):
"""Format statistics data to load with highcharts
Args:
data: data from load_statistics_data
"""
counts = {}
for k in stats_key_map.keys():
counts[k] = []
for row in data:
collected = row["collected"]
stats = row["stats"]
ts = _make_timestamp(collected)
for k, v in counts.items():
counts[k].append([ts, stats[k]])
stats = [{"name": stats_key_map.get(key, key), "data": data} for key, data in counts.items()]
return stats
def load_statistics_data(limit=None):
# Postgres doesn't let you create a json dictionary using values
# from one column as keys and another column as values. Instead we
# create an array of {"name": name, "value": value} objects and change
# it in python
args = {}
# TODO: use sqlalchemy select().limit()?
qtext = """
SELECT collected
, json_agg(row_to_json(
(SELECT r FROM (SELECT name, value) r) )) AS stats
FROM statistics
GROUP BY collected
ORDER BY collected DESC
"""
if limit:
args["limit"] = int(limit)
qtext += " LIMIT :limit"
query = text(qtext)
with db.engine.connect() as connection:
stats_result = connection.execute(query, args)
ret = []
for line in stats_result:
row = {"collected": line["collected"], "stats": {}}
for stat in line["stats"]:
row["stats"][stat["name"]] = stat["value"]
ret.append(row)
# We order by DESC in order to use the `limit` parameter, but
# we actually need the stats in increasing order.
return list(reversed(ret))
def get_statistics_history():
return format_statistics_for_highcharts(load_statistics_data())
def _count_submissions_to_date(connection, to_date):
"""Count number of low-level submissions in the database
before a given date."""
counts = {
LOWLEVEL_LOSSY: 0,
LOWLEVEL_LOSSY_UNIQUE: 0,
LOWLEVEL_LOSSLESS: 0,
LOWLEVEL_LOSSLESS_UNIQUE: 0,
LOWLEVEL_TOTAL: 0,
LOWLEVEL_TOTAL_UNIQUE: 0,
}
# All submissions, split by lossless/lossy
query = text("""
SELECT lossless
, count(*)
FROM lowlevel
WHERE submitted < :submitted
GROUP BY lossless
""")
result = connection.execute(query, {"submitted": to_date})
for is_lossless, count in result.fetchall():
if is_lossless:
counts[LOWLEVEL_LOSSLESS] = count
else:
counts[LOWLEVEL_LOSSY] = count
# Unique submissions, split by lossless, lossy
query = text("""
SELECT lossless
, count(distinct(mbid))
FROM lowlevel
WHERE submitted < :submitted
GROUP BY lossless
""")
result = connection.execute(query, {"submitted": to_date})
for is_lossless, count in result.fetchall():
if is_lossless:
counts[LOWLEVEL_LOSSLESS_UNIQUE] = count
else:
counts[LOWLEVEL_LOSSY_UNIQUE] = count
# total number of unique submissions
query = text("""
SELECT count(distinct(mbid))
FROM lowlevel
WHERE submitted < :submitted
""")
result = connection.execute(query, {"submitted": to_date})
row = result.fetchone()
counts[LOWLEVEL_TOTAL_UNIQUE] = row[0]
# total of all submissions can be computed by summing lossless and lossy
counts[LOWLEVEL_TOTAL] = counts[LOWLEVEL_LOSSY] + counts[LOWLEVEL_LOSSLESS]
return counts
def _make_timestamp(dt):
""" Return the number of miliseconds since the epoch, in UTC """
dt = dt.replace(microsecond=0)
return calendar.timegm(dt.utctimetuple())*1000
def _get_earliest_submission_date(connection):
"""Get the earliest date that something was submitted to AB."""
q = text("""SELECT submitted
FROM lowlevel
ORDER BY submitted ASC
LIMIT 1""")
cur = connection.execute(q)
row = cur.fetchone()
if row:
return row[0]
def _get_most_recent_stats_date(connection):
q = text("""SELECT collected
FROM statistics
ORDER BY collected DESC
LIMIT 1""")
cur = connection.execute(q)
row = cur.fetchone()
if row:
return row[0]
def _get_next_hour(date):
"""Round up a date to the nearest hour:00:00.
Arguments:
date: a datetime
"""
delta = datetime.timedelta(hours=1)
date = date + delta
date = date.replace(minute=0, second=0, microsecond=0)
return date
| gpl-2.0 |
Ikerlb/calendario_proyecto3 | db/migrate/20151206230745_add_permission_level_to_users.rb | 144 | class AddPermissionLevelToUsers < ActiveRecord::Migration
def change
add_column :users, :permission_level, :integer, default: 1
end
end
| gpl-2.0 |
Nils-TUD/Escape | source/drivers/common/ext2/inode.cc | 8645 | /**
* $Id$
* Copyright (C) 2008 - 2014 Nils Asmussen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <fs/blockcache.h>
#include <fs/permissions.h>
#include <sys/common.h>
#include <sys/endian.h>
#include <sys/io.h>
#include <sys/proc.h>
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "bitmap.h"
#include "ext2.h"
#include "inode.h"
#include "inodecache.h"
#include "sbmng.h"
using namespace fs;
int Ext2INode::create(Ext2FileSystem *e,User *u,Ext2CInode *dirNode,Ext2CInode **ino,mode_t mode) {
size_t i;
time_t now;
Ext2CInode *cnode;
/* request inode */
ino_t inodeNo = Ext2Bitmap::allocInode(e,dirNode,S_ISDIR(mode));
if(inodeNo == 0)
return -ENOSPC;
cnode = e->inodeCache.request(inodeNo,IMODE_WRITE);
if(cnode == NULL) {
Ext2Bitmap::freeInode(e,inodeNo,S_ISDIR(mode));
return -ENOBUFS;
}
/* init inode */
cnode->inode.uid = cputole16(u->uid);
cnode->inode.gid = cputole16(u->gid);
cnode->inode.mode = cputole16(mode);
cnode->inode.linkCount = cputole16(0);
cnode->inode.size = cputole32(0);
cnode->inode.singlyIBlock = cputole32(0);
cnode->inode.doublyIBlock = cputole32(0);
cnode->inode.triplyIBlock = cputole32(0);
for(i = 0; i < EXT2_DIRBLOCK_COUNT; i++)
cnode->inode.dBlocks[i] = cputole32(0);
cnode->inode.blocks = cputole32(0);
now = cputole32(time(NULL));
cnode->inode.accesstime = now;
cnode->inode.createtime = now;
cnode->inode.modifytime = now;
cnode->inode.deletetime = cputole32(0);
e->inodeCache.markDirty(cnode);
*ino = cnode;
return 0;
}
int Ext2INode::chmod(Ext2FileSystem *e,User *u,ino_t inodeNo,mode_t mode) {
mode_t oldMode;
Ext2CInode *cnode = e->inodeCache.request(inodeNo,IMODE_WRITE);
if(cnode == NULL)
return -ENOBUFS;
if(!Permissions::canChmod(u,le16tocpu(cnode->inode.uid)))
return -EPERM;
if(S_ISLNK(le16tocpu(cnode->inode.mode)))
return -ENOTSUP;
oldMode = le16tocpu(cnode->inode.mode);
cnode->inode.mode = cputole16((oldMode & ~EXT2_S_PERMS) | (mode & EXT2_S_PERMS));
e->inodeCache.markDirty(cnode);
e->inodeCache.release(cnode);
return 0;
}
int Ext2INode::chown(Ext2FileSystem *e,User *u,ino_t inodeNo,uid_t uid,gid_t gid) {
uid_t oldUid;
gid_t oldGid;
Ext2CInode *cnode = e->inodeCache.request(inodeNo,IMODE_WRITE);
if(cnode == NULL)
return -ENOBUFS;
oldUid = le16tocpu(cnode->inode.uid);
oldGid = le16tocpu(cnode->inode.gid);
if(!Permissions::canChown(u,oldUid,oldGid,uid,gid))
return -EPERM;
if(S_ISLNK(le16tocpu(cnode->inode.mode)))
return -ENOTSUP;
if(uid != (uid_t)-1)
cnode->inode.uid = cputole16(uid);
if(gid != (gid_t)-1)
cnode->inode.gid = cputole16(gid);
e->inodeCache.markDirty(cnode);
e->inodeCache.release(cnode);
return 0;
}
int Ext2INode::utime(Ext2FileSystem *e,User *u,ino_t inodeNo,const struct utimbuf *utimes) {
Ext2CInode *cnode = e->inodeCache.request(inodeNo,IMODE_WRITE);
if(cnode == NULL)
return -ENOBUFS;
if(!Permissions::canUtime(u,le16tocpu(cnode->inode.uid)))
return -EPERM;
cnode->inode.accesstime = cputole32(utimes->actime);
cnode->inode.modifytime = cputole32(utimes->modtime);
e->inodeCache.markDirty(cnode);
e->inodeCache.release(cnode);
return 0;
}
int Ext2INode::destroy(Ext2FileSystem *e,Ext2CInode *cnode) {
int res;
/* free inode, clear it and ensure that it get's written back to disk */
if((res = Ext2Bitmap::freeInode(e,cnode->inodeNo,S_ISDIR(le16tocpu(cnode->inode.mode)))) < 0)
return res;
/* just set the delete-time and reset link-count. the block-numbers in the inode
* are still present, so that it may be possible to restore the file, if the blocks
* have not been overwritten in the meantime. */
cnode->inode.deletetime = cputole32(time(NULL));
cnode->inode.linkCount = cputole16(0);
e->inodeCache.markDirty(cnode);
return 0;
}
block_t Ext2INode::accessIndirBlock(Ext2FileSystem *e,Ext2CInode *cnode,block_t *indir,block_t i,
bool req,int level,block_t div) {
bool added = false;
uint bmode = req ? BlockCache::WRITE : BlockCache::READ;
size_t blockSize = e->blockSize();
size_t blocksPerBlock = blockSize / sizeof(block_t);
CBlock *cblock;
/* is the pointer to the block we want to write the block number into still missing? */
if(*indir == 0) {
if(!req)
return 0;
*indir = cputole32(Ext2Bitmap::allocBlock(e,cnode));
if(!*indir)
return 0;
added = true;
}
/* request the block with block numbers */
cblock = e->blockCache.request(le32tocpu(*indir),bmode);
if(cblock == NULL)
return 0;
/* clear it, if we just created it */
if(added)
memclear(cblock->buffer,blockSize);
block_t bno = 0;
block_t *blockNos = (block_t*)(cblock->buffer);
/* if we're the last level, write the block-number into it */
if(level == 0) {
assert(i < blocksPerBlock);
if(blockNos[i] == 0) {
if(!req)
goto error;
blockNos[i] = cputole32(Ext2Bitmap::allocBlock(e,cnode));
if(blockNos[i] == 0)
goto error;
cnode->inode.blocks = cputole32(le32tocpu(cnode->inode.blocks) + e->blocksToSecs(1));
e->blockCache.markDirty(cblock);
}
bno = le32tocpu(blockNos[i]);
}
/* otherwise let the callee write the block-number into cblock */
else {
block_t *subIndir = blockNos + i / div;
/* mark the block dirty, if the callee will write to it */
if(req && !*subIndir)
e->blockCache.markDirty(cblock);
bno = accessIndirBlock(e,cnode,subIndir,i % div,req,level - 1,div / blocksPerBlock);
}
error:
e->blockCache.release(cblock);
return bno;
}
block_t Ext2INode::doGetDataBlock(Ext2FileSystem *e,Ext2CInode *cnode,block_t block,bool req) {
size_t blockSize = e->blockSize();
size_t blocksPerBlock = blockSize / sizeof(block_t);
if(block < EXT2_DIRBLOCK_COUNT) {
block_t bno = le32tocpu(cnode->inode.dBlocks[block]);
if(req && bno == 0) {
bno = Ext2Bitmap::allocBlock(e,cnode);
cnode->inode.dBlocks[block] = cputole32(bno);
if(bno != 0) {
uint32_t blocks = le32tocpu(cnode->inode.blocks);
cnode->inode.blocks = cputole32(blocks + e->blocksToSecs(1));
}
}
return bno;
}
block -= EXT2_DIRBLOCK_COUNT;
if(block < blocksPerBlock)
return accessIndirBlock(e,cnode,&cnode->inode.singlyIBlock,block,req,0,1);
block -= blocksPerBlock;
if(block < blocksPerBlock * blocksPerBlock)
return accessIndirBlock(e,cnode,&cnode->inode.doublyIBlock,block,req,1,blocksPerBlock);
block -= blocksPerBlock * blocksPerBlock;
if(block < blocksPerBlock * blocksPerBlock * blocksPerBlock) {
return accessIndirBlock(e,cnode,&cnode->inode.triplyIBlock,block,req,2,
blocksPerBlock * blocksPerBlock);
}
/* too large */
return 0;
}
#if DEBUGGING
void Ext2INode::print(Ext2Inode *inode) {
size_t i;
printf("\tmode=0x%08x\n",le16tocpu(inode->mode));
printf("\tuid=%d\n",le16tocpu(inode->uid));
printf("\tgid=%d\n",le16tocpu(inode->gid));
printf("\tsize=%d\n",le32tocpu(inode->size));
printf("\taccesstime=%d\n",le32tocpu(inode->accesstime));
printf("\tcreatetime=%d\n",le32tocpu(inode->createtime));
printf("\tmodifytime=%d\n",le32tocpu(inode->modifytime));
printf("\tdeletetime=%d\n",le32tocpu(inode->deletetime));
printf("\tlinkCount=%d\n",le16tocpu(inode->linkCount));
printf("\tblocks=%d\n",le32tocpu(inode->blocks));
printf("\tflags=0x%08x\n",le32tocpu(inode->flags));
printf("\tosd1=0x%08x\n",le32tocpu(inode->osd1));
for(i = 0; i < EXT2_DIRBLOCK_COUNT; i++)
printf("\tblock%zu=%d\n",i,le32tocpu(inode->dBlocks[i]));
printf("\tsinglyIBlock=%d\n",le32tocpu(inode->singlyIBlock));
printf("\tdoublyIBlock=%d\n",le32tocpu(inode->doublyIBlock));
printf("\ttriplyIBlock=%d\n",le32tocpu(inode->triplyIBlock));
printf("\tgeneration=%d\n",le32tocpu(inode->generation));
printf("\tfileACL=%d\n",le32tocpu(inode->fileACL));
printf("\tdirACL=%d\n",le32tocpu(inode->dirACL));
printf("\tfragAddr=%d\n",le32tocpu(inode->fragAddr));
printf("\tosd2=0x%08x%08x%08x%08x\n",le16tocpu(inode->osd2[0]),le16tocpu(inode->osd2[1]),
le16tocpu(inode->osd2[2]),le16tocpu(inode->osd2[3]));
}
#endif
| gpl-2.0 |
dpinney/omf | omf/models/transmission.py | 8569 | ''' The transmission model pre-alpha release.
Requirements: GNU octave
Tested on Linux and macOS.
'''
import json, os, shutil, subprocess, math, platform, base64
from os.path import join as pJoin
import matplotlib
if platform.system() == 'Darwin':
matplotlib.use('TkAgg')
else:
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import matplotlib.cm as cm
from omf import network
from omf.models import __neoMetaModel__
from omf.models.__neoMetaModel__ import *
# Model metadata:
modelName, template = __neoMetaModel__.metadata(__file__)
tooltip = "The transmission model imports, runs and visualizes MATPOWER transmission and generation simulations."
hidden = False
def work(modelDir, inputDict):
''' Run the model in its directory.'''
outData = {
'tableData' : {'volts': [[],[]], 'powerReal' : [[],[]], 'powerReact' : [[],[]]},
# 'charts' : {'volts' : '', 'powerReact' : '', 'powerReal' : ''},
'voltsChart' : '', 'powerReactChart' : '', 'powerRealChart' : '',
'stdout' : '', 'stderr' : ''
}
# Read feeder and convert to .mat.
try:
networkName = [x for x in os.listdir(modelDir) if x.endswith('.omt')][0][0:-4]
except:
networkName = 'case9'
with open(pJoin(modelDir,networkName+".omt")) as f:
networkJson = json.load(f)
matName = 'matIn'
matFileName = matName + '.m'
matStr = network.netToMat(networkJson, matName)
with open(pJoin(modelDir, matFileName),"w") as outMat:
for row in matStr: outMat.write(row)
# Build the MATPOWER command.
matDir = pJoin(__neoMetaModel__._omfDir,'solvers','matpower7.0')
matPath = _getMatPath(matDir)
algorithm = inputDict.get("algorithm","NR")
pfArg = "'pf.alg', '" + algorithm + "'"
modelArg = "'model', '" + inputDict.get("model","AC") + "'"
iterCode = "pf." + algorithm[:2].lower() + ".max_it"
pfItArg = "'" + iterCode + "', " + str(inputDict.get("iteration",10))
pfTolArg = "'pf.tol', " + str(inputDict.get("tolerance",math.pow(10,-8)))
pfEnflArg = "'pf.enforce_q_lims', " + str(inputDict.get("genLimits",0))
if platform.system() == "Windows":
# Find the location of octave-cli tool.
envVars = os.environ["PATH"].split(';')
octavePath = "C:\\Octave\\Octave-4.2.0"
for pathVar in envVars:
if "octave" in pathVar.lower():
octavePath = pathVar
# Run Windows-specific Octave command.
mpoptArg = "mpoption(" + pfArg + ", " + modelArg + ", " + pfItArg + ", " + pfTolArg+", " + pfEnflArg + ") "
cmd = "runpf('"+pJoin(modelDir,matFileName)+"'," + mpoptArg +")"
args = [octavePath + '\\bin\\octave-cli','-p',matPath, "--eval", cmd]
myOut = subprocess.check_output(args, shell=True)
with open(pJoin(modelDir, "matout.txt"), "w") as matOut:
matOut.write(myOut)
else:
# Run UNIX Octave command.
mpoptArg = "mpopt = mpoption("+pfArg+", "+modelArg+", "+pfItArg+", "+pfTolArg+", "+pfEnflArg+"); "
command = "octave -p " + matPath + "--no-gui --eval \""+mpoptArg+"runpf('"+pJoin(modelDir,matFileName)+"', mpopt)\" > \"" + pJoin(modelDir,"matout.txt") + "\""
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
print(command)
(out, err) = proc.communicate()
imgSrc = pJoin(__neoMetaModel__._omfDir,'scratch','transmission','inData')
# Read matout.txt and parse into outData.
gennums=[]
todo = None
with open(pJoin(modelDir,"matout.txt")) as f:
for i,line in enumerate(f):
# Determine what type of data is coming up.
if "How many?" in line:
todo = "count"
elif "Generator Data" in line:
todo = "gen"
lineNo = i
elif "Bus Data" in line:
todo = "node"
lineNo = i
elif "Branch Data" in line:
todo = "line"
lineNo = i
# Parse lines.
line = line.split(' ')
line = [a for a in line if a != '']
if todo=="count":
if "Buses" in line:
busCount = int(line[1])
elif "Generators" in line:
genCount = int(line[1])
elif "Loads" in line:
loadCount = int(line[1])
elif "Branches" in line:
branchCount = int(line[1])
elif "Transformers" in line:
transfCount = int(line[1])
todo = None
elif todo=="gen":
if i>(lineNo+4) and i<(lineNo+4+genCount+1):
# gen bus numbers.
gennums.append(line[1])
elif i>(lineNo+4+genCount+1):
todo = None
elif todo=="node":
if i>(lineNo+4) and i<(lineNo+4+busCount+1):
# voltage
if line[0] in gennums: comp="gen"
else: comp="node"
outData['tableData']['volts'][0].append(comp+str(line[0]))
outData['tableData']['powerReal'][0].append(comp+str(line[0]))
outData['tableData']['powerReact'][0].append(comp+str(line[0]))
outData['tableData']['volts'][1].append(line[1])
outData['tableData']['powerReal'][1].append(line[3])
outData['tableData']['powerReact'][1].append(line[4])
elif i>(lineNo+4+busCount+1):
todo = None
elif todo=="line":
if i>(lineNo+4) and i<(lineNo+4+branchCount+1):
# power
outData['tableData']['powerReal'][0].append("line"+str(line[0]))
outData['tableData']['powerReact'][0].append("line"+str(line[0]))
outData['tableData']['powerReal'][1].append(line[3])
outData['tableData']['powerReact'][1].append(line[4])
elif i>(lineNo+4+branchCount+1):
todo = None
# Massage the data.
for powerOrVolt in outData['tableData'].keys():
for i in range(len(outData['tableData'][powerOrVolt][1])):
if outData['tableData'][powerOrVolt][1][i]!='-':
outData['tableData'][powerOrVolt][1][i]=float(outData['tableData'][powerOrVolt][1][i])
#Create chart
nodeVolts = outData["tableData"]["volts"][1]
minNum = min(nodeVolts)
maxNum = max(nodeVolts)
norm = matplotlib.colors.Normalize(vmin=minNum, vmax=maxNum, clip=True)
cmViridis = plt.get_cmap('viridis')
mapper = cm.ScalarMappable(norm=norm, cmap=cmViridis)
mapper._A = []
plt.figure(figsize=(10,10))
plt.colorbar(mapper)
plt.axis('off')
plt.tight_layout()
plt.gca().invert_yaxis() # HACK: to make latitudes show up right. TODO: y-flip the transEdit.html and remove this.
plt.gca().set_aspect('equal')
busLocations = {}
i = 0
for busName, busInfo in networkJson["bus"].items():
y = float(busInfo["latitude"])
x = float(busInfo["longitude"])
plt.plot([x], [y], marker='o', markersize=12.0, color=mapper.to_rgba(nodeVolts[i]), zorder=5)
busLocations[busName] = [x, y]
i = i + 1
for genName, genInfo in networkJson["gen"].items():
x,y = busLocations[genInfo["bus"]]
plt.plot([x], [y], 's', color='gray', zorder=10, markersize=6.0)
for branchName, branchInfo in networkJson["branch"].items():
x1, y1 = busLocations[branchInfo["fbus"]]
x2, y2 = busLocations[branchInfo["tbus"]]
plt.plot([x1, x2], [y1,y2], color='black', marker = '', zorder=0)
plt.savefig(modelDir + '/output.png')
with open(pJoin(modelDir,"output.png"),"rb") as inFile:
outData["chart"] = base64.standard_b64encode(inFile.read()).decode('ascii')
# Stdout/stderr.
outData["stdout"] = "Success"
outData["stderr"] = ""
return outData
def _getMatPath(matDir):
# Get paths required for matpower7.0 in octave
if platform.system() == "Windows":
pathSep = ";"
else:
pathSep = ":"
relativePaths = ['lib', 'lib/t', 'data', 'mips/lib', 'mips/lib/t', 'most/lib', 'most/lib/t', 'mptest/lib', 'mptest/lib/t', 'extras/maxloadlim', 'extras/maxloadlim/tests', 'extras/maxloadlim/examples', 'extras/misc', 'extras/reduction', 'extras/sdp_pf', 'extras/se', 'extras/smartmarket', 'extras/state_estimator', 'extras/syngrid/lib','extras/syngrid/lib/t']
paths = [matDir] + [pJoin(matDir, relativePath) for relativePath in relativePaths]
matPath = '"' + pathSep.join(paths) + '"'
return matPath
def new(modelDir):
''' Create a new instance of this model. Returns true on success, false on failure. '''
defaultInputs = {
"user": "admin",
"networkName1": "case9",
"algorithm": "NR",
"model": "AC",
"tolerance": "0.00000001",
"iteration": 10,
"genLimits": 0,
"modelType":modelName}
creationCode = __neoMetaModel__.new(modelDir, defaultInputs)
try:
shutil.copy(pJoin(__neoMetaModel__._omfDir,"static","SimpleNetwork.json"),pJoin(modelDir,"case9.omt"))
except:
return False
return creationCode
@neoMetaModel_test_setup
def _tests():
# Location
modelLoc = pJoin(__neoMetaModel__._omfDir,"data","Model","admin","Automated Testing of " + modelName)
# Blow away old test results if necessary.
try:
shutil.rmtree(modelLoc)
except:
# No previous test results.
pass
# Create New.
new(modelLoc)
# Pre-run.
# renderAndShow(modelLoc)
# Run the model.
__neoMetaModel__.runForeground(modelLoc)
# Show the output.
__neoMetaModel__.renderAndShow(modelLoc)
if __name__ == '__main__':
_tests()
| gpl-2.0 |
toandevitviet/vpan | administrator/components/com_djcatalog2/models/field.php | 6235 | <?php
/**
* @version $Id: field.php 191 2013-11-03 07:15:27Z michal $
* @package DJ-Catalog2
* @copyright Copyright (C) 2012 DJ-Extensions.com LTD, All rights reserved.
* @license http://www.gnu.org/licenses GNU/GPL
* @author url: http://dj-extensions.com
* @author email [email protected]
* @developer Michal Olczyk - [email protected]
*
* DJ-Catalog2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DJ-Catalog2 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 DJ-Catalog2. If not, see <http://www.gnu.org/licenses/>.
*
*/
// No direct access.
defined('_JEXEC') or die;
//jimport('joomla.application.component.modeladmin');
require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'lib'.DS.'modeladmin.php');
class Djcatalog2ModelField extends DJCJModelAdmin
{
protected $text_prefix = 'COM_DJCATALOG2';
public function __construct($config = array()) {
//$config['event_after_save'] = 'onFieldAfterSave';
//$config['event_after_delete'] = 'onFieldAfterDelete';
parent::__construct($config);
}
public function getTable($type = 'Fields', $prefix = 'Djcatalog2Table', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
// Initialise variables.
$app = JFactory::getApplication();
// Get the form.
$form = $this->loadForm('com_djcatalog2.field', 'field', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_djcatalog2.edit.field.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
protected function _prepareTable(&$table)
{
jimport('joomla.filter.output');
$date = JFactory::getDate();
$user = JFactory::getUser();
$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);
if (empty($table->alias)) {
$table->alias = JApplication::stringURLSafe($table->name);
$table->alias = trim(str_replace('-','_',$table->alias));
if(trim(str_replace('_','',$table->alias)) == '') {
$table->alias = JFactory::getDate()->format('Y_m_d_H_i_s');
}
}
if (empty($table->id)) {
if (empty($table->ordering)) {
$db = JFactory::getDbo();
$db->setQuery('SELECT MAX(ordering) FROM #__djc2_items_extra_fields');
$max = $db->loadResult();
$table->ordering = $max+1;
}
}
}
protected function getReorderConditions($table)
{
$condition = array();
$condition[] = 'group_id = '.(int) $table->group_id;
return $condition;
}
public function delete(&$cid) {
if (count( $cid ))
{
$cids = implode(',', $cid);
try {
$db = JFactory::getDbo();
$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_text WHERE field_id IN ('.$cids.') ');
$db->query();
}
catch (Exception $e) {
$this->setError($e->getMessage());
return false;
}
try {
$db = JFactory::getDbo();
$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_int WHERE field_id IN ('.$cids.') ');
$db->query();
}
catch (Exception $e) {
$this->setError($e->getMessage());
return false;
}
try {
$db = JFactory::getDbo();
$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_date WHERE field_id IN ('.$cids.') ');
$db->query();
}
catch (Exception $e) {
$this->setError($e->getMessage());
return false;
}
}
return parent::delete($cid);
}
public function saveOptions($values, &$table) {
$db = JFactory::getDbo();
if (!empty($values) && array_key_exists('id', $values) && array_key_exists('option', $values) && array_key_exists('position', $values)) {
if ($table->type == 'select' || $table->type == 'checkbox' || $table->type == 'radio') {
//$db->setQuery('SELECT MAX(ordering) FROM #__djc2_items_extra_fields_options WHERE field_id='.(int)$table->id);
//$max = $db->loadResult();
$pks = array();
$max = 1;
foreach ($values['id'] as $key=>$id) {
if ($values['option'][$key]) {
$fo_table = JTable::getInstance('FieldOptions', 'Djcatalog2Table', array());
$isNew = true;
// Load the row if saving an existing record.
if ($id > 0) {
$fo_table->load($id);
$isNew = false;
}
$data = array();
$data['id'] = $isNew ? null:$id;
//$data['value'] = htmlspecialchars($values['option'][$key]);
$data['value'] = ($values['option'][$key]);
$data['ordering'] = ($values['position'][$key] > 0) ? $values['position'][$key] : 0;
$data['field_id'] = $table->id;
// Bind the data.
if (!$fo_table->bind($data)) {
$this->setError($fo_table->getError());
return false;
}
if (empty($fo_table->ordering) || !$fo_table->ordering) {
$fo_table->ordering = $max;
}
$max = $fo_table->ordering + 1;
// Check the data.
if (!$fo_table->check()) {
$this->setError($fo_table->getError());
return false;
}
// Store the data.
if (!$fo_table->store()) {
$this->setError($fo_table->getError());
return false;
}
$pks[] = $fo_table->id;
}
}
if (!empty($pks)) {
$db->setQuery('DELETE FROM #__djc2_items_extra_fields_options WHERE field_id='.(int)$table->id.' AND id NOT IN ('.implode(',',$pks).')');
$db->query();
}
}
}
return true;
}
public function deleteOptions(&$table) {
$db = JFactory::getDbo();
$db->setQuery('DELETE FROM #__djc2_items_extra_fields_options WHERE field_id='.(int)$table->id);
if (!$db->query()){
$this->setError($db->getError());
}
return true;
}
} | gpl-2.0 |
ericbarns/WP-e-Commerce | wpsc-components/theme-engine-v2/mvc/controllers/register.php | 3588 | <?php
class WPSC_Controller_Register extends WPSC_Controller
{
public function __construct() {
if ( is_user_logged_in() ) {
wp_redirect( wpsc_get_store_url() );
exit;
}
parent::__construct();
$this->title = wpsc_get_register_title();
}
public function index() {
if ( isset( $_POST['action'] ) && $_POST['action'] == 'register' ) {
$this->callback_register();
}
$this->view = 'register';
}
public function filter_fields_dont_match_message() {
return __( 'The password fields do not match.', 'wpsc' );
}
private function callback_register() {
$form_args = wpsc_get_register_form_args();
$validation = wpsc_validate_form( $form_args );
if ( is_wp_error( $validation ) ) {
wpsc_set_validation_errors( $validation );
return;
}
extract( $_POST, EXTR_SKIP );
$errors = new WP_Error();
do_action( 'register_post', $username, $email, $errors );
$errors = apply_filters( 'registration_errors', $errors, $username, $email );
if ( $errors->get_error_code() ) {
wpsc_set_validation_error( $errors );
return;
}
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $username, $password, $email );
if ( is_wp_error( $user_id ) ) {
foreach ( $user_id->get_error_messages() as $message ) {
$this->message_collection->add( $message, 'error' );
}
return;
}
if ( ! $user_id ) {
$message = apply_filters( 'wpsc_register_unknown_error_message', __( 'Sorry, but we could not process your registration information. Please <a href="mailto:%s">contact us</a>, or try again later.', 'wpsc' ) );
$this->message_collection->add( sprintf( $message, get_option( 'admin_email' ), 'error' ) );
return;
}
update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
$this->send_registration_notification( $user_id, $username, $email, $password );
$this->message_collection->add( __( 'We just sent you an e-mail containing your generated password. Just follow the directions in that e-mail to complete your registration.', 'wpsc' ), 'success', 'main', 'flash' );
wp_redirect( wpsc_get_login_url() );
exit;
}
private function send_registration_notification( $user_id, $username, $email, $password ) {
wp_new_user_notification( $user_id );
$username = stripslashes( $username );
$password = stripslashes( $password );
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$title = apply_filters( 'wpsc_registration_notification_title', __( '[%s] Thank you for registering', 'wpsc' ) );
$title = sprintf( $title, $blogname );
$message = sprintf( __( 'Welcome, %s.', 'wpsc' ), $username ) . "\r\n\r\n";
$message .= __( "Thank you for registering with us. Your account has been created:", 'wpsc' ) . "\r\n\r\n";
$message .= sprintf( __( 'Username: %s', 'wpsc' ), $username ) . "\r\n\r\n";
$message .= sprintf( __( 'Password: %s', 'wpsc' ), $password ) . "\r\n\r\n";
$message .= __( "Here's a list of things you can do to get started:", 'wpsc' ) . "\r\n\r\n";
$message .= sprintf( __( '1. Log in with your new account details <%s>', 'wpsc' ), wpsc_get_login_url() ) . "\r\n\r\n";
$message .= sprintf( __( '2. Build your customer profile, and probably change your password to something easier to remember <%s>', 'wpsc' ), wpsc_get_customer_account_url() ) . "\r\n\r\n";
$message .= sprintf( __( '3. Explore our shop! <%s>', 'wpsc' ), wpsc_get_store_url() ) . "\r\n\r\n";
$message = apply_filters( 'wpsc_registration_notification_body', $message );
wp_mail( $email, $title, $message );
}
} | gpl-2.0 |
TheTypoMaster/Scaper | openjdk/corba/src/share/classes/com/sun/corba/se/impl/protocol/giopmsgheaders/TargetAddressHelper.java | 6596 | /*
* Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.corba.se.impl.protocol.giopmsgheaders;
/**
* com/sun/corba/se/impl/protocol/giopmsgheaders/TargetAddressHelper.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from ../../../../../../../src/share/classes/com/sun/corba/se/GiopIDL/g.idl
* Sunday, June 4, 2000 5:18:54 PM PDT
*/
abstract public class TargetAddressHelper
{
private static String _id = "IDL:messages/TargetAddress:1.0";
public static void insert (org.omg.CORBA.Any a, com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
org.omg.CORBA.TypeCode _disTypeCode0;
_disTypeCode0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short);
_disTypeCode0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.corba.se.impl.protocol.giopmsgheaders.AddressingDispositionHelper.id (), "AddressingDisposition", _disTypeCode0);
org.omg.CORBA.UnionMember[] _members0 = new org.omg.CORBA.UnionMember [3];
org.omg.CORBA.TypeCode _tcOf_members0;
org.omg.CORBA.Any _anyOf_members0;
// Branch for object_key
_anyOf_members0 = org.omg.CORBA.ORB.init ().create_any ();
_anyOf_members0.insert_short ((short)com.sun.corba.se.impl.protocol.giopmsgheaders.KeyAddr.value);
_tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_octet);
_tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0);
_members0[0] = new org.omg.CORBA.UnionMember (
"object_key",
_anyOf_members0,
_tcOf_members0,
null);
// Branch for profile
_anyOf_members0 = org.omg.CORBA.ORB.init ().create_any ();
_anyOf_members0.insert_short ((short)com.sun.corba.se.impl.protocol.giopmsgheaders.ProfileAddr.value);
_tcOf_members0 = org.omg.IOP.TaggedProfileHelper.type ();
_members0[1] = new org.omg.CORBA.UnionMember (
"profile",
_anyOf_members0,
_tcOf_members0,
null);
// Branch for ior
_anyOf_members0 = org.omg.CORBA.ORB.init ().create_any ();
_anyOf_members0.insert_short ((short)com.sun.corba.se.impl.protocol.giopmsgheaders.ReferenceAddr.value);
_tcOf_members0 = com.sun.corba.se.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.type ();
_members0[2] = new org.omg.CORBA.UnionMember (
"ior",
_anyOf_members0,
_tcOf_members0,
null);
__typeCode = org.omg.CORBA.ORB.init ().create_union_tc (com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddressHelper.id (), "TargetAddress", _disTypeCode0, _members0);
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress read (org.omg.CORBA.portable.InputStream istream)
{
com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress value = new com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress ();
short _dis0 = (short)0;
_dis0 = istream.read_short ();
switch (_dis0)
{
case com.sun.corba.se.impl.protocol.giopmsgheaders.KeyAddr.value:
byte _object_key[] = null;
int _len1 = istream.read_long ();
_object_key = new byte[_len1];
istream.read_octet_array (_object_key, 0, _len1);
value.object_key (_object_key);
break;
case com.sun.corba.se.impl.protocol.giopmsgheaders.ProfileAddr.value:
org.omg.IOP.TaggedProfile _profile = null;
_profile = org.omg.IOP.TaggedProfileHelper.read (istream);
value.profile (_profile);
break;
case com.sun.corba.se.impl.protocol.giopmsgheaders.ReferenceAddr.value:
com.sun.corba.se.impl.protocol.giopmsgheaders.IORAddressingInfo _ior = null;
_ior = com.sun.corba.se.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.read (istream);
value.ior (_ior);
break;
default:
throw new org.omg.CORBA.BAD_OPERATION ();
}
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.corba.se.impl.protocol.giopmsgheaders.TargetAddress value)
{
ostream.write_short (value.discriminator ());
switch (value.discriminator ())
{
case com.sun.corba.se.impl.protocol.giopmsgheaders.KeyAddr.value:
ostream.write_long (value.object_key ().length);
ostream.write_octet_array (value.object_key (), 0, value.object_key ().length);
break;
case com.sun.corba.se.impl.protocol.giopmsgheaders.ProfileAddr.value:
org.omg.IOP.TaggedProfileHelper.write (ostream, value.profile ());
break;
case com.sun.corba.se.impl.protocol.giopmsgheaders.ReferenceAddr.value:
com.sun.corba.se.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.write (ostream, value.ior ());
break;
default:
throw new org.omg.CORBA.BAD_OPERATION ();
}
}
}
| gpl-2.0 |
HyperloopTeam/FullOpenMDAO | cantera-2.0.2/test_problems/surfkin/surfdemo.cpp | 1149 | /*
* Sample program that solves an implicit problem for surface
* site fractions.
*/
#include <iostream>
#include "cantera/IdealGasMix.h"
#include "cantera/Interface.h"
using namespace Cantera;
using namespace std;
int main()
{
try {
IdealGasMix gas("gri30.xml", "gri30");
gas.setState_TPX(1200.0, OneAtm,
"H2:2, O2:1, OH:0.01, H:0.01, O:0.01");
vector<ThermoPhase*> phases;
phases.push_back(&gas);
Interface surf("surface.xml", "surface", phases);
vector_fp cov;
cov.push_back(0.8);
cov.push_back(0.2);
surf.setCoverages(DATA_PTR(cov));
vector_fp wdot(gas.nSpecies() + surf.nSpecies());
surf.getNetProductionRates(DATA_PTR(wdot));
for (size_t k = 0; k < gas.nSpecies(); k++) {
cout << gas.speciesName(k) << " " << wdot[k] << endl;
}
for (size_t k = 0; k < surf.nSpecies(); k++)
cout << surf.speciesName(k) << " "
<< wdot[k+gas.nSpecies()] << endl;
} catch (CanteraError& err) {
std::cout << err.what() << std::endl;
}
return 0;
}
| gpl-2.0 |
lasyan3/TrinityCore | src/server/scripts/EasternKingdoms/ZulGurub/boss_hazzarah.cpp | 4175 | /*
* Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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/>.
*/
/* ScriptData
SDName: Boss_Hazzarah
SD%Complete: 100
SDComment:
SDCategory: Zul'Gurub
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "TemporarySummon.h"
#include "zulgurub.h"
enum Spells
{
SPELL_MANABURN = 26046,
SPELL_SLEEP = 24664
};
enum Events
{
EVENT_MANABURN = 1,
EVENT_SLEEP = 2,
EVENT_ILLUSIONS = 3
};
class boss_hazzarah : public CreatureScript
{
public:
boss_hazzarah() : CreatureScript("boss_hazzarah") { }
struct boss_hazzarahAI : public BossAI
{
boss_hazzarahAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS) { }
void Reset() override
{
_Reset();
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
}
void JustEngagedWith(Unit* /*who*/) override
{
_JustEngagedWith();
events.ScheduleEvent(EVENT_MANABURN, 4s, 10s);
events.ScheduleEvent(EVENT_SLEEP, 10s, 18s);
events.ScheduleEvent(EVENT_ILLUSIONS, 10s, 18s);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MANABURN:
DoCastVictim(SPELL_MANABURN, true);
events.ScheduleEvent(EVENT_MANABURN, 8s, 16s);
break;
case EVENT_SLEEP:
DoCastVictim(SPELL_SLEEP, true);
events.ScheduleEvent(EVENT_SLEEP, 12s, 20s);
break;
case EVENT_ILLUSIONS:
// We will summon 3 illusions that will spawn on a random gamer and attack this gamer
// We will just use one model for the beginning
for (uint8 i = 0; i < 3; ++i)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
if (Creature* Illusion = me->SummonCreature(NPC_NIGHTMARE_ILLUSION, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 30000))
Illusion->AI()->AttackStart(target);
}
events.ScheduleEvent(EVENT_ILLUSIONS, 15s, 25s);
break;
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<boss_hazzarahAI>(creature);
}
};
void AddSC_boss_hazzarah()
{
new boss_hazzarah();
}
| gpl-2.0 |
GudkovS/joomla2.5.14 | administrator/components/com_unitehcarousel/views/items/tmpl/default.php | 570 | <?php
/**
* @package Unite Horizontal Carousel for Joomla 1.7-2.5
* @author UniteCMS.net
* @copyright (C) 2012 Unite CMS, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
defined('_JEXEC') or die('Restricted access'); ?>
<?php
$numSliders = count($this->arrSliders);
if($numSliders == 0){ //error output
?>
<h2>Please add some slider before operating slides</h2>
<?php
}else
echo $this->loadTemplate("slide");
HelperUniteHCar::includeView("sliders/tmpl/footer.php");
?>
| gpl-2.0 |
ramonrdm/agendador | agenda/forms.py | 44691 | # -*- coding: utf-8 -*-
from agenda.models import *
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.forms import UserChangeForm
from django.core.exceptions import PermissionDenied
from django import forms
from django.contrib.admin import widgets
import datetime
from datetime import timedelta
from django.core.mail import send_mail
from django.forms import ModelForm, Form, HiddenInput, models, fields
from django.contrib.admin.sites import AdminSite
from django.core.exceptions import ValidationError
from django.contrib.admin import widgets
from django.forms.widgets import Select
from django.template.loader import render_to_string
from widgets import *
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.forms import UserCreationForm
from django.db.models.fields.related import ManyToOneRel
import admin
translated_week_names = dict(Sunday='domingo', Monday='segunda-feira', Tuesday='terça-feira', Wednesday='quarta-feira', Thursday='quinta-feira', Friday='sexta-feira', Saturday='sábado')
shortened_week_names = ('seg', 'ter', 'qua', 'qui', 'sex', 'sab', 'dom')
class AtividadeAdminForm(forms.ModelForm):
class Meta:
model = Atividade
fields = "__all__"
def __init__(self, *args, **kwargs):
super(AtividadeAdminForm, self).__init__(*args, **kwargs)
def clean(self):
all_actvs = Atividade.objects.all()
cleaned_data = super(AtividadeAdminForm, self).clean()
for actv in all_actvs:
if actv.nome.lower() == cleaned_data['nome'].lower() and self.instance.pk != actv.id:
raise ValidationError(("Já existe atividade com esse nome"), code="existing_activity")
def save(self, *args, **kwargs):
return super(AtividadeAdminForm, self).save(*args, **kwargs)
class ReservaAdminForm(forms.ModelForm):
recorrente = forms.BooleanField(required=False)
dataInicio = forms.DateField(required=False)
dataFim = forms.DateField(required=False)
seg = forms.BooleanField(required=False)
ter = forms.BooleanField(required=False)
qua = forms.BooleanField(required=False)
qui = forms.BooleanField(required=False)
sex = forms.BooleanField(required=False)
sab = forms.BooleanField(required=False)
dom = forms.BooleanField(required=False)
class Meta:
model = Reserva
fields = '__all__'
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
self.admin_type = kwargs.pop('admin_type', None)
self.reservable_type = kwargs.pop('reservable_type', None)
self.reserve_type = kwargs.pop('reserve_type', None)
super(ReservaAdminForm, self).__init__(*args, **kwargs)
self.is_new_object = True # start assuming the form is to create a new object in the db
# If the user is trying to edit a reserve for a reservable not being responsable for it, he can only read
# If the user is creating a new reserve or trying to edit a form he has permission, he can change the fields accordingly
readOnly = False
if 'instance' in kwargs:
if kwargs['instance']:
self.is_new_object = False # the form is to edit an existing object
self.instance = kwargs['instance']
reservable = kwargs['instance'].locavel
if self.request.user not in reservable.responsavel.all():
readOnly = True
try:
starting_reservable = self.request.session['id_reservable']
except:
starting_reservable = None
if starting_reservable:
self.check_group_only()
if readOnly and not self.request.user.is_superuser:
self.init_common_user_editting(kwargs)
else:
self.init_status_field(kwargs)
self.init_date_field()
self.init_hour_fields()
self.init_reservable_field(kwargs)
self.init_activity_field()
self.init_user_field()
self.init_recurrent_field(kwargs)
def init_common_user_editting(self, kwargs):
self.init_user_editting_status()
self.init_read_only(kwargs)
def init_user_editting_status(self):
initial = None
for choice in self.fields['estado'].choices:
if choice[0] == self.instance.estado and choice[0] != 'C':
initial = choice
if initial:
self.fields['estado'].choices = (initial, ('C', 'Cancelado'))
else:
self.fields['estado'].choices = (('C', 'Cancelado'),)
def check_group_only(self):
reservable = self.reservable_type.objects.get(id=self.request.session['id_reservable'])
if reservable.somenteGrupo:
groups = reservable.grupos.all()
has_permission = False
for group in groups:
if self.request.user in group.user_set.all():
has_permission = True
if not has_permission and not self.request.user.is_superuser and not (self.request.user in reservable.responsavel.all()):
self.request.session['id_reservable'] = None
groups = ", ".join(group.name for group in groups)
raise PermissionDenied('Apenas usuarios no(s) grupo(s) '+groups+' podem pedir reserva em ' + reservable.nome +'.')
def init_recurrent_field(self, kwargs):
self.fields['recorrente'].widget = RecurrentReserveWidget()
if self.is_new_object:
self.fields['dataInicio'].widget = forms.HiddenInput()
self.fields['dataInicio'].label = ''
self.fields['dataFim'].label = 'Data Fim'
elif kwargs['instance'].recorrencia:
instance = kwargs['instance']
self.fields['dataInicio'].initial = instance.recorrencia.dataInicio
self.fields['dataInicio'].widget = ReadOnlyWidget(attrs=dict(label='Data início'))
self.fields['dataInicio'].disabled = True
self.fields['dataFim'].widget = ReadOnlyWidget(attrs=dict(label='Data fim'))
self.fields['dataFim'].disabled = True
self.fields['dataFim'].initial = instance.recorrencia.dataFim
self.fields['recorrente'].initial = True
# here we check the value of the week day field
week_days = instance.recorrencia.get_days()
for number, day in enumerate(shortened_week_names):
if number in week_days:
self.fields[day].widget = ReadOnlyWidget(check_box=True, check_box_value=True)
self.fields[day].initial = True
else:
self.fields[day].widget = ReadOnlyWidget(check_box=True, check_box_value=False)
self.fields[day].initial = False
self.fields[day].disabled = True
def init_read_only(self, kwargs):
# For all fields, put the readonly widget and makes sure the data can't be tempered
self.fields['data'].widget = ReadOnlyWidget()
self.fields['data'].disabled = True
self.fields['horaInicio'].widget = ReadOnlyWidget(attrs=dict(label='Hora início'))
self.fields['horaInicio'].disabled = True
self.fields['horaFim'].widget = ReadOnlyWidget(attrs=dict(label='Hora fim'))
self.fields['horaFim'].disabled = True
self.fields['locavel'].widget = ReadOnlyWidget(attrs=dict(label='Locável'), search_model=type(kwargs['instance'].locavel))
self.fields['locavel'].disabled = True
self.fields['atividade'].widget = ReadOnlyWidget(type(kwargs['instance'].atividade))
self.fields['ramal'].widget = ReadOnlyWidget()
self.fields['ramal'].disabled = True
self.fields['finalidade'].widget = ReadOnlyWidget()
self.fields['finalidade'].disabled = True
# recurrent is not read only so users can cancel all reserves in one go
self.fields['recorrente'].initial = self.instance.recorrencia
self.fields['recorrente'].widget = RecurrentReserveWidget()
if kwargs['instance'].recorrencia:
self.fields['dataInicio'].initial = kwargs['instance'].recorrencia.dataInicio
self.fields['dataInicio'].widget = ReadOnlyWidget()
self.fields['dataInicio'].label = 'Data início'
self.fields['dataInicio'].disabled = True
self.fields['dataFim'].initial = kwargs['instance'].recorrencia.dataFim
self.fields['dataFim'].widget = ReadOnlyWidget()
self.fields['dataFim'].disabled= True
# init week days
week_days = self.instance.recorrencia.get_days()
for number, day in enumerate(shortened_week_names):
if number in week_days:
self.fields[day].widget = ReadOnlyWidget(check_box=True, check_box_value=True)
self.fields[day].initial = True
else:
self.fields[day].widget = ReadOnlyWidget(check_box=True, check_box_value=False)
self.fields[day].initial = False
self.fields[day].disabled = True
else:
self.fields['dataInicio'].widget = forms.HiddenInput()
self.fields['dataInicio'].label = ''
self.fields['dataFim'].widget = forms.HiddenInput()
self.fields['dataFim'].label = ''
# The hidden fields are hidded
self.fields['usuario'].widget = forms.HiddenInput()
self.fields['usuario'].label = ''
def init_status_field(self, kwargs):
# If we're creating a new form it's okay to hide the status.
# If we're additing an existing one, it must show status if user is reponsable
hide = False
if 'instance' in kwargs:
if kwargs['instance']:
reservable = kwargs['instance'].locavel
# Check what's the model and reservables the user own
if isinstance(reservable, EspacoFisico):
reservable_set = self.request.user.espacofisico_set.all()
elif isinstance(reservable, Equipamento):
reservable_set = self.request.user.equipamento_set.all()
elif isinstance(reservable, Servico):
reservable_set = self.request.user.servico_set.all()
if reservable not in reservable_set:
hide = True
else:
hide = True
else:
hide = True
if hide and not self.request.user.is_superuser:
self.fields['estado'].initial = 'E'
self.fields['estado'].label = ''
self.fields['estado'].widget = forms.HiddenInput()
def init_user_field(self):
# Hide if it's not superuser, otherwise check for errors and initialize
if not self.request.user.is_superuser:
self.fields['usuario'].initial = self.request.user
self.fields['usuario'].widget = forms.HiddenInput()
self.fields['usuario'].label = ''
else:
attrs = dict(label="Usuário")
if 'usuario' in self.errors:
attrs['error'] = self.errors['usuario']
self.fields['usuario'].widget = AutocompleteWidget(attrs=attrs, query=User.objects.all(), model=User)
def init_activity_field(self):
# If there's a initial reservable get activities that belong to it
if self.fields['locavel'].initial:
reservable = self.reservable_type.objects.get(id=self.fields['locavel'].initial)
self.fields['atividade'].queryset = reservable.atividadesPermitidas
# Initialize the widget that dynamically change activities according to the selected reservable
rel = Reserva._meta.get_field('atividade').rel
self.fields['atividade'].widget = DynamicAtividadeWidget(Select(choices=models.ModelChoiceIterator(self.fields['atividade'])), rel, admin.admin.site)
self.fields['atividade'].widget.can_add_related = False # remove add button
self.fields['atividade'].widget.can_change_related = False # remove edit button
def init_reservable_field(self, kwargs):
# If there was a error of validation there's the need to recover the reservable as pre-selected
if self.errors:
try:
self.request.session['id_reservable'] = self.request.session['id_reservable_backup']
except:
pass
# Check if there is a pre-selected reservable
try:
self.id_reservable = self.request.session['id_reservable']
except:
self.id_reservable = None
# If user is changing an existing reserve the reserve's reservable already selected is the only option
# If user is creating a reserve, the queryset of possible reservables is determinet
if 'instance' in kwargs:
if kwargs['instance']:
reservable = kwargs['instance'].locavel
queryset = self.reservable_type.objects.filter(id=reservable.id)
else:
ma = self.admin_type(self.reservable_type, AdminSite())
queryset = ma.get_queryset(self.request)
else:
ma = self.admin_type(self.reservable_type, AdminSite())
queryset = ma.get_queryset(self.request)
# If there's a pre=selected reservable he is the option
# Else the options are the user's queryset
if self.id_reservable:
self.fields['locavel'].initial = self.id_reservable
self.fields['locavel'].queryset = self.reservable_type.objects.filter(id=self.id_reservable)
else:
self.fields['locavel'].queryset = queryset
# id_reservable is saved so it can be recovered in case of validation error
self.request.session['id_reservable_backup'] = self.id_reservable
self.request.session['id_reservable'] = None
#setlabel
self.fields['locavel'].label = "Locável"
self.fields['locavel'].widget.can_add_related = False # remove add button
self.fields['locavel'].widget.can_change_related = False # remove edit button
def init_hour_fields(self):
# Check fields for error and intialize Widgets
attrs = dict(label="Hora Inicio")
if 'horaInicio' in self.errors:
attrs['error'] = self.errors['horaInicio']
self.fields['horaInicio'] = forms.TimeField(input_formats=['%H:%M'], widget=SelectTimeWidget(attrs=attrs))
attrs = dict(label="Hora Fim")
if 'horaFim' in self.errors:
attrs['error'] = self.errors['horaFim']
self.fields['horaFim'] = forms.TimeField(input_formats=['%H:%M'], widget=SelectTimeWidget(attrs=attrs))
# See if there's a initial value
try:
self.fields['horaInicio'].initial = self.request.session['horaInicio']
self.fields['horaFim'].initial = self.request.session['horaFim']
except:
pass
self.request.session['horaInicio'] = ''
self.request.session['horaFim'] = ''
def init_date_field(self):
# See if there's a initial value
try:
self.fields['data'].initial = self.request.session['data']
except:
pass
self.request.session['data'] = ''
def send_mail(self, status, instance):
user = instance.usuario
status = instance.estado
reservable = instance.locavel
date = instance.data
start = instance.horaInicio
end = instance.horaFim
responsables = reservable.responsavel.all()
# add e-mail text that alerts a recurrent reserve
if self.cleaned_data['recorrente']:
day_name = instance.recorrencia.dataInicio.strftime("%A")
translated_day_name = translated_week_names[day_name]
if translated_day_name == 'sabado' or translated_day_name == 'domingo':
conector = 'todo'
else:
conector = 'toda'
ending_date = instance.recorrencia.dataFim
date = instance.recorrencia.dataInicio
recurrent_text= ' ao dia %s, %s %s' % (ending_date.strftime('%d/%m/%Y'), conector, translated_day_name)
else:
recurrent_text = ''
user_dict = dict(user=user, reservable=reservable.nome.encode("utf-8"), date=date.strftime("%d/%m/%Y"), recurrent=recurrent_text, beginTime=start.strftime('%H:%M'), endTime=end.strftime("%H:%M"))
# First we send an email to the user who asked for the reserve
if status == 'A':
email_title = 'Reserva de %s confirmada.' % reservable.nome.encode("utf-8")
user_dict['suffix'] = "foi confirmada."
elif status == 'E':
email_title = 'Reserva de %s aguardando aprovação.' % reservable.nome.encode("utf-8")
user_dict['suffix'] = " está aguardando aprovação. Você receberá uma notificação quando o estado da sua reserva for atualizado."
# Need to check reservable instance to genereate the link
if isinstance(reservable, EspacoFisico):
reserve_type = 'reservaespacofisico'
elif isinstance(reservable, Equipamento):
reserve_type = 'reservaequipamento'
elif isinstance(reservable, Servico):
reserve_type = 'reservaservico'
base_url = self.request.build_absolute_uri('/')
url = "%sadmin/agenda/%s/%d/change/" % (base_url, reserve_type, instance.id)
for responsable in responsables:
responsable_title = 'Pedido de reserva de %s' % reservable.nome.encode("utf-8")
user_dict["responsable"] = responsable
user_dict["link"] = url
responsable_text = render_to_string("agenda/email_responsable.html", user_dict)
try:
send_mail(responsable_title, "", settings.EMAIL_HOST_USER, [responsable.email], html_message=responsable_text)
except:
messages.error(self.request, 'E-mail não enviado para responsável')
#print(responsable_text)
elif status == 'D':
email_title = 'Reserva de %s negada.' % reservable.nome.encode("utf-8")
user_dict['suffix'] = "foi negada."
elif status == 'C':
email_title = 'Reserva de %s canceada.' % reservable.nome.encode("utf-8")
user_dict['suffix'] = "foi cancelada."
email_text = render_to_string("agenda/email_user.html", user_dict)
try:
send_mail(email_title,"", settings.EMAIL_HOST_USER, [user.email], html_message=email_text)
except:
messages.error(self.request, 'E-mail não enviado para solicitante.')
# print(email_text)
def clean(self):
cleaned_data = super(ReservaAdminForm, self).clean()
recurrent = cleaned_data['recorrente']
errors = dict()
if recurrent and self.is_valid():
# check if starting and ending date was selected
if not cleaned_data['dataFim']:
errors['dataFim'] = 'Este campo é obrigatório.'
if bool(errors):
raise ValidationError(errors)
# check if a day of the week was selected
if not (cleaned_data['seg'] or cleaned_data['ter'] or cleaned_data['qua'] or cleaned_data['qui'] or cleaned_data['sex'] or cleaned_data['sab'] or cleaned_data['dom']):
raise ValidationError({'recorrente': 'Escolha os dias da semana da recorrência.'})
# check if ending date is bigger than starting
if (self.is_new_object) and (cleaned_data['dataFim'] < cleaned_data['data']):
raise ValidationError({'dataFim': 'Data final deve ser maior que a inicial.'})
# if dataInicio is not in the day of the week of the reserve, dataInicio is changed so it is the next one
reserve_days = self.recurrent_week_days()
while not (cleaned_data['data'].weekday() in reserve_days):
cleaned_data['data'] = cleaned_data['data'] + timedelta(days=1)
# Do the same check again
if (self.is_new_object) and (cleaned_data['dataFim'] < cleaned_data['data']):
raise ValidationError({'dataFim': 'Esse período não inclui o dia da semana selecionado.'})
# If fisical aspects of the reserve have been changed we need to check for conflict, otherwise not
check_conflict = False
dont_check_field = ['atividade', 'ramal', 'finalidade', 'usuario', 'recorrente', 'dataInicio', 'dataFim']
# Check form variables
for key in cleaned_data:
if (key in self.changed_data) and (key not in dont_check_field):
check_conflict = True
# Check recurrent object variables
recurrent_object = self.instance.recorrencia
if not self.is_new_object:
if (cleaned_data['dataInicio'] != recurrent_object.dataInicio) or (cleaned_data['dataFim'] != recurrent_object.dataFim):
check_conflict = True
# check if there isn't datetime conflict in the selected timespan
if check_conflict and cleaned_data['estado'] != 'C' and cleaned_data['estado'] != 'D':
error = self.recurrent_option_possible(cleaned_data)
if error:
raise ValidationError({'recorrente': error, 'dataFim': error})
return cleaned_data
def recurrent_week_days(self):
# Set reserve dates
reserve_days = list()
if self.cleaned_data['seg']:
reserve_days.append(0)
if self.cleaned_data['ter']:
reserve_days.append(1)
if self.cleaned_data['qua']:
reserve_days.append(2)
if self.cleaned_data['qui']:
reserve_days.append(3)
if self.cleaned_data['sex']:
reserve_days.append(4)
if self.cleaned_data['sab']:
reserve_days.append(5)
if self.cleaned_data['dom']:
reserve_days.append(6)
return reserve_days
# Maybe this function has to be in the model, but that wouldn't allow correct error feedback for the user
def recurrent_option_possible(self,cleaned_data):
# get necessary variables
reservable = cleaned_data['locavel']
starting_date = cleaned_data['data']
ending_date = cleaned_data['dataFim']
starting_time = cleaned_data['horaInicio']
ending_time = cleaned_data['horaFim']
dummy_activitie = Atividade(nome="dummy", descricao="dummy")
reserve_days = self.recurrent_week_days()
# Don't need to check self reserves in case of an update
try:
query = self.instance.recorrencia.get_reserves()
except:
query = self.reserve_type.objects.none()
# Test max advance reserve
advance = (ending_date - datetime.now().date()).days
if reservable.antecedenciaMaxima != 0:
if advance > reservable.antecedenciaMaxima:
return ('Este locável tem antecedência máxima de %d dias.' % (reservable.antecedenciaMaxima, ))
# test if there's no conflict
if self.is_new_object:
current_date = starting_date
else:
current_date = self.instance.recorrencia.get_reserves()[0].data
error = False
while current_date <= ending_date:
if current_date.weekday() in reserve_days:
dummy_reserve = self.reserve_type(data=current_date, horaInicio=starting_time, horaFim=ending_time, atividade=dummy_activitie, usuario=self.request.user, ramal=1, finalidade='1', locavel=reservable)
error_dict = dict()
dummy_reserve.verificaChoque(error_dict, query)
if bool(error_dict):
error = 'Reservas nesse período causarão choque de horário.'
current_date = current_date + timedelta(days=1)
return error
def save(self, *args, **kwargs):
user_query = kwargs.pop('query', None)
reservable = self.cleaned_data['locavel']
status = self.cleaned_data['estado']
user = self.request.user
instance = super(ReservaAdminForm, self).save(commit=False)
# Check if the user has permission in this reservable
# If it is, the reserve is automatically accepted
have_user_permission = (reservable in user_query) and (not reservable.permissaoNecessaria) or (user in reservable.responsavel.all())
if have_user_permission and self.is_new_object:
status = 'A'
instance.estado = status
instance.save()
# Treat recurrent reserves
if self.cleaned_data['recorrente']:
if self.is_new_object:
self.create_recurrent_reserve(instance)
else:
self.update_recurrent_reserves(instance)
self.send_mail(status, instance)
return instance
def update_recurrent_reserves(self, instance):
# Look for the recurrent reserve that matches the current reserve
current_reserve_chain = instance.recorrencia
# Get queryset
reserve_query = current_reserve_chain.get_reserves()
# Change it's fields to match the new version, except for the data
for reserve in reserve_query:
today = datetime.now().date()
if reserve.data >= today:
for key in reserve.__dict__:
if key != 'data':
setattr(reserve, key, getattr(instance, key))
reserve.save()
current_reserve_chain.update_fields(instance.data)
def create_recurrent_reserve(self, instance):
# If reserve is recurrent, create all reserves
# Get all necessary variables
date = self.cleaned_data['data']
starting_date = date
ending_date = self.cleaned_data['dataFim']
starting_time = self.cleaned_data['horaInicio']
ending_date = self.cleaned_data['dataFim']
ending_time = self.cleaned_data['horaFim']
activity = self.cleaned_data['atividade']
user = self.cleaned_data['usuario']
ramal = self.cleaned_data['ramal']
reason = self.cleaned_data['finalidade']
reservable = self.cleaned_data['locavel']
recurrent_chain = ReservaRecorrente.objects.create(dataInicio=date, dataFim=ending_date) # create the recurrent object that will chain the reserves
recurrent_chain.save()
# Set reserve dates
reserve_days = self.recurrent_week_days()
# Create reserves
instance.recorrencia = recurrent_chain # add the recurrent_chain to the original reserve
current_date = date + timedelta(days=1) # the starting will aready be created by the form
while current_date <= ending_date:
if current_date.weekday() in reserve_days:
recurrent_reserve = self.reserve_type.objects.create(estado=instance.estado, data=current_date, recorrencia=recurrent_chain, horaInicio=starting_time, horaFim=ending_time, atividade=activity, usuario=user, ramal=ramal, finalidade=reason, locavel=reservable)
recurrent_reserve.save()
current_date = current_date + timedelta(days=1)
instance.save()
class ReservaEquipamentoAdminForm(ReservaAdminForm):
class Meta:
model = ReservaEquipamento
fields = '__all__'
def __init__(self, *args, **kwargs):
kwargs['admin_type'] = admin.EquipamentoAdmin
kwargs['reservable_type'] = Equipamento
kwargs['reserve_type'] = ReservaEquipamento
super(ReservaEquipamentoAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
temp_request = self.request
temp_request.user = self.cleaned_data['usuario']
ma = admin.EquipamentoAdmin(Equipamento, AdminSite())
user_query = ma.get_queryset(temp_request)
kwargs['query'] = user_query
return super(ReservaEquipamentoAdminForm, self).save(*args, **kwargs)
class ReservaEspacoFisicoAdminForm(ReservaAdminForm):
class Meta:
model = ReservaEspacoFisico
fields = '__all__'
def __init__(self, *args, **kwargs):
kwargs['admin_type'] = admin.EspacoFisicoAdmin
kwargs['reservable_type'] = EspacoFisico
kwargs['reserve_type'] = ReservaEspacoFisico
super(ReservaEspacoFisicoAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
temp_request = self.request
temp_request.user = self.cleaned_data['usuario']
ma = admin.EspacoFisicoAdmin(EspacoFisico, AdminSite())
user_query = ma.get_queryset(self.request)
kwargs['query'] = user_query
return super(ReservaEspacoFisicoAdminForm, self).save(*args, **kwargs)
class ReservaServicoAdminForm(ReservaAdminForm):
class Meta:
model = ReservaServico
fields = '__all__'
def __init__(self, *args, **kwargs):
kwargs['admin_type'] = admin.ServicoAdmin
kwargs['reservable_type'] = Servico
kwargs['reserve_type'] = ReservaServico
super(ReservaServicoAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
temp_request = self.request
temp_request.user = self.cleaned_data['usuario']
ma = admin.ServicoAdmin(Servico, AdminSite())
user_query = ma.get_queryset(self.request)
kwargs['query'] = user_query
return super(ReservaServicoAdminForm, self).save(*args, **kwargs)
class UnidadeAdminForm(forms.ModelForm):
class Meta:
model = Unidade
fields = ('sigla', 'nome', 'unidadePai', 'grupos', 'responsavel', 'descricao', 'logoLink')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(UnidadeAdminForm, self).__init__(*args, **kwargs)
# get the old responsables for future comparissons
try:
self.initial_responsables = kwargs['instance'].responsavel
# if it's a new form there's no old responsables
except:
self.initial_responsables = User.objects.none()
# check if is an add form or and edit form
self.object = None
if 'instance' in kwargs:
if kwargs['instance']:
self.object = kwargs['instance']
self.init_unidadePai_field()
self.remove_add_and_edit_icons()
self.init_many_to_many_fields()
def init_unidadePai_field(self):
if self.request.user.is_superuser:
self.fields['unidadePai'].queryset = Unidade.objects.all()
else:
if self.object:
unidadePai = Unidade.objects.filter(id=self.object.unidadePai.id).distinct()
else:
unidadePai = Unidade.objects.none()
ma = admin.UnidadeAdmin(Unidade, AdminSite())
queryset = ma.get_queryset(self.request)
# set possible options on the field
self.fields['unidadePai'].queryset = unidadePai | queryset
def init_many_to_many_fields(self):
self.fields['grupos'].widget = FilteredSelectMultipleJs(verbose_name="Grupos", is_stacked=False)
self.fields['grupos'].queryset = Group.objects.all()
self.fields['grupos'].help_text = ''
self.fields['responsavel'].widget = FilteredSelectMultipleJs(verbose_name="Responsáveis", is_stacked=False)
self.fields['responsavel'].queryset = User.objects.all()
self.fields['responsavel'].help_text = ''
def remove_add_and_edit_icons(self):
self.fields['unidadePai'].widget.can_add_related = False # remove add button
self.fields['unidadePai'].widget.can_change_related = False # remove edit button
self.fields['responsavel'].widget.can_add_related = False # remove add button
self.fields['grupos'].widget.can_add_related = False # remove add button
def save(self, *args, **kwargs):
new_responsables = self.cleaned_data['responsavel']
instance = super(UnidadeAdminForm, self).save(commit=False)
instance.save()
link = self.cleaned_data['logoLink']
import urllib2
if link:
request = urllib2.Request(link)
img = urllib2.urlopen(request).read()
with open(settings.BASE_DIR+'/agenda/static/agenda/img/Unidades/'+self.cleaned_data["sigla"]+".jpg", 'w') as f: f.write(img)
group = Group.objects.get_or_create(name='responsables')[0]
# Add new responsables to group
for user in new_responsables:
user.is_staff = True
user.save()
group.user_set.add(user)
for old_responsable in self.initial_responsables.all():
# Check if user removed from responsable.
if old_responsable not in new_responsables.all():
# check if it has other permissions, aside for the one being remove. if not remove from group
user_responsabilities = bool(old_responsable.unidade_set.exclude(id=instance.id))
user_responsabilities = user_responsabilities or bool(old_responsable.espacofisico_set.all())
user_responsabilities = user_responsabilities or bool(old_responsable.equipamento_set.all())
if not user_responsabilities:
group.user_set.remove(old_responsable)
old_responsable.is_staff = False
old_responsable.save()
return instance
def clean(self):
cleaned_data = super(UnidadeAdminForm, self).clean()
father_unit = cleaned_data['unidadePai']
if father_unit==None and not self.request.user.is_superuser:
raise ValidationError({'unidadePai': "Escolha uma unidade pai."})
return cleaned_data
class SearchFilterForm(forms.Form):
def __init__(self, *args, **kwargs):
try:
self.tipo_init = kwargs.pop('tipo')
super(SearchFilterForm,self).__init__(*args,**kwargs)
self.fields['tipo'].initial = self.tipo_init
except:
super(SearchFilterForm,self).__init__(*args,**kwargs)
data = forms.DateField(input_formats=['%d/%m/%Y'], widget=SelectDateWidget())
data.label = ''
horaInicio = forms.TimeField(input_formats=['%H:%M'], widget=SelectTimeWidget(attrs={"label":"Hora Início"}))
horaFim = forms.TimeField(input_formats=['%H:%M'], widget=SelectTimeWidget(attrs={"label":"Hora Fim"}))
tipo = forms.CharField(widget = forms.HiddenInput())
def clean(self):
cleaned_data = super(SearchFilterForm, self).clean()
class LocavelAdminForm(forms.ModelForm):
class Media:
css = {
"all": ("admin/css/locavel_form_fields.css", )
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
self.reservable_type = kwargs.pop('reservable_type')
super(LocavelAdminForm, self).__init__(*args, **kwargs)
self.fields['antecedenciaMinima'].initial = 0
self.fields['antecedenciaMaxima'].initial = 0
self.remove_add_and_edit_icons()
self.init_many_to_many_fields()
ma = admin.UnidadeAdmin(Unidade, AdminSite())
queryset = ma.get_queryset(self.request)
# get current parent so reservable can be edited
try:
queryset = queryset | Unidade.objects.filter(id=kwargs['instance'].unidade.id).distinct()
except:
pass # new reservable, no unit yet
self.fields['unidade'].queryset = queryset
# get the old responsables for future comparissons
try:
self.initial_responsables = kwargs['instance'].responsavel
# if it's a new form there's no old responsables
except:
self.initial_responsables = User.objects.none()
def init_many_to_many_fields(self):
self.fields['grupos'].widget = FilteredSelectMultipleJs(verbose_name="Grupos", is_stacked=False)
self.fields['grupos'].queryset = Group.objects.all()
self.fields['grupos'].help_text = ''
self.fields['responsavel'].widget = FilteredSelectMultipleJs(verbose_name="Responsáveis", is_stacked=False)
self.fields['responsavel'].queryset = User.objects.all()
self.fields['responsavel'].help_text = ''
self.fields['atividadesPermitidas'].widget = FilteredSelectMultipleJs(verbose_name="Atividades permitidas", is_stacked=False)
self.fields['atividadesPermitidas'].queryset = Atividade.objects.all()
self.fields['atividadesPermitidas'].help_text = ''
def remove_add_and_edit_icons(self):
self.fields['responsavel'].widget.can_add_related = False # remove add button
self.fields['responsavel'].widget.can_change_related = False # remove edit button
self.fields['unidade'].widget.can_add_related = False # remove add button
self.fields['unidade'].widget.can_change_related = False # remove edit button
self.fields['atividadesPermitidas'].widget.can_add_related = False # remove add button
self.fields['atividadesPermitidas'].widget.can_change_related = False # remove edit button
self.fields['grupos'].widget.can_add_related = False # remove add button
def save(self, *args, **kwargs):
new_responsables = self.cleaned_data['responsavel']
instance = super(LocavelAdminForm, self).save(commit=False)
instance.save()
link = self.cleaned_data['fotoLink']
import urllib2
if link:
request = urllib2.Request(link)
img = urllib2.urlopen(request).read()
with open(settings.BASE_DIR+'/agenda/static/agenda/img/Locaveis/'+self.cleaned_data["nome"]+".jpg", 'w') as f: f.write(img)
group = Group.objects.get_or_create(name='responsables')[0]
# Add new responsables to group
for user in new_responsables:
user.is_staff = True
user.save()
group.user_set.add(user)
for old_responsable in self.initial_responsables.all():
# Check if user removed from responsable.
if old_responsable not in new_responsables.all():
# check if it has other permissions, aside for the one being remove. if not remove from group
user_responsabilities = bool(old_responsable.unidade_set.all())
if self.reservable_type == Equipamento:
user_responsabilities = user_responsabilities or bool(old_responsable.espacofisico_set.all())
user_responsabilities = user_responsabilities or bool(old_responsable.equipamento_set.exclude(id=instance.id))
elif self.reservable_type == EspacoFisico:
user_responsabilities = user_responsabilities or bool(old_responsable.equipamento_set.all())
user_responsabilities = user_responsabilities or bool(old_responsable.espacofisico_set.exclude(id=instance.id))
if not user_responsabilities:
group.user_set.remove(old_responsable)
old_responsable.is_staff = False
old_responsable.save()
return instance
class EquipamentoAdminForm(LocavelAdminForm):
def __init__(self, *args, **kwargs):
kwargs['reservable_type'] = Equipamento
super(EquipamentoAdminForm, self).__init__(*args, **kwargs)
self.fields["limite_horas"].widget=SelectTimeWidget(attrs={"label":"Limite de", 'class':"class_limite_horas"})
self.fields["periodo_limite"].label = "A cada"
def save(self, *args, **kwargs):
return super(EquipamentoAdminForm, self).save(*args, **kwargs)
class EspacoFisicoAdminForm(LocavelAdminForm):
def __init__(self, *args, **kwargs):
kwargs['reservable_type'] = EspacoFisico
super(EspacoFisicoAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
return super(EspacoFisicoAdminForm, self).save(*args, **kwargs)
class ServicoAdminForm(LocavelAdminForm):
def __init__(self, *args, **kwargs):
kwargs['reservable_type'] = Servico
super(ServicoAdminForm, self).__init__(*args, **kwargs)
self.fields['profissionais'].widget = FilteredSelectMultipleJs(verbose_name="Profissionais", is_stacked=False)
self.fields['profissionais'].queryset = User.objects.all()
self.fields['profissionais'].help_text = ''
def save(self, *args, **kwargs):
return super(ServicoAdminForm, self).save(*args, **kwargs)
class UserAdminForm(UserChangeForm):
class Meta:
model = User
fields = ('username', 'password', 'email', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active', 'groups', 'user_permissions', 'last_login', 'date_joined')
def __init__(self, *args, **kwargs):
super(UserAdminForm, self).__init__(*args, **kwargs)
if not self.request.user.is_superuser:
self.hide_fields()
self.init_groups_field()
self.init_permissions_field()
def init_permissions_field(self):
self.fields['user_permissions'].widget = FilteredSelectMultipleJs(verbose_name="Permissões", is_stacked=False)
self.fields['user_permissions'].help_text = ''
self.fields['user_permissions'].label = 'Permissões'
self.fields['user_permissions'].queryset = Permission.objects.all()
def init_groups_field(self):
self.fields['groups'].widget = FilteredSelectMultipleJs(verbose_name="Grupos", is_stacked=False)
self.fields['groups'].help_text = ''
self.fields['groups'].label = 'Grupos'
self.fields['groups'].queryset = Group.objects.all()
def hide_fields(self):
self.fields['password'].widget = HiddenInput()
self.fields['password'].label = ''
self.fields['password'].help_text = ''
self.fields['is_superuser'].widget = HiddenInput()
self.fields['is_superuser'].label = ''
self.fields['is_superuser'].help_text = ''
self.fields['is_staff'].widget = HiddenInput()
self.fields['is_staff'].label = ''
self.fields['is_staff'].help_text = ''
self.fields['is_active'].widget = HiddenInput()
self.fields['is_active'].label = ''
self.fields['is_active'].help_text = ''
class GroupAdminForm(forms.ModelForm):
class Meta:
model = Group
exclude=[]
users = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
required=False,
widget=FilteredSelectMultiple('users', False)
)
def __init__(self, *args, **kwargs):
super(GroupAdminForm, self).__init__(*args, **kwargs)
if self.instance.pk:
self.fields['users'].initial = self.instance.user_set.all()
def save_m2m(self):
self.instance.user_set = self.cleaned_data['users']
def save(self, *args, **kwargs):
instance = super(GroupAdminForm, self).save()
self.save_m2m()
return instance
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text="Obrigatório. Informe um email válido")
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
class EstatisticaForm(forms.Form):
def __init__(self, usr, *args, **kwargs):
super(EstatisticaForm, self).__init__(*args,**kwargs)
if usr != None:
if not usr.is_superuser:
self.fields["equipamento_choose"].queryset = Equipamento.objects.filter(responsavel=usr)
self.fields["espacofisico_choose"].queryset = EspacoFisico.objects.filter(responsavel=usr)
usuario = forms.ModelChoiceField(queryset=User.objects.all(), required=True, widget=AutocompleteWidget(query=User.objects.all(), model=User))
periodo_inicio = forms.DateField(widget=forms.DateInput(attrs={"class":"date_picker", "placeholder":"da data"}), required=True)
periodo_fim = forms.DateField(widget=forms.DateInput(attrs={"class":"date_picker", "placeholder":"ate a data"}), required=True)
equipamento_choose = forms.ModelMultipleChoiceField(queryset=Equipamento.objects.all(), required=False, widget=FilteredSelectMultiple("equipamento_choose",False))
espacofisico_choose = forms.ModelMultipleChoiceField(queryset=EspacoFisico.objects.all(), required=False, widget=FilteredSelectMultiple("espacofisico_choose",False))
| gpl-2.0 |
vanilla/vanilla | packages/vanilla-dom-utils/src/events.test.ts | 4216 | /**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import { expect } from "chai";
import sinon from "sinon";
import { delegateEvent, removeAllDelegatedEvents, removeDelegatedEvent } from "./index";
describe("delegateEvent()", () => {
beforeEach(() => {
removeAllDelegatedEvents();
document.body.innerHTML = `
<div>
<div class="scope1">
<button class="filterSelector">MyButton</button>
<button class="altFilterSelector">OtherButton</button>
</div>
<div class="scope2">
<button class="filterSelector">MyButton</button>
<button class="altFilterSelector">OtherButton</button>
</div>
</div>
`;
});
it("A event can be registered successfully", () => {
const callback = sinon.spy();
delegateEvent("click", "", callback);
const button = document.querySelector(".filterSelector") as HTMLElement;
button.click();
sinon.assert.calledOnce(callback);
});
it("identical events will not be registered twice", () => {
const callback = sinon.spy();
const hash1 = delegateEvent("click", "", callback);
const hash2 = delegateEvent("click", "", callback);
const hash3 = delegateEvent("click", "", callback);
const button = document.querySelector(".filterSelector") as HTMLElement;
button.click();
sinon.assert.calledOnce(callback);
// Hashes should all be for the same handler.
expect(hash1).eq(hash2);
expect(hash2).eq(hash3);
});
describe("delegation filtering works()", () => {
const callback = sinon.spy();
beforeEach(() => {
delegateEvent("click", ".filterSelector", callback);
});
it("events can be delegated to their filterSelector", () => {
document.querySelectorAll(".filterSelector").forEach((button: HTMLElement) => {
button.click();
});
sinon.assert.calledTwice(callback);
});
it("delegated events only match their filterSelector", () => {
callback.resetHistory();
document.querySelectorAll(".altFilterSelector").forEach((button: HTMLElement) => {
button.click();
});
sinon.assert.notCalled(callback);
});
});
describe("delegation scoping works", () => {
const callback = sinon.spy();
beforeEach(() => {
delegateEvent("click", "", callback, ".scope1");
});
it("events can be scoped to their scopeSelector", () => {
document.querySelectorAll(".scope1 button").forEach((button: HTMLElement) => {
button.click();
});
sinon.assert.calledTwice(callback);
});
it("delegated events only match their scopeSelector", () => {
callback.resetHistory();
document.querySelectorAll(".scope2 button").forEach((button: HTMLElement) => {
button.click();
});
sinon.assert.notCalled(callback);
});
});
});
describe("removeDelegatedEvent() && removeAllDelegatedEvents()", () => {
const callback1 = sinon.spy();
const callback2 = sinon.spy();
let eventHandler1;
let eventHandler2;
beforeEach(() => {
callback1.resetHistory();
callback2.resetHistory();
eventHandler1 = delegateEvent("click", "", callback1);
eventHandler2 = delegateEvent("click", ".scope1", callback2, ".filterSelector");
});
it("can remove a single event", () => {
removeDelegatedEvent(eventHandler1);
(document.querySelector(".scope1 .filterSelector") as HTMLElement).click();
sinon.assert.notCalled(callback1);
sinon.assert.calledOnce(callback2);
});
it("can remove all events", () => {
removeAllDelegatedEvents();
(document.querySelector(".scope1 .filterSelector") as HTMLElement).click();
sinon.assert.notCalled(callback1);
sinon.assert.notCalled(callback2);
});
});
| gpl-2.0 |
CoderHam/Machine_Learning_Projects | random_forest/hemant_randForest.py | 1805 | #!/usr/bin/python
import matplotlib.pyplot as plt
from prep_terrain_data import makeTerrainData
from class_vis import prettyPicture
from time import time
features_train, labels_train, features_test, labels_test = makeTerrainData()
### the training data (features_train, labels_train) have both "fast" and "slow" points mixed
### in together--separate them so we can give them different colors in the scatterplot,
### and visually identify them
grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0]
bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0]
grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1]
bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1]
#### initial visualization
plt.xlim(0.0, 1.0)
plt.ylim(0.0, 1.0)
plt.scatter(bumpy_fast, grade_fast, color = "b", label="fast")
plt.scatter(grade_slow, bumpy_slow, color = "r", label="slow")
plt.legend()
plt.xlabel("bumpiness")
plt.ylabel("grade")
#plt.show()
#################################################################################
### your code here! name your classifier object clf if you want the
### visualization code (prettyPicture) to show you the decision boundary
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=10)
t0 = time()
clf.fit(features_train, labels_train)
print "training time:", round(time()-t0, 3), "s"
t0 = time()
pred = clf.predict(features_test)
print "precition time:", round(time()-t0, 3), "s"
from sklearn.metrics import accuracy_score
print accuracy_score(pred, labels_test)
# try:
# prettyPicture(clf, features_test, labels_test)
# except NameError:
# pass
| gpl-2.0 |
cathral/mintra-homepage | wp-content/plugins/stella-free/js/bloginfo-tabs.js | 1877 | /*
* Usage: Everywhere
*/
jQuery(document).ready(function($) {
if( bloginfo_langs != null ){
var bloginfo_vars = $.parseJSON(bloginfo_langs);
}
if( $('#blogname').length )
{
$('form table.form-table').before('<div id="bloginfo-tabs"></div>');
$('#bloginfo-tabs').prepend('<div class="tabs-nav"><ul></ul></div>');
for(i = 0; i < bloginfo_vars['langs'].length;i++){
// tab navigation elements
if( i == 0 ) $('#bloginfo-tabs .tabs-nav ul').append('<li><a href="#bloginfo-tab-'+ bloginfo_vars['langs'][i][0]+'">' + bloginfo_vars['langs'][i][1] + '<span class="default-label"> ( ' + bloginfo_vars['default_str'] + ' )</span></a></li>');
else $('#bloginfo-tabs .tabs-nav ul').append('<li><a href="#bloginfo-tab-'+ bloginfo_vars['langs'][i][0]+'">' + bloginfo_vars['langs'][i][1] + '</a></li>');
// tab elements
$('#bloginfo-tabs').append('<div id="bloginfo-tab-' + bloginfo_vars['langs'][i][0] + '"><table class="form-table"></table></div>');
if( i == 0) {
var blogname_elem = $('#blogname').parent().parent().detach();
var blogdescription_elem = $('#blogdescription').parent().parent().detach();
$('#bloginfo-tab-' + bloginfo_vars['langs'][i][0] + ' table').append(blogname_elem);
$('#bloginfo-tab-' + bloginfo_vars['langs'][i][0] + ' table').append(blogdescription_elem);
}else{
var blogname_elem = $('#blogname-' + bloginfo_vars['langs'][i][0] ).parent().parent().detach();
var blogdescription_elem = $('#blogdescription-' + bloginfo_vars['langs'][i][0] ).parent().parent().detach();
$('#bloginfo-tab-' + bloginfo_vars['langs'][i][0] + ' table').append(blogname_elem);
$('#bloginfo-tab-' + bloginfo_vars['langs'][i][0] + ' table').append(blogdescription_elem);
}
}
$('#bloginfo-tabs').append('<div class="tabs-separator"></div>');
}
$('#bloginfo-tabs').tabs();
});
| gpl-2.0 |
ProTip/metricus | plugins/SitesFilter/SitesFilter.cs | 6326 | using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using ServiceStack.Text;
using Microsoft.Web.Administration;
using System.Text.RegularExpressions;
using System.Linq;
namespace Metricus.Plugin
{
public class SitesFilter : FilterPlugin, IFilterPlugin
{
private SitesFilterConfig config;
private Dictionary<int, string> siteIDtoName;
private ServerManager ServerManager;
private System.Timers.Timer LoadSitesTimer;
private Object RefreshLock = new Object();
private class SitesFilterConfig {
public Dictionary<string,ConfigCategory> Categories { get; set; }
}
private class ConfigCategory {
public bool PreserveOriginal { get; set; }
}
public class ConfigCategories
{
public const string AspNetApplications = "ASP.NET Applications";
public const string Process = "Process";
}
public SitesFilter(PluginManager pm) : base(pm) {
var path = Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location);
var configFile = path + "/config.json";
Console.WriteLine ("Loading config from {0}", configFile);
config = JsonSerializer.DeserializeFromString<SitesFilterConfig> (File.ReadAllText (path + "/config.json"));
Console.WriteLine ("Loaded config : {0}", config.Dump ());
siteIDtoName = new Dictionary<int, string> ();
this.LoadSites ();
LoadSitesTimer = new System.Timers.Timer(60000);
LoadSitesTimer.Elapsed += (o, e) => this.LoadSites();
LoadSitesTimer.Start();
}
public override List<metric> Work(List<metric> m) {
lock(RefreshLock)
{
if (config.Categories.ContainsKey(ConfigCategories.AspNetApplications))
{
m = FilterAspNetC.Filter(m, this.siteIDtoName, config.Categories[ConfigCategories.AspNetApplications].PreserveOriginal);
}
if (config.Categories.ContainsKey(ConfigCategories.Process))
m = FilterWorkerPoolProcesses.Filter(m, ServerManager, config.Categories[ConfigCategories.Process].PreserveOriginal);
}
return m;
}
public class FilterWorkerPoolProcesses
{
public static string IdCategory = ConfigCategories.Process;
public static string IdCounter = "ID Process";
public static Dictionary<string, int> WpNamesToIds = new Dictionary<string, int>();
public static List<metric> Filter(List<metric> metrics, ServerManager serverManager,bool preserveOriginal)
{
// "Listen" to the process id counters to map instance names to process id's
metric m;
int wpId;
var originalMetricsCount = metrics.Count;
for (int x = 0; x < originalMetricsCount;x++ )
{
m = metrics[x];
if (m.category != IdCategory)
continue;
if (m.type == IdCounter)
{
WpNamesToIds[m.instance] = (int)m.value;
continue;
}
if (m.instance.StartsWith("w3wp", StringComparison.Ordinal) && WpNamesToIds.TryGetValue(m.instance, out wpId))
{
for (int y = 0; y < serverManager.WorkerProcesses.Count; y++)
{
if (serverManager.WorkerProcesses[y].ProcessId == wpId)
{
m.instance = serverManager.WorkerProcesses[y].AppPoolName;
switch(preserveOriginal)
{
case true:
metrics.Add(m); break;
case false:
metrics[x] = m; break;
}
}
}
}
}
return metrics;
}
}
public class FilterAspNetC
{
private static string PathSansId = "_LM_W3SVC";
private static Regex MatchPathWithId = new Regex("_LM_W3SVC_(\\d+)_");
private static Regex MatchRoot = new Regex("ROOT_?");
public static List<metric> Filter(List<metric> metrics, Dictionary<int,string> siteIdsToNames, bool preserveOriginal)
{
var returnMetrics = new List<metric>();
foreach (var metric in metrics)
{
var newMetric = metric;
if (metric.instance.Contains(PathSansId))
{
var match = MatchPathWithId.Match(metric.instance);
var id = match.Groups[1].Value;
string siteName;
if (siteIdsToNames.TryGetValue(int.Parse(id), out siteName))
{
newMetric.instance = Regex.Replace(metric.instance, "_LM_W3SVC_(\\d+)_ROOT_?", siteName + "/");
returnMetrics.Add(newMetric);
}
if (preserveOriginal)
returnMetrics.Add(metric);
}
else
returnMetrics.Add(newMetric);
}
return returnMetrics;
}
}
public void LoadSites() {
lock (RefreshLock)
{
if(ServerManager != null)
ServerManager.Dispose();
ServerManager = new Microsoft.Web.Administration.ServerManager();
siteIDtoName.Clear();
foreach (var site in ServerManager.Sites)
{
this.siteIDtoName.Add((int)site.Id, site.Name);
}
this.siteIDtoName.PrintDump();
}
}
}
} | gpl-2.0 |
NatLibFi/NDL-VuFind2 | module/Finna/src/Finna/View/Helper/Root/OpenUrlFactory.php | 3492 | <?php
/**
* OpenUrl helper factory.
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
* Copyright (C) The National Library of Finland 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package View_Helpers
* @author Demian Katz <[email protected]>
* @author Ere Maijala <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
namespace Finna\View\Helper\Root;
use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
use Laminas\ServiceManager\Factory\FactoryInterface;
/**
* OpenUrl helper factory.
*
* @category VuFind
* @package View_Helpers
* @author Demian Katz <[email protected]>
* @author Ere Maijala <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class OpenUrlFactory implements FactoryInterface
{
/**
* Create an object
*
* @param ContainerInterface $container Service manager
* @param string $requestedName Service being created
* @param null|array $options Extra options (optional)
*
* @return object
*
* @throws ServiceNotFoundException if unable to resolve the service.
* @throws ServiceNotCreatedException if an exception is raised when
* creating a service.
* @throws ContainerException if any other error occurs
*/
public function __invoke(
ContainerInterface $container,
$requestedName,
array $options = null
) {
if (!empty($options)) {
throw new \Exception('Unexpected options sent to factory.');
}
$config
= $container->get(\VuFind\Config\PluginManager::class)->get('config');
$file = \VuFind\Config\Locator::getLocalConfigPath('OpenUrlRules.json');
if ($file === null) {
$file = \VuFind\Config\Locator::getLocalConfigPath(
'OpenUrlRules.json',
'config/finna'
);
if ($file === null) {
$file = \VuFind\Config\Locator::getConfigPath('OpenUrlRules.json');
}
}
$openUrlRules = json_decode(file_get_contents($file), true);
$resolverPluginManager
= $container->get(\VuFind\Resolver\Driver\PluginManager::class);
$helpers = $container->get('ViewHelperManager');
return new $requestedName(
$helpers->get('context'),
$openUrlRules,
$resolverPluginManager,
$config->OpenURL ?? null
);
}
}
| gpl-2.0 |
Kirshan/ALiveCoreRC2 | src/server/game/Spells/Spell.cpp | 309687 | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 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 "DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Opcodes.h"
#include "Log.h"
#include "UpdateMask.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Pet.h"
#include "Unit.h"
#include "Totem.h"
#include "Spell.h"
#include "DynamicObject.h"
#include "Group.h"
#include "UpdateData.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "CellImpl.h"
#include "SharedDefines.h"
#include "LootMgr.h"
#include "VMapFactory.h"
#include "Battleground.h"
#include "Util.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
#include "SpellAuraEffects.h"
#include "ScriptMgr.h"
#include "ConditionMgr.h"
#include "DisableMgr.h"
#include "SpellScript.h"
#include "InstanceScript.h"
#include "SpellInfo.h"
#include "OutdoorPvPWG.h"
#include "OutdoorPvPMgr.h"
extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0)
{
m_unitTarget = NULL;
m_itemTarget = NULL;
m_GOTarget = NULL;
m_unitTargetGUID = 0;
m_GOTargetGUID = 0;
m_CorpseTargetGUID = 0;
m_itemTargetGUID = 0;
m_itemTargetEntry = 0;
m_srcTransGUID = 0;
m_srcTransOffset.Relocate(0, 0, 0, 0);
m_srcPos.Relocate(0, 0, 0, 0);
m_dstTransGUID = 0;
m_dstTransOffset.Relocate(0, 0, 0, 0);
m_dstPos.Relocate(0, 0, 0, 0);
m_strTarget = "";
m_targetMask = 0;
}
SpellCastTargets::~SpellCastTargets()
{
}
SpellCastTargets& SpellCastTargets::operator=(const SpellCastTargets &target)
{
m_unitTarget = target.m_unitTarget;
m_itemTarget = target.m_itemTarget;
m_GOTarget = target.m_GOTarget;
m_unitTargetGUID = target.m_unitTargetGUID;
m_GOTargetGUID = target.m_GOTargetGUID;
m_CorpseTargetGUID = target.m_CorpseTargetGUID;
m_itemTargetGUID = target.m_itemTargetGUID;
m_itemTargetEntry = target.m_itemTargetEntry;
m_srcTransGUID = target.m_srcTransGUID;
m_srcTransOffset = target.m_srcTransOffset;
m_srcPos = target.m_srcPos;
m_dstTransGUID = target.m_dstTransGUID;
m_dstTransOffset = target.m_dstTransOffset;
m_dstPos = target.m_dstPos;
m_elevation = target.m_elevation;
m_speed = target.m_speed;
m_strTarget = target.m_strTarget;
m_targetMask = target.m_targetMask;
return *this;
}
void SpellCastTargets::Read(ByteBuffer& data, Unit* caster)
{
data >> m_targetMask;
if (m_targetMask == TARGET_FLAG_SELF)
return;
if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_UNIT_MINIPET))
data.readPackGUID(m_unitTargetGUID);
if (m_targetMask & (TARGET_FLAG_GAMEOBJECT))
data.readPackGUID(m_GOTargetGUID);
if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM))
data.readPackGUID(m_itemTargetGUID);
if (m_targetMask & (TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_CORPSE_ALLY))
data.readPackGUID(m_CorpseTargetGUID);
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
{
data.readPackGUID(m_srcTransGUID);
if (m_srcTransGUID)
data >> m_srcTransOffset.PositionXYZStream();
else
data >> m_srcPos.PositionXYZStream();
}
else
{
m_srcTransGUID = caster->GetTransGUID();
if (m_srcTransGUID)
m_srcTransOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO());
else
m_srcPos.Relocate(caster);
}
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
{
data.readPackGUID(m_dstTransGUID);
if (m_dstTransGUID)
data >> m_dstTransOffset.PositionXYZStream();
else
data >> m_dstPos.PositionXYZStream();
}
else
{
m_dstTransGUID = caster->GetTransGUID();
if (m_dstTransGUID)
m_dstTransOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO());
else
m_dstPos.Relocate(caster);
}
if (m_targetMask & TARGET_FLAG_STRING)
data >> m_strTarget;
Update(caster);
}
void SpellCastTargets::Write(ByteBuffer& data)
{
data << uint32(m_targetMask);
if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_UNIT_MINIPET))
{
if (m_targetMask & TARGET_FLAG_UNIT)
{
if (m_unitTarget)
data.append(m_unitTarget->GetPackGUID());
else
data << uint8(0);
}
else if (m_targetMask & TARGET_FLAG_GAMEOBJECT)
{
if (m_GOTarget)
data.append(m_GOTarget->GetPackGUID());
else
data << uint8(0);
}
else if (m_targetMask & (TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_CORPSE_ENEMY))
data.appendPackGUID(m_CorpseTargetGUID);
else
data << uint8(0);
}
if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM))
{
if (m_itemTarget)
data.append(m_itemTarget->GetPackGUID());
else
data << uint8(0);
}
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
{
data.appendPackGUID(m_srcTransGUID); // relative position guid here - transport for example
if (m_srcTransGUID)
data << m_srcTransOffset.PositionXYZStream();
else
data << m_srcPos.PositionXYZStream();
}
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
{
data.appendPackGUID(m_dstTransGUID); // relative position guid here - transport for example
if (m_dstTransGUID)
data << m_dstTransOffset.PositionXYZStream();
else
data << m_dstPos.PositionXYZStream();
}
if (m_targetMask & TARGET_FLAG_STRING)
data << m_strTarget;
}
void SpellCastTargets::SetUnitTarget(Unit* target)
{
if (!target)
return;
m_unitTarget = target;
m_unitTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_UNIT;
}
Position const* SpellCastTargets::GetSrc() const
{
return &m_srcPos;
}
void SpellCastTargets::SetSrc(float x, float y, float z)
{
m_srcPos.Relocate(x, y, z);
m_srcTransGUID = 0;
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(Position const& pos)
{
m_srcPos.Relocate(pos);
m_srcTransGUID = 0;
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(WorldObject const& wObj)
{
uint64 guid = wObj.GetTransGUID();
m_srcTransGUID = guid;
m_srcTransOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO());
m_srcPos.Relocate(wObj);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::ModSrc(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION);
if (m_srcTransGUID)
{
Position offset;
m_srcPos.GetPositionOffsetTo(pos, offset);
m_srcTransOffset.RelocateOffset(offset);
}
m_srcPos.Relocate(pos);
}
WorldLocation const* SpellCastTargets::GetDst() const
{
return &m_dstPos;
}
void SpellCastTargets::SetDst(float x, float y, float z, float orientation, uint32 mapId)
{
m_dstPos.Relocate(x, y, z, orientation);
m_dstTransGUID = 0;
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
if (mapId != MAPID_INVALID)
m_dstPos.m_mapId = mapId;
}
void SpellCastTargets::SetDst(Position const& pos)
{
m_dstPos.Relocate(pos);
m_dstTransGUID = 0;
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(WorldObject const& wObj)
{
uint64 guid = wObj.GetTransGUID();
m_dstTransGUID = guid;
m_dstTransOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO());
m_dstPos.Relocate(wObj);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(SpellCastTargets const& spellTargets)
{
m_dstTransGUID = spellTargets.m_dstTransGUID;
m_dstTransOffset.Relocate(spellTargets.m_dstTransOffset);
m_dstPos.Relocate(spellTargets.m_dstPos);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::ModDst(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION);
if (m_dstTransGUID)
{
Position offset;
m_dstPos.GetPositionOffsetTo(pos, offset);
m_dstTransOffset.RelocateOffset(offset);
}
m_dstPos.Relocate(pos);
}
void SpellCastTargets::SetGOTarget(GameObject* target)
{
m_GOTarget = target;
m_GOTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_GAMEOBJECT;
}
void SpellCastTargets::SetItemTarget(Item* item)
{
if (!item)
return;
m_itemTarget = item;
m_itemTargetGUID = item->GetGUID();
m_itemTargetEntry = item->GetEntry();
m_targetMask |= TARGET_FLAG_ITEM;
}
void SpellCastTargets::SetTradeItemTarget(Player* caster)
{
m_itemTargetGUID = uint64(TRADE_SLOT_NONTRADED);
m_itemTargetEntry = 0;
m_targetMask |= TARGET_FLAG_TRADE_ITEM;
Update(caster);
}
void SpellCastTargets::UpdateTradeSlotItem()
{
if (m_itemTarget && (m_targetMask & TARGET_FLAG_TRADE_ITEM))
{
m_itemTargetGUID = m_itemTarget->GetGUID();
m_itemTargetEntry = m_itemTarget->GetEntry();
}
}
void SpellCastTargets::SetCorpseTarget(Corpse* corpse)
{
m_CorpseTargetGUID = corpse->GetGUID();
}
void SpellCastTargets::Update(Unit* caster)
{
m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
m_unitTarget = m_unitTargetGUID ? (m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID)) : NULL;
m_itemTarget = NULL;
if (caster->GetTypeId() == TYPEID_PLAYER)
{
Player* player = caster->ToPlayer();
if (m_targetMask & TARGET_FLAG_ITEM)
m_itemTarget = player->GetItemByGuid(m_itemTargetGUID);
else if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
if (m_itemTargetGUID == TRADE_SLOT_NONTRADED) // here it is not guid but slot. Also prevents hacking slots
if (TradeData* pTrade = player->GetTradeData())
m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED);
if (m_itemTarget)
m_itemTargetEntry = m_itemTarget->GetEntry();
}
// update positions by transport move
if (HasSrc() && m_srcTransGUID)
{
if (WorldObject * transport = ObjectAccessor::GetWorldObject(*caster, m_srcTransGUID))
{
m_srcPos.Relocate(transport);
m_srcPos.RelocateOffset(m_srcTransOffset);
}
}
if (HasDst() && m_dstTransGUID)
{
if (WorldObject * transport = ObjectAccessor::GetWorldObject(*caster, m_dstTransGUID))
{
m_dstPos.Relocate(transport);
m_dstPos.RelocateOffset(m_dstTransOffset);
}
}
}
void SpellCastTargets::OutDebug() const
{
if (!m_targetMask)
sLog->outString("TARGET_FLAG_SELF");
if (m_targetMask & TARGET_FLAG_UNIT)
sLog->outString("TARGET_FLAG_UNIT: " UI64FMTD, m_unitTargetGUID);
if (m_targetMask & TARGET_FLAG_UNIT_MINIPET)
sLog->outString("TARGET_FLAG_UNIT_MINIPET: " UI64FMTD, m_unitTargetGUID);
if (m_targetMask & TARGET_FLAG_GAMEOBJECT)
sLog->outString("TARGET_FLAG_GAMEOBJECT: " UI64FMTD, m_GOTargetGUID);
if (m_targetMask & TARGET_FLAG_CORPSE_ENEMY)
sLog->outString("TARGET_FLAG_CORPSE_ENEMY: " UI64FMTD, m_CorpseTargetGUID);
if (m_targetMask & TARGET_FLAG_CORPSE_ALLY)
sLog->outString("TARGET_FLAG_CORPSE_ALLY: " UI64FMTD, m_CorpseTargetGUID);
if (m_targetMask & TARGET_FLAG_ITEM)
sLog->outString("TARGET_FLAG_ITEM: " UI64FMTD, m_itemTargetGUID);
if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
sLog->outString("TARGET_FLAG_TRADE_ITEM: " UI64FMTD, m_itemTargetGUID);
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
sLog->outString("TARGET_FLAG_SOURCE_LOCATION: transport guid:" UI64FMTD " trans offset: %s position: %s", m_srcTransGUID, m_srcTransOffset.ToString().c_str(), m_srcPos.ToString().c_str());
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
sLog->outString("TARGET_FLAG_DEST_LOCATION: transport guid:" UI64FMTD " trans offset: %s position: %s", m_dstTransGUID, m_dstTransOffset.ToString().c_str(), m_dstPos.ToString().c_str());
if (m_targetMask & TARGET_FLAG_STRING)
sLog->outString("TARGET_FLAG_STRING: %s", m_strTarget.c_str());
sLog->outString("speed: %f", m_speed);
sLog->outString("elevation: %f", m_elevation);
}
SpellValue::SpellValue(SpellInfo const* proto)
{
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
EffectBasePoints[i] = proto->Effects[i].BasePoints;
MaxAffectedTargets = proto->MaxAffectedTargets;
RadiusMod = 1.0f;
AuraStackAmount = 1;
}
Spell::Spell(Unit* caster, SpellInfo const *info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID, bool skipCheck) :
m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)),
m_caster(caster), m_spellValue(new SpellValue(m_spellInfo))
{
m_customError = SPELL_CUSTOM_ERROR_NONE;
m_skipCheck = skipCheck;
m_selfContainer = NULL;
m_referencedFromCurrentSpell = false;
m_executedCurrently = false;
m_needComboPoints = m_spellInfo->NeedsComboPoints();
m_comboPointGain = 0;
m_delayStart = 0;
m_delayAtDamageCount = 0;
m_applyMultiplierMask = 0;
m_effectMask = 0;
m_auraScaleMask = 0;
// Get data for type of attack
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND)
m_attackType = OFF_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
case SPELL_DAMAGE_CLASS_RANGED:
m_attackType = m_spellInfo->IsRangedWeaponSpell() ? RANGED_ATTACK : BASE_ATTACK;
break;
default:
// Wands
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)
m_attackType = RANGED_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
}
m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example)
if (m_attackType == RANGED_ATTACK)
// wand case
if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK))
m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->Damage[0].DamageType);
if (originalCasterGUID)
m_originalCasterGUID = originalCasterGUID;
else
m_originalCasterGUID = m_caster->GetGUID();
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
}
m_spellState = SPELL_STATE_NULL;
_triggeredCastFlags = triggerFlags;
if (info->AttributesEx4 & SPELL_ATTR4_TRIGGERED)
_triggeredCastFlags = TRIGGERED_FULL_MASK;
m_CastItem = NULL;
m_castItemGUID = 0;
unitTarget = NULL;
itemTarget = NULL;
gameObjTarget = NULL;
focusObject = NULL;
m_cast_count = 0;
m_glyphIndex = 0;
m_preCastSpell = 0;
m_triggeredByAuraSpell = NULL;
m_spellAura = NULL;
//Auto Shot & Shoot (wand)
m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell();
m_runesState = 0;
m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
m_timer = 0; // will set to castime in prepare
m_channelTargetEffectMask = 0;
// Determine if spell can be reflected back to the caster
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->Attributes & SPELL_ATTR0_ABILITY)
&& !(m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REFLECTED) && !(m_spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
&& !m_spellInfo->IsPassive() && !m_spellInfo->IsPositive();
CleanupTargetList();
CleanupEffectExecuteData();
}
/*
Spell::Spell2(Unit* caster, SpellEntry const *info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID, bool skipCheck) :
m_spellInfo2(sSpellMgr->GetSpellForDifficultyFromSpell(0, caster)),
m_caster(caster), m_spellValue(new SpellValue(m_spellInfo))
{
m_customError = SPELL_CUSTOM_ERROR_NONE;
m_skipCheck = skipCheck;
m_selfContainer = NULL;
m_referencedFromCurrentSpell = false;
m_executedCurrently = false;
m_needComboPoints = m_spellInfo->NeedsComboPoints();
m_comboPointGain = 0;
m_delayStart = 0;
m_delayAtDamageCount = 0;
m_applyMultiplierMask = 0;
m_effectMask = 0;
m_auraScaleMask = 0;
// Get data for type of attack
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND)
m_attackType = OFF_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
case SPELL_DAMAGE_CLASS_RANGED:
m_attackType = m_spellInfo->IsRangedWeaponSpell() ? RANGED_ATTACK : BASE_ATTACK;
break;
default:
// Wands
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)
m_attackType = RANGED_ATTACK;
else
m_attackType = BASE_ATTACK;
break;
}
m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example)
if (m_attackType == RANGED_ATTACK)
// wand case
if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK))
m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->Damage[0].DamageType);
if (originalCasterGUID)
m_originalCasterGUID = originalCasterGUID;
else
m_originalCasterGUID = m_caster->GetGUID();
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
}
m_spellState = SPELL_STATE_NULL;
_triggeredCastFlags = triggerFlags;
if (info->AttributesEx4 & SPELL_ATTR4_TRIGGERED)
_triggeredCastFlags = TRIGGERED_FULL_MASK;
m_CastItem = NULL;
m_castItemGUID = 0;
unitTarget = NULL;
itemTarget = NULL;
gameObjTarget = NULL;
focusObject = NULL;
m_cast_count = 0;
m_glyphIndex = 0;
m_preCastSpell = 0;
m_triggeredByAuraSpell = NULL;
m_spellAura = NULL;
//Auto Shot & Shoot (wand)
m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell();
m_runesState = 0;
m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
m_timer = 0; // will set to castime in prepare
m_channelTargetEffectMask = 0;
// Determine if spell can be reflected back to the caster
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !(m_spellInfo->Attributes & SPELL_ATTR0_ABILITY)
&& !(m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REFLECTED) && !(m_spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
&& !m_spellInfo->IsPassive() && !m_spellInfo->IsPositive();
CleanupTargetList();
CleanupEffectExecuteData();
}
*/
Spell::~Spell()
{
// unload scripts
while(!m_loadedScripts.empty())
{
std::list<SpellScript *>::iterator itr = m_loadedScripts.begin();
(*itr)->_Unload();
delete (*itr);
m_loadedScripts.erase(itr);
}
if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this)
{
// Clean the reference to avoid later crash.
// If this error is repeating, we may have to add an ASSERT to better track down how we get into this case.
sLog->outError("SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id);
*m_selfContainer = NULL;
}
if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER)
ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this);
delete m_spellValue;
CheckEffectExecuteData();
}
template<typename T>
WorldObject* Spell::FindCorpseUsing()
{
// non-standard target selection
float max_range = m_spellInfo->GetMaxRange(false);
CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
WorldObject* result = NULL;
T u_check(m_caster, max_range);
Trinity::WorldObjectSearcher<T> searcher(m_caster, result, u_check);
TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher);
cell.Visit(p, grid_searcher, *m_caster->GetMap(), *m_caster, max_range);
if (!result)
{
TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher);
cell.Visit(p, world_searcher, *m_caster->GetMap(), *m_caster, max_range);
}
return result;
}
void Spell::SelectSpellTargets()
{
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// not call for empty effect.
// Also some spells use not used effect targets for store targets for dummy effect in triggered spells
if (!m_spellInfo->Effects[i].Effect)
continue;
uint32 effectTargetType = m_spellInfo->Effects[i].GetRequiredTargetType();
// is it possible that areaaura is not applied to caster?
if (effectTargetType == SPELL_REQUIRE_NONE)
continue;
uint32 targetA = m_spellInfo->Effects[i].TargetA.GetTarget();
uint32 targetB = m_spellInfo->Effects[i].TargetB.GetTarget();
if (targetA)
SelectEffectTargets(i, m_spellInfo->Effects[i].TargetA);
if (targetB) // In very rare case !A && B
SelectEffectTargets(i, m_spellInfo->Effects[i].TargetB);
if (effectTargetType != SPELL_REQUIRE_UNIT)
{
if (effectTargetType == SPELL_REQUIRE_CASTER)
AddUnitTarget(m_caster, i);
else if (effectTargetType == SPELL_REQUIRE_ITEM)
if (m_targets.GetItemTarget())
AddItemTarget(m_targets.GetItemTarget(), i);
continue;
}
if (!targetA && !targetB)
{
if (!m_spellInfo->GetMaxRange(true))
{
AddUnitTarget(m_caster, i);
continue;
}
// add here custom effects that need default target.
// FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
switch(m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_DUMMY:
{
switch(m_spellInfo->Id)
{
case 20577: // Cannibalize
case 54044: // Carrion Feeder
{
WorldObject* result = NULL;
if (m_spellInfo->Id == 20577)
result = FindCorpseUsing<Trinity::CannibalizeObjectCheck>();
else
result = FindCorpseUsing<Trinity::CarrionFeederObjectCheck>();
if (result)
{
switch(result->GetTypeId())
{
case TYPEID_UNIT:
case TYPEID_PLAYER:
AddUnitTarget((Unit*)result, i);
break;
case TYPEID_CORPSE:
m_targets.SetCorpseTarget((Corpse*)result);
if (Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
AddUnitTarget(owner, i);
break;
default:
break;
}
}
else
{
// clear cooldown at fail
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true);
SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
finish(false);
}
break;
}
default:
if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
else
AddUnitTarget(m_caster, i);
break;
}
break;
}
case SPELL_EFFECT_BIND:
case SPELL_EFFECT_RESURRECT:
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_TRIGGER_SPELL:
case SPELL_EFFECT_SKILL_STEP:
case SPELL_EFFECT_PROFICIENCY:
case SPELL_EFFECT_SUMMON_OBJECT_WILD:
case SPELL_EFFECT_SELF_RESURRECT:
case SPELL_EFFECT_REPUTATION:
case SPELL_EFFECT_LEARN_SPELL:
case SPELL_EFFECT_SEND_TAXI:
if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
// Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
else if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_TRIGGER_SPELL)
AddUnitTarget(m_caster, i);
break;
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
case SPELL_EFFECT_SUMMON_PLAYER:
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->GetSelection())
{
Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection());
if (target)
AddUnitTarget(target, i);
}
break;
case SPELL_EFFECT_RESURRECT_NEW:
if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
if (m_targets.GetCorpseTargetGUID())
{
Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID());
if (corpse)
{
Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
if (owner)
AddUnitTarget(owner, i);
}
}
break;
case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
case SPELL_EFFECT_ADD_FARSIGHT:
case SPELL_EFFECT_APPLY_GLYPH:
case SPELL_EFFECT_STUCK:
case SPELL_EFFECT_FEED_PET:
case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
case SPELL_EFFECT_KILL_CREDIT2: // only one spell: 42793
AddUnitTarget(m_caster, i);
break;
case SPELL_EFFECT_LEARN_PET_SPELL:
if (Guardian* pet = m_caster->GetGuardianPet())
AddUnitTarget(pet, i);
break;
case SPELL_EFFECT_APPLY_AURA:
switch(m_spellInfo->Effects[i].ApplyAuraName)
{
case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_UNIT_CASTER(1) (and present for other ranks for same spell for example)
case SPELL_AURA_ADD_PCT_MODIFIER:
AddUnitTarget(m_caster, i);
break;
default: // apply to target in other case
if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
break;
}
break;
case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
else if (m_targets.GetCorpseTargetGUID())
{
Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID());
if (corpse)
{
Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
if (owner)
AddUnitTarget(owner, i);
}
}
break;
default:
AddUnitTarget(m_caster, i);
break;
}
}
if (m_spellInfo->IsChanneled())
{
uint8 mask = (1<<i);
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->effectMask & mask)
{
m_channelTargetEffectMask |= mask;
break;
}
}
}
else if (m_auraScaleMask)
{
bool checkLvl = !m_UniqueTargetInfo.empty();
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();)
{
// remove targets which did not pass min level check
if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask)
{
// Do not check for selfcast
if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID())
{
m_UniqueTargetInfo.erase(ihit++);
continue;
}
}
++ihit;
}
if (checkLvl && m_UniqueTargetInfo.empty())
{
SendCastResult(SPELL_FAILED_LOWLEVEL);
finish(false);
}
}
}
if (m_targets.HasDst())
{
if (m_targets.HasTraj())
{
float speed = m_targets.GetSpeedXY();
if (speed > 0.0f)
m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f);
}
else if (m_spellInfo->Speed > 0.0f)
{
float dist = m_caster->GetDistance(*m_targets.GetDst());
m_delayMoment = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f);
}
}
}
void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/)
{
//==========================================================================================
// Now fill data for trigger system, need know:
// can spell trigger another or not (m_canTrigger)
// Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx)
//==========================================================================================
m_procVictim = m_procAttacker = 0;
// Get data for type of attack and fill base info for trigger
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS;
if (m_attackType == OFF_ATTACK)
m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK;
else
m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS;
break;
case SPELL_DAMAGE_CLASS_RANGED:
// Auto attack
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG)
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
else // Ranged spell attack
{
m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS;
m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS;
}
break;
default:
if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON &&
m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND)
&& m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
// For other spells trigger procflags are set in Spell::DoAllEffectOnTarget
// Because spell positivity is dependant on target
}
m_procEx = PROC_EX_NONE;
// Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER &&
(m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow
m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc
m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap
m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION;
/* Effects which are result of aura proc from triggered spell cannot proc
to prevent chain proc of these spells */
// Hellfire Effect - trigger as DOT
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040)
{
m_procAttacker = PROC_FLAG_DONE_PERIODIC;
m_procVictim = PROC_FLAG_TAKEN_PERIODIC;
}
// Ranged autorepeat attack is set as triggered spell - ignore it
if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK))
{
if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS &&
(m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC ||
m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2))
m_procEx |= PROC_EX_INTERNAL_CANT_PROC;
else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS)
m_procEx |= PROC_EX_INTERNAL_TRIGGERED;
}
// Totem casts require spellfamilymask defined in spell_proc_event to proc
if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isTotem() && m_caster->IsControlledByPlayer())
{
m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY;
}
}
void Spell::CleanupTargetList()
{
m_UniqueTargetInfo.clear();
m_UniqueGOTargetInfo.clear();
m_UniqueItemInfo.clear();
m_delayMoment = 0;
}
void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
{
if (!m_spellInfo->Effects[effIndex].IsEffect())
return;
if (!CheckTarget(pVictim, effIndex))
return;
// Check for effect immune skip if immuned
bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
uint64 targetGUID = pVictim->GetGUID();
// Lookup target in already in list
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
if (!immuned)
ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned
ihit->scaleAura = false;
if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != pVictim)
{
SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id));
if (uint32(pVictim->getLevel() + 10) >= auraSpell->SpellLevel)
ihit->scaleAura = true;
}
return;
}
}
// This is new target calculate data for him
// Get spell hit result on target
TargetInfo target;
target.targetGUID = targetGUID; // Store target GUID
target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned
target.processed = false; // Effects not apply on target
target.alive = pVictim->isAlive();
target.damage = 0;
target.crit = false;
target.scaleAura = false;
if (m_auraScaleMask && target.effectMask == m_auraScaleMask && m_caster != pVictim)
{
SpellInfo const* auraSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id));
if (uint32(pVictim->getLevel() + 10) >= auraSpell->SpellLevel)
target.scaleAura = true;
}
// Calculate hit result
if (m_originalCaster)
{
target.missCondition = m_originalCaster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
if (m_skipCheck && target.missCondition != SPELL_MISS_IMMUNE)
target.missCondition = SPELL_MISS_NONE;
}
else
target.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE;
// Spell have speed - need calculate incoming time
// Incoming time is zero for self casts. At least I think so.
if (m_spellInfo->Speed > 0.0f && m_caster != pVictim)
{
// calculate spell incoming interval
// TODO: this is a hack
float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
if (dist < 5.0f) dist = 5.0f;
target.timeDelay = (uint64) floor(dist / m_spellInfo->Speed * 1000.0f);
// Calculate minimum incoming time
if (m_delayMoment == 0 || m_delayMoment>target.timeDelay)
m_delayMoment = target.timeDelay;
}
else
target.timeDelay = 0LL;
// If target reflect spell back to caster
if (target.missCondition == SPELL_MISS_REFLECT)
{
// Calculate reflected spell result on caster
target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
target.reflectResult = SPELL_MISS_PARRY;
// Increase time interval for reflected spells by 1.5
target.timeDelay += target.timeDelay >> 1;
}
else
target.reflectResult = SPELL_MISS_NONE;
// Add target to list
m_UniqueTargetInfo.push_back(target);
}
void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
{
if (Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID))
AddUnitTarget(unit, effIndex);
}
void Spell::AddGOTarget(GameObject* go, uint32 effIndex)
{
if (!m_spellInfo->Effects[effIndex].IsEffect())
return;
switch (m_spellInfo->Effects[effIndex].Effect)
{
case SPELL_EFFECT_GAMEOBJECT_DAMAGE:
case SPELL_EFFECT_GAMEOBJECT_REPAIR:
case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE:
if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING)
return;
break;
default:
break;
}
uint64 targetGUID = go->GetGUID();
// Lookup target in already in list
for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
ihit->effectMask |= 1 << effIndex; // Add only effect mask
return;
}
}
// This is new target calculate data for him
GOTargetInfo target;
target.targetGUID = targetGUID;
target.effectMask = 1 << effIndex;
target.processed = false; // Effects not apply on target
// Spell have speed - need calculate incoming time
if (m_spellInfo->Speed > 0.0f)
{
// calculate spell incoming interval
float dist = m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ());
if (dist < 5.0f)
dist = 5.0f;
target.timeDelay = uint64(floor(dist / m_spellInfo->Speed * 1000.0f));
if (m_delayMoment == 0 || m_delayMoment > target.timeDelay)
m_delayMoment = target.timeDelay;
}
else
target.timeDelay = 0LL;
// Add target to list
m_UniqueGOTargetInfo.push_back(target);
}
void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
{
if (GameObject* go = m_caster->GetMap()->GetGameObject(goGUID))
AddGOTarget(go, effIndex);
}
void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
{
if (!m_spellInfo->Effects[effIndex].IsEffect())
return;
// Lookup target in already in list
for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
if (pitem == ihit->item) // Found in list
{
ihit->effectMask |= 1 << effIndex; // Add only effect mask
return;
}
// This is new target add data
ItemTargetInfo target;
target.item = pitem;
target.effectMask = 1 << effIndex;
m_UniqueItemInfo.push_back(target);
}
void Spell::DoAllEffectOnTarget(TargetInfo *target)
{
if (!target || target->processed)
return;
target->processed = true; // Target checked in apply effects procedure
// Get mask of effects for target
uint8 mask = target->effectMask;
Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
if (!unit)
{
uint8 farMask = 0;
// create far target mask
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].IsFarUnitTargetEffect())
if ((1 << i) & mask)
farMask |= (1 << i);
if (!farMask)
return;
// find unit in world
unit = ObjectAccessor::FindUnit(target->targetGUID);
if (!unit)
return;
// do far effects on the unit
// can't use default call because of threading, do stuff as fast as possible
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (farMask & (1 << i))
HandleEffects(unit, NULL, NULL, i);
return;
}
if (unit->isAlive() != target->alive)
return;
if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime)
return; // No missinfo in that case
// Get original caster (if exist) and calculate damage/healing from him data
Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
// Skip if m_originalCaster not avaiable
if (!caster)
return;
SpellMissInfo missInfo = target->missCondition;
// Need init unitTarget by default unit (can changed in code on reflect)
// Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
unitTarget = unit;
// Reset damage/healing counter
m_damage = target->damage;
m_healing = -target->damage;
// Fill base trigger info
uint32 procAttacker = m_procAttacker;
uint32 procVictim = m_procVictim;
uint32 procEx = m_procEx;
m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied
//Spells with this flag cannot trigger if effect is casted on self
// Slice and Dice, relentless strikes, eviscerate
bool canEffectTrigger = !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && CanExecuteTriggersOnHit(mask);
Unit* spellHitTarget = NULL;
if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
spellHitTarget = unit;
else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
{
if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
{
spellHitTarget = m_caster;
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_caster->ToCreature()->LowerPlayerDamageReq(target->damage);
}
}
if (spellHitTarget)
{
SpellMissInfo missInfo = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura);
if (missInfo != SPELL_MISS_NONE)
{
if (missInfo != SPELL_MISS_MISS)
m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo);
m_damage = 0;
spellHitTarget = NULL;
}
}
// Do not take combo points on dodge and miss
if (m_needComboPoints && m_targets.GetUnitTargetGUID() == target->targetGUID)
if (missInfo != SPELL_MISS_NONE)
{
m_needComboPoints = false;
// Restore spell mods for a miss/dodge/parry Cold Blood
// TODO: check how broad this rule should be
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if ((missInfo == SPELL_MISS_MISS) ||
(missInfo == SPELL_MISS_DODGE) ||
(missInfo == SPELL_MISS_PARRY))
m_caster->ToPlayer()->RestoreSpellMods(this, 14177);
}
// Trigger info was not filled in spell::preparedatafortriggersystem - we do it now
if (canEffectTrigger && !procAttacker && !procVictim)
{
bool positive = true;
if (m_damage > 0)
positive = false;
else if (!m_healing)
{
for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
// If at least one effect negative spell is negative hit
if (mask & (1<<i) && !m_spellInfo->IsPositiveEffect(i))
{
positive = false;
break;
}
}
switch(m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG;
}
break;
case SPELL_DAMAGE_CLASS_NONE:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG;
}
break;
}
}
CallScriptOnHitHandlers();
// All calculated do it!
// Do healing and triggers
if (m_healing > 0)
{
bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask);
uint32 addhealth = m_healing;
if (crit)
{
procEx |= PROC_EX_CRITICAL_HIT;
addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
}
else
procEx |= PROC_EX_NORMAL_HIT;
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit);
unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
}
// Do damage and triggers
else if (m_damage > 0)
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
// Add bonuses and fill damageInfo struct
caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit);
caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
// Send log damage message to client
caster->SendSpellNonMeleeDamageLog(&damageInfo);
procEx |= createProcExtendMask(&damageInfo, missInfo);
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
{
caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 &&
(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx);
}
caster->DealSpellDamage(&damageInfo, true);
// Haunt
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1))
{
AuraEffect * aurEff = m_spellAura->GetEffect(1);
aurEff->SetAmount(CalculatePctU(aurEff->GetAmount(), damageInfo.damage));
}
}
// Passive spell hits/misses or active spells only misses (only triggers)
else
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
procEx |= createProcExtendMask(&damageInfo, missInfo);
// Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
// Failed Pickpocket, reveal rogue
if (missInfo == SPELL_MISS_RESIST && m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
if (unitTarget->ToCreature()->IsAIEnabled)
unitTarget->ToCreature()->AI()->AttackStart(m_caster);
}
}
if (missInfo != SPELL_MISS_EVADE && m_caster && !m_caster->IsFriendlyTo(unit) && !m_spellInfo->IsPositive())
{
m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO));
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC)
if (!unit->IsStandState())
unit->SetStandState(UNIT_STAND_STATE_STAND);
}
if (spellHitTarget)
{
//AI functions
if (spellHitTarget->GetTypeId() == TYPEID_UNIT)
{
if (spellHitTarget->ToCreature()->IsAIEnabled)
spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo);
// cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
// ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm...)
if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !spellHitTarget->ToCreature()->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive())
if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
p->CastedCreatureOrGO(spellHitTarget->GetEntry(), spellHitTarget->GetGUID(), m_spellInfo->Id);
}
if (m_caster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled)
m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo);
// Needs to be called after dealing damage/healing to not remove breaking on damage auras
DoTriggersOnSpellHit(spellHitTarget, mask);
// if target is fallged for pvp also flag caster if a player
if (unit->IsPvP())
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->UpdatePvP(true);
}
CallScriptAfterHitHandlers();
}
}
SpellMissInfo Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask, bool scaleAura)
{
if (!unit || !effectMask)
return SPELL_MISS_EVADE;
// Recheck immune (only for delayed spells)
if (m_spellInfo->Speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))
return SPELL_MISS_IMMUNE;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
if (unit->GetTypeId() == TYPEID_PLAYER)
{
unit->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id);
unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, m_caster);
unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
}
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id);
m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
}
if (m_caster != unit)
{
// Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
if (m_spellInfo->Speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
return SPELL_MISS_EVADE;
// check for IsHostileTo() instead of !IsFriendlyTo()
// ex: spell 47463 needs to be casted by different units on the same neutral target
if (m_caster->IsHostileTo(unit))
{
unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
//TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer())
unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH);
}
else if (m_caster->IsFriendlyTo(unit))
{
// for delayed spells ignore negative spells (after duel end) for friendly targets
// TODO: this cause soul transfer bugged
if (m_spellInfo->Speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive())
return SPELL_MISS_EVADE;
// assisting case, healing and resurrection
if (unit->HasUnitState(UNIT_STAT_ATTACK_PLAYER))
{
m_caster->SetContestedPvP();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->UpdatePvP(true);
}
if (unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO))
{
m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit);
unit->getHostileRefManager().threatAssist(m_caster, 0.0f);
}
}
}
// Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo, m_triggeredByAuraSpell);
if (m_diminishGroup)
{
m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup);
// Increase Diminishing on unit, current informations for actually casts will use values above
if ((type == DRTYPE_PLAYER && unit->GetCharmerOrOwnerPlayerOrPlayerItself()) || type == DRTYPE_ALL)
unit->IncrDiminishing(m_diminishGroup);
}
uint8 aura_effmask = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (effectMask & (1 <<i ) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect())
aura_effmask |= 1 << i;
if (aura_effmask)
{
// Select rank for aura with level requirements only in specific cases
// Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target
SpellInfo const* aurSpellInfo = m_spellInfo;
int32 basePoints[3];
if (scaleAura)
{
aurSpellInfo = m_spellInfo->GetAuraRankForLevel(unitTarget->getLevel());
ASSERT(aurSpellInfo);
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
basePoints[i] = aurSpellInfo->Effects[i].BasePoints;
if (m_spellInfo->Effects[i].Effect != aurSpellInfo->Effects[i].Effect)
{
aurSpellInfo = m_spellInfo;
break;
}
}
}
if (m_originalCaster)
{
bool refresh = false;
m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit,
m_originalCaster, (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh);
if (m_spellAura)
{
// Set aura stack amount to desired value
if (m_spellValue->AuraStackAmount > 1)
{
if (!refresh)
m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount);
else
m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount);
}
// Now Reduce spell duration using data received at spell hit
int32 duration = m_spellAura->GetMaxDuration();
int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup, aurSpellInfo);
float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel, limitduration);
// unit is immune to aura if it was diminished to 0 duration
if (diminishMod == 0.0f)
{
m_spellAura->Remove();
return SPELL_MISS_IMMUNE;
}
((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup);
bool positive = m_spellAura->GetSpellInfo()->IsPositive();
AuraApplication * aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID());
if (aurApp)
positive = aurApp->IsPositive();
duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive);
// Haste modifies duration of channeled spells
if (m_spellInfo->IsChanneled())
{
if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this);
}
// and duration of auras affected by SPELL_AURA_PERIODIC_HASTE
else if (m_originalCaster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, aurSpellInfo) || m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
duration = int32(duration * m_originalCaster->GetFloatValue(UNIT_MOD_CAST_SPEED));
if (duration != m_spellAura->GetMaxDuration())
{
m_spellAura->SetMaxDuration(duration);
m_spellAura->SetDuration(duration);
}
m_spellAura->_RegisterForTargets();
}
}
}
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(unit, NULL, NULL, effectNumber);
return SPELL_MISS_NONE;
}
void Spell::DoTriggersOnSpellHit(Unit *unit, uint8 effMask)
{
// Apply additional spell effects to target
// TODO: move this code to scripts
if (m_preCastSpell)
{
// Paladin immunity shields
if (m_preCastSpell == 61988)
{
// Cast Forbearance
m_caster->CastSpell(unit, 25771, true);
// Cast Avenging Wrath Marker
unit->CastSpell(unit, 61987, true);
}
// Avenging Wrath
if (m_preCastSpell == 61987)
// Cast the serverside immunity shield marker
m_caster->CastSpell(unit, 61988, true);
if (sSpellMgr->GetSpellInfo(m_preCastSpell))
// Blizz seems to just apply aura without bothering to cast
m_caster->AddAura(m_preCastSpell, unit);
}
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras
// this is executed after spell proc spells on target hit
// spells are triggered for each hit spell target
// info confirmed with retail sniffs of permafrost and shadow weaving
if (!m_hitTriggerSpells.empty() && CanExecuteTriggersOnHit(effMask))
{
int _duration = 0;
for (HitTriggerSpells::const_iterator i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i)
{
if (roll_chance_i(i->second))
{
m_caster->CastSpell(unit, i->first, true);
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id);
// SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration
// set duration of current aura to the triggered spell
if (i->first->GetDuration() == -1)
{
if (Aura * triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID()))
{
// get duration from aura-only once
if (!_duration)
{
Aura * aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID());
_duration = aur ? aur->GetDuration() : -1;
}
triggeredAur->SetDuration(_duration);
}
}
}
}
}
// trigger linked auras remove/apply
// TODO: remove/cleanup this, as this table is not documented and people are doing stupid things with it
if (std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT))
for (std::vector<int32>::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i)
if (*i < 0)
unit->RemoveAurasDueToSpell(-(*i));
else
unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID());
}
void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
{
if (target->processed) // Check target
return;
target->processed = true; // Target checked in apply effects procedure
uint32 effectMask = target->effectMask;
if (!effectMask)
return;
GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
if (!go)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(NULL, NULL, go, effectNumber);
CallScriptOnHitHandlers();
// cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
// ignore autorepeat/melee casts for speed (not exist quest for spells (hm...)
if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive())
if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
CallScriptAfterHitHandlers();
}
void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
{
uint32 effectMask = target->effectMask;
if (!target->item || !effectMask)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers();
for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber)
if (effectMask & (1 << effectNumber))
HandleEffects(NULL, target->item, NULL, effectNumber);
CallScriptOnHitHandlers();
CallScriptAfterHitHandlers();
}
bool Spell::UpdateChanneledTargetList()
{
// Not need check return true
if (m_channelTargetEffectMask == 0)
return true;
uint8 channelTargetEffectMask = m_channelTargetEffectMask;
uint8 channelAuraMask = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA)
channelAuraMask |= 1<<i;
channelAuraMask &= channelTargetEffectMask;
float range = 0;
if (channelAuraMask)
{
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive());
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
}
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask))
{
Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
if (!unit)
continue;
if (IsValidDeadOrAliveTarget(unit))
{
if (channelAuraMask & ihit->effectMask)
{
if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID))
{
if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range))
{
ihit->effectMask &= ~aurApp->GetEffectMask();
unit->RemoveAura(aurApp);
continue;
}
}
else // aura is dispelled
continue;
}
channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
}
}
}
// is all effects from m_needAliveTargetMask have alive targets
return channelTargetEffectMask == 0;
}
// Helper for Chain Healing
// Spell target first
// Raidmates then descending by injury suffered (MaxHealth - Health)
// Other players/mobs then descending by injury suffered (MaxHealth - Health)
struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
{
const Unit* MainTarget;
ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
// functor for operator ">"
bool operator()(Unit const* _Left, Unit const* _Right) const
{
return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
}
int32 ChainHealingHash(Unit const* Target) const
{
if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER && Target->ToPlayer()->IsInSameRaidWith(MainTarget->ToPlayer()))
{
if (Target->IsFullHealth())
return 40000;
else
return 20000 - Target->GetMaxHealth() + Target->GetHealth();
}
else
return 40000 - Target->GetMaxHealth() + Target->GetHealth();
}
};
void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, float max_range, uint32 num, SpellTargets TargetType)
{
Unit *cur = m_targets.GetUnitTarget();
if (!cur)
return;
//FIXME: This very like horrible hack and wrong for most spells
if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
max_range += num * CHAIN_SPELL_JUMP_RADIUS;
std::list<Unit*> tempUnitMap;
if (TargetType == SPELL_TARGETS_CHAINHEAL)
{
SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, SPELL_TARGETS_ALLY);
tempUnitMap.sort(ChainHealingOrder(m_caster));
}
else
SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, TargetType);
tempUnitMap.remove(cur);
while (num)
{
TagUnitMap.push_back(cur);
--num;
if (tempUnitMap.empty())
break;
std::list<Unit*>::iterator next;
if (TargetType == SPELL_TARGETS_CHAINHEAL)
{
next = tempUnitMap.begin();
while (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS || !cur->IsWithinLOSInMap(*next))
{
++next;
if (next == tempUnitMap.end())
return;
}
}
else
{
tempUnitMap.sort(Trinity::ObjectDistanceOrderPred(cur));
next = tempUnitMap.begin();
if (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) // Don't search beyond the max jump radius
break;
// Check if (*next) is a valid chain target. If not, don't add to TagUnitMap, and repeat loop.
// If you want to add any conditions to exclude a target from TagUnitMap, add condition in this while() loop.
while ((m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE
&& !m_caster->isInFrontInMap(*next, max_range))
|| !m_caster->canSeeOrDetect(*next)
|| !cur->IsWithinLOSInMap(*next)
|| ((GetSpellInfo()->AttributesEx6 & SPELL_ATTR6_IGNORE_CROWD_CONTROL_TARGETS) && !(*next)->CanFreeMove()))
{
++next;
if (next == tempUnitMap.end() || cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) // Don't search beyond the max jump radius
return;
}
}
cur = *next;
tempUnitMap.erase(next);
}
}
void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry)
{
if (TargetType == SPELL_TARGETS_GO)
return;
Position const* pos;
switch(type)
{
case PUSH_DST_CENTER:
CheckDst();
pos = m_targets.GetDst();
break;
case PUSH_SRC_CENTER:
CheckSrc();
pos = m_targets.GetSrc();
break;
case PUSH_CHAIN:
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
{
sLog->outError("SPELL: cannot find unit target for spell ID %u\n", m_spellInfo->Id);
return;
}
pos = target;
break;
}
default:
pos = m_caster;
break;
}
Trinity::SpellNotifierCreatureAndPlayer notifier(m_caster, TagUnitMap, radius, type, TargetType, pos, entry, m_spellInfo);
if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_PLAYERS_ONLY) || (TargetType == SPELL_TARGETS_ENTRY && !entry))
{
m_caster->GetMap()->VisitWorld(pos->m_positionX, pos->m_positionY, radius, notifier);
TagUnitMap.remove_if(Trinity::ObjectTypeIdCheck(TYPEID_PLAYER, false)); // above line will select also pets and totems, remove them
}
else
m_caster->GetMap()->VisitAll(pos->m_positionX, pos->m_positionY, radius, notifier);
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_EXCLUDE_SELF)
TagUnitMap.remove(m_caster);
}
void Spell::SearchGOAreaTarget(std::list<GameObject*> &TagGOMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry)
{
if (TargetType != SPELL_TARGETS_GO)
return;
Position const* pos;
switch (type)
{
case PUSH_DST_CENTER:
CheckDst();
pos = m_targets.GetDst();
break;
case PUSH_SRC_CENTER:
CheckSrc();
pos = m_targets.GetSrc();
break;
default:
pos = m_caster;
break;
}
Trinity::GameObjectInRangeCheck check(pos->m_positionX, pos->m_positionY, pos->m_positionZ, radius, entry);
Trinity::GameObjectListSearcher<Trinity::GameObjectInRangeCheck> searcher(m_caster, TagGOMap, check);
m_caster->GetMap()->VisitGrid(pos->m_positionX, pos->m_positionY, radius, searcher);
}
WorldObject* Spell::SearchNearbyTarget(float range, SpellTargets TargetType, SpellEffIndex effIndex)
{
switch(TargetType)
{
case SPELL_TARGETS_ENTRY:
{
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id);
if (conditions.empty())
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) does not have record in `conditions` for spell script target (ConditionSourceType 13)", m_spellInfo->Id, m_caster->GetEntry());
if (m_spellInfo->IsPositive())
return SearchNearbyTarget(range, SPELL_TARGETS_ALLY, effIndex);
else
return SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, effIndex);
}
Creature* creatureScriptTarget = NULL;
GameObject* goScriptTarget = NULL;
for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST)
{
if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET)
continue;
if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1 << uint32(effIndex))))
continue;
switch((*i_spellST)->mConditionValue1)
{
case SPELL_TARGET_TYPE_CONTROLLED:
for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
if ((*itr)->GetEntry() == (*i_spellST)->mConditionValue2 && (*itr)->IsWithinDistInMap(m_caster, range))
{
goScriptTarget = NULL;
creatureScriptTarget = (*itr)->ToCreature();
range = m_caster->GetDistance(creatureScriptTarget);
}
break;
case SPELL_TARGET_TYPE_GAMEOBJECT:
if ((*i_spellST)->mConditionValue2)
{
if (GameObject *go = m_caster->FindNearestGameObject((*i_spellST)->mConditionValue2, range))
{
// remember found target and range, next attempt will find more near target with another entry
goScriptTarget = go;
creatureScriptTarget = NULL;
range = m_caster->GetDistance(goScriptTarget);
}
}
else if (focusObject) //Focus Object
{
float frange = m_caster->GetDistance(focusObject);
if (range >= frange)
{
creatureScriptTarget = NULL;
goScriptTarget = focusObject;
range = frange;
}
}
break;
case SPELL_TARGET_TYPE_CREATURE:
if (m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetEntry() == (*i_spellST)->mConditionValue2)
return m_targets.GetUnitTarget();
case SPELL_TARGET_TYPE_DEAD:
default:
if (Creature *cre = m_caster->FindNearestCreature((*i_spellST)->mConditionValue2, range, (*i_spellST)->mConditionValue1 != SPELL_TARGET_TYPE_DEAD))
{
creatureScriptTarget = cre;
goScriptTarget = NULL;
range = m_caster->GetDistance(creatureScriptTarget);
}
break;
}
}
if (creatureScriptTarget)
return creatureScriptTarget;
else
return goScriptTarget;
}
default:
case SPELL_TARGETS_ENEMY:
{
Unit* target = NULL;
Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
m_caster->VisitNearbyObject(range, searcher);
return target;
}
case SPELL_TARGETS_ALLY:
{
Unit* target = NULL;
Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
m_caster->VisitNearbyObject(range, searcher);
return target;
}
}
}
void Spell::SelectEffectTargets(uint32 i, SpellImplicitTargetInfo const& cur)
{
SpellNotifyPushType pushType = PUSH_NONE;
Player *modOwner = NULL;
if (m_originalCaster)
modOwner = m_originalCaster->GetSpellModOwner();
switch(cur.GetType())
{
case TARGET_TYPE_UNIT_CASTER:
{
switch(cur.GetTarget())
{
case TARGET_UNIT_CASTER:
AddUnitTarget(m_caster, i);
break;
case TARGET_UNIT_CASTER_FISHING:
{
float min_dis = m_spellInfo->GetMinRange(true);
float max_dis = m_spellInfo->GetMaxRange(true);
float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis;
float x, y, z;
m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis);
m_targets.SetDst(x, y, z, m_caster->GetOrientation());
break;
}
case TARGET_UNIT_MASTER:
if (Unit* owner = m_caster->GetCharmerOrOwner())
AddUnitTarget(owner, i);
break;
case TARGET_UNIT_PET:
if (Guardian* pet = m_caster->GetGuardianPet())
AddUnitTarget(pet, i);
break;
case TARGET_UNIT_SUMMONER:
if (m_caster->isSummon())
if (Unit* unit = m_caster->ToTempSummon()->GetSummoner())
AddUnitTarget(unit, i);
break;
case TARGET_UNIT_PARTY_CASTER:
case TARGET_UNIT_RAID_CASTER:
pushType = PUSH_CASTER_CENTER;
break;
case TARGET_UNIT_VEHICLE:
if (Unit *vehicle = m_caster->GetVehicleBase())
AddUnitTarget(vehicle, i);
break;
case TARGET_UNIT_PASSENGER_0:
case TARGET_UNIT_PASSENGER_1:
case TARGET_UNIT_PASSENGER_2:
case TARGET_UNIT_PASSENGER_3:
case TARGET_UNIT_PASSENGER_4:
case TARGET_UNIT_PASSENGER_5:
case TARGET_UNIT_PASSENGER_6:
case TARGET_UNIT_PASSENGER_7:
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle())
if (Unit *unit = m_caster->GetVehicleKit()->GetPassenger(cur.GetTarget() - TARGET_UNIT_PASSENGER_0))
AddUnitTarget(unit, i);
break;
default:
break;
}
break;
}
case TARGET_TYPE_UNIT_TARGET:
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
{
sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id);
break;
}
switch(cur.GetTarget())
{
case TARGET_UNIT_TARGET_ENEMY:
if (Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
if (magnet != target)
m_targets.SetUnitTarget(magnet);
pushType = PUSH_CHAIN;
break;
case TARGET_UNIT_TARGET_ANY:
if (!m_spellInfo->IsPositive())
if (Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
if (magnet != target)
m_targets.SetUnitTarget(magnet);
pushType = PUSH_CHAIN;
break;
case TARGET_UNIT_CHAINHEAL:
pushType = PUSH_CHAIN;
break;
case TARGET_UNIT_TARGET_ALLY:
AddUnitTarget(target, i);
break;
case TARGET_UNIT_TARGET_RAID:
case TARGET_UNIT_TARGET_PARTY:
case TARGET_UNIT_TARGET_MINIPET:
if (IsValidSingleTargetSpell(target))
AddUnitTarget(target, i);
break;
case TARGET_UNIT_TARGET_PASSENGER:
if (target->IsOnVehicle(m_caster))
AddUnitTarget(target, i);
break;
case TARGET_UNIT_TARGET_ALLY_PARTY:
case TARGET_UNIT_TARGET_CLASS_RAID:
pushType = PUSH_CASTER_CENTER; // not real
break;
default:
break;
}
break;
}
case TARGET_TYPE_UNIT_NEARBY:
{
WorldObject *target = NULL;
float range;
switch(cur.GetTarget())
{
case TARGET_UNIT_NEARBY_ENEMY:
range = m_spellInfo->GetMaxRange(false);
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
target = SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, SpellEffIndex(i));
break;
case TARGET_UNIT_NEARBY_ALLY:
case TARGET_UNIT_NEARBY_PARTY: // TODO: fix party/raid targets
case TARGET_UNIT_NEARBY_RAID:
range = m_spellInfo->GetMaxRange(true);
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
target = SearchNearbyTarget(range, SPELL_TARGETS_ALLY, SpellEffIndex(i));
break;
case TARGET_UNIT_NEARBY_ENTRY:
case TARGET_GAMEOBJECT_NEARBY_ENTRY:
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive());
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i));
break;
default:
break;
}
if (!target)
return;
else if (target->GetTypeId() == TYPEID_GAMEOBJECT)
AddGOTarget((GameObject*)target, i);
else
{
pushType = PUSH_CHAIN;
if (m_targets.GetUnitTarget() != target)
m_targets.SetUnitTarget((Unit*)target);
}
break;
}
case TARGET_TYPE_AREA_SRC:
pushType = PUSH_SRC_CENTER;
break;
case TARGET_TYPE_AREA_DST:
pushType = PUSH_DST_CENTER;
break;
case TARGET_TYPE_AREA_CONE:
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_BACK)
pushType = PUSH_IN_BACK;
else if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_CONE_LINE)
pushType = PUSH_IN_LINE;
else
pushType = PUSH_IN_FRONT;
break;
case TARGET_TYPE_DEST_CASTER: //4+8+2
{
if (cur.GetTarget() == TARGET_SRC_CASTER)
{
m_targets.SetSrc(*m_caster);
break;
}
else if (cur.GetTarget() == TARGET_DST_CASTER)
{
m_targets.SetDst(*m_caster);
break;
}
float angle, dist;
float objSize = m_caster->GetObjectSize();
if (cur.GetTarget() == TARGET_MINION)
dist = 0.0f;
else
dist = m_spellInfo->Effects[i].CalcRadius(m_caster);
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, dist, this);
if (dist < objSize)
dist = objSize;
else if (cur.GetTarget() == TARGET_DEST_CASTER_RANDOM)
dist = objSize + (dist - objSize) * (float)rand_norm();
switch(cur.GetTarget())
{
case TARGET_DEST_CASTER_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break;
case TARGET_DEST_CASTER_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break;
case TARGET_DEST_CASTER_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break;
case TARGET_DEST_CASTER_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break;
case TARGET_MINION:
case TARGET_DEST_CASTER_FRONT_LEAP:
case TARGET_DEST_CASTER_FRONT: angle = 0.0f; break;
case TARGET_DEST_CASTER_BACK: angle = static_cast<float>(M_PI); break;
case TARGET_DEST_CASTER_RIGHT: angle = static_cast<float>(-M_PI/2); break;
case TARGET_DEST_CASTER_LEFT: angle = static_cast<float>(M_PI/2); break;
default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break;
}
Position pos;
if (cur.GetTarget() == TARGET_DEST_CASTER_FRONT_LEAP)
m_caster->GetFirstCollisionPosition(pos, dist, angle);
else
m_caster->GetNearPosition(pos, dist, angle);
m_targets.SetDst(*m_caster);
m_targets.ModDst(pos);
break;
}
case TARGET_TYPE_DEST_TARGET: //2+8+2
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
{
sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id);
break;
}
if (cur.GetTarget() == TARGET_DST_TARGET_ENEMY || cur.GetTarget() == TARGET_DEST_TARGET_ANY)
{
m_targets.SetDst(*target);
break;
}
float angle, dist;
float objSize = target->GetObjectSize();
dist = m_spellInfo->Effects[i].CalcRadius(m_caster);
if (dist < objSize)
dist = objSize;
else if (cur.GetTarget() == TARGET_DEST_TARGET_RANDOM)
dist = objSize + (dist - objSize) * (float)rand_norm();
switch(cur.GetTarget())
{
case TARGET_DEST_TARGET_FRONT: angle = 0.0f; break;
case TARGET_DEST_TARGET_BACK: angle = static_cast<float>(M_PI); break;
case TARGET_DEST_TARGET_RIGHT: angle = static_cast<float>(M_PI/2); break;
case TARGET_DEST_TARGET_LEFT: angle = static_cast<float>(-M_PI/2); break;
case TARGET_DEST_TARGET_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break;
case TARGET_DEST_TARGET_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break;
case TARGET_DEST_TARGET_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break;
case TARGET_DEST_TARGET_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break;
default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break;
}
Position pos;
target->GetNearPosition(pos, dist, angle);
m_targets.SetDst(*target);
m_targets.ModDst(pos);
break;
}
case TARGET_TYPE_DEST_DEST: //5+8+1
{
if (!m_targets.HasDst())
{
sLog->outError("SPELL: no destination for spell ID %u", m_spellInfo->Id);
break;
}
float angle;
switch(cur.GetTarget())
{
case TARGET_DEST_DYNOBJ_ENEMY:
case TARGET_DEST_DYNOBJ_ALLY:
case TARGET_DEST_DYNOBJ_NONE:
case TARGET_DEST_DEST:
return;
case TARGET_DEST_TRAJ:
SelectTrajTargets();
return;
case TARGET_DEST_DEST_FRONT: angle = 0.0f; break;
case TARGET_DEST_DEST_BACK: angle = static_cast<float>(M_PI); break;
case TARGET_DEST_DEST_RIGHT: angle = static_cast<float>(M_PI/2); break;
case TARGET_DEST_DEST_LEFT: angle = static_cast<float>(-M_PI/2); break;
case TARGET_DEST_DEST_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break;
case TARGET_DEST_DEST_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break;
case TARGET_DEST_DEST_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break;
case TARGET_DEST_DEST_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break;
default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break;
}
float dist = m_spellInfo->Effects[i].CalcRadius(m_caster);
if (cur.GetTarget() == TARGET_DEST_DEST_RANDOM || cur.GetTarget() == TARGET_DEST_DEST_RANDOM_DIR_DIST)
dist *= (float)rand_norm();
// must has dst, no need to set flag
Position pos = *m_targets.GetDst();
m_caster->MovePosition(pos, dist, angle);
m_targets.ModDst(pos);
break;
}
case TARGET_TYPE_DEST_SPECIAL:
{
switch(cur.GetTarget())
{
case TARGET_DST_DB:
if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id))
{
//TODO: fix this check
if (m_spellInfo->Effects[0].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[1].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[2].Effect == SPELL_EFFECT_TELEPORT_UNITS)
m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId);
else if (st->target_mapId == m_caster->GetMapId())
m_targets.SetDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation);
}
else
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id);
Unit* target = NULL;
if (uint64 guid = m_caster->GetUInt64Value(UNIT_FIELD_TARGET))
target = ObjectAccessor::GetUnit(*m_caster, guid);
m_targets.SetDst(target ? *target : *m_caster);
}
break;
case TARGET_DST_HOME:
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_targets.SetDst(m_caster->ToPlayer()->m_homebindX, m_caster->ToPlayer()->m_homebindY, m_caster->ToPlayer()->m_homebindZ, m_caster->ToPlayer()->GetOrientation(), m_caster->ToPlayer()->m_homebindMapId);
break;
case TARGET_DST_NEARBY_ENTRY:
{
float range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive());
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
if (WorldObject *target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i)))
m_targets.SetDst(*target);
break;
}
default:
break;
}
break;
}
case TARGET_TYPE_CHANNEL:
{
if (!m_originalCaster || !m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: no current channeled spell for spell ID %u - spell triggering this spell was interrupted.", m_spellInfo->Id);
break;
}
switch (cur.GetTarget())
{
case TARGET_UNIT_CHANNEL_TARGET:
// unit target may be no longer avalible - teleported out of map for example
if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.GetUnitTargetGUID()))
AddUnitTarget(target, i);
else
sLog->outError("SPELL: cannot find channel spell target for spell ID %u", m_spellInfo->Id);
break;
case TARGET_DEST_CHANNEL_TARGET:
if (m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.HasDst())
m_targets.SetDst(m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets);
else if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.GetUnitTargetGUID()))
m_targets.SetDst(*target);
else
sLog->outError("SPELL: cannot find channel spell destination for spell ID %u", m_spellInfo->Id);
break;
case TARGET_DEST_CHANNEL_CASTER:
m_targets.SetDst(*m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->GetCaster());
break;
default:
break;
}
break;
}
default:
{
switch (cur.GetTarget())
{
case TARGET_GAMEOBJECT:
if (m_targets.GetGOTarget())
AddGOTarget(m_targets.GetGOTarget(), i);
break;
case TARGET_GAMEOBJECT_ITEM:
if (m_targets.GetGOTargetGUID())
AddGOTarget(m_targets.GetGOTarget(), i);
else if (m_targets.GetItemTarget())
AddItemTarget(m_targets.GetItemTarget(), i);
break;
default:
sLog->outError("SPELL (caster[type: %u; guidlow: %u], spell: %u): unhandled spell target (%u)",
m_caster->GetTypeId(), m_caster->GetGUIDLow(), m_spellInfo->Id, cur.GetTarget());
break;
}
break;
}
}
if (pushType == PUSH_CHAIN) // Chain
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
{
sLog->outError("SPELL: no chain unit target for spell ID %u", m_spellInfo->Id);
return;
}
//Chain: 2, 6, 22, 25, 45, 77
uint32 maxTargets = m_spellInfo->Effects[i].ChainTarget;
if (modOwner)
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this);
if (maxTargets > 1)
{
//otherwise, this multiplier is used for something else
m_damageMultipliers[i] = 1.0f;
m_applyMultiplierMask |= 1 << i;
float range;
std::list<Unit*> unitList;
switch (cur.GetTarget())
{
case TARGET_UNIT_NEARBY_ENEMY:
case TARGET_UNIT_TARGET_ENEMY:
case TARGET_UNIT_NEARBY_ENTRY: // fix me
range = m_spellInfo->GetMaxRange(false);
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_ENEMY);
break;
case TARGET_UNIT_CHAINHEAL:
case TARGET_UNIT_NEARBY_ALLY: // fix me
case TARGET_UNIT_NEARBY_PARTY:
case TARGET_UNIT_NEARBY_RAID:
range = m_spellInfo->GetMaxRange(true);
if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_CHAINHEAL);
break;
default:
break;
}
CallScriptAfterUnitTargetSelectHandlers(unitList, SpellEffIndex(i));
for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
AddUnitTarget(*itr, i);
}
else
AddUnitTarget(target, i);
}
else if (pushType)
{
// Dummy, just for client
if (m_spellInfo->Effects[i].GetRequiredTargetType() != SPELL_REQUIRE_UNIT)
return;
float radius;
SpellTargets targetType;
switch(cur.GetTarget())
{
case TARGET_UNIT_AREA_ENEMY_SRC:
case TARGET_UNIT_AREA_ENEMY_DST:
case TARGET_UNIT_CONE_ENEMY:
case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
case TARGET_UNIT_AREA_PATH:
radius = m_spellInfo->Effects[i].CalcRadius();
targetType = SPELL_TARGETS_ENEMY;
break;
case TARGET_UNIT_AREA_ALLY_SRC:
case TARGET_UNIT_AREA_ALLY_DST:
case TARGET_UNIT_CONE_ALLY:
radius = m_spellInfo->Effects[i].CalcRadius();
targetType = SPELL_TARGETS_ALLY;
break;
case TARGET_UNIT_AREA_ENTRY_DST:
case TARGET_UNIT_AREA_ENTRY_SRC:
case TARGET_UNIT_CONE_ENTRY: // fix me
radius = m_spellInfo->Effects[i].CalcRadius();
targetType = SPELL_TARGETS_ENTRY;
break;
case TARGET_GAMEOBJECT_AREA_SRC:
case TARGET_GAMEOBJECT_AREA_DST:
case TARGET_GAMEOBJECT_AREA_PATH:
radius = m_spellInfo->Effects[i].CalcRadius();
targetType = SPELL_TARGETS_GO;
break;
default:
radius = m_spellInfo->Effects[i].CalcRadius();
targetType = SPELL_TARGETS_NONE;
break;
}
if (modOwner)
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this);
radius *= m_spellValue->RadiusMod;
std::list<Unit*> unitList;
std::list<GameObject*> gobjectList;
switch (targetType)
{
case SPELL_TARGETS_ENTRY:
{
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id);
if (!conditions.empty())
{
for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST)
{
if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET)
continue;
if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1<<i)))
continue;
if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_CREATURE)
SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, (*i_spellST)->mConditionValue2);
else if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_CONTROLLED)
{
for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
if ((*itr)->GetEntry() == (*i_spellST)->mConditionValue2 &&
(*itr)->IsInMap(m_caster)) // For 60243 and 52173 need skip radius check or use range (no radius entry for effect)
unitList.push_back(*itr);
}
}
}
else
{
// Custom entries
// TODO: move these to sql
switch (m_spellInfo->Id)
{
case 46584: // Raise Dead
{
if (WorldObject* result = FindCorpseUsing<Trinity::RaiseDeadObjectCheck> ())
{
switch(result->GetTypeId())
{
case TYPEID_UNIT:
m_targets.SetDst(*result);
break;
default:
break;
}
}
break;
}
// Corpse Explosion
case 49158:
case 51325:
case 51326:
case 51327:
case 51328:
// Search for ghoul if our ghoul or dead body not valid unit target
if (!(m_targets.GetUnitTarget() && ((m_targets.GetUnitTarget()->GetEntry() == 26125 && m_targets.GetUnitTarget()->GetOwnerGUID() == m_caster->GetGUID())
|| (m_targets.GetUnitTarget()->getDeathState() == CORPSE
&& m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId()
&& m_targets.GetUnitTarget()->GetTypeId() == TYPEID_UNIT
&& !(m_targets.GetUnitTarget()->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL)
&& m_targets.GetUnitTarget()->GetDisplayId() == m_targets.GetUnitTarget()->GetNativeDisplayId()))))
{
CleanupTargetList();
WorldObject* result = FindCorpseUsing <Trinity::ExplodeCorpseObjectCheck> ();
if (result)
{
switch (result->GetTypeId())
{
case TYPEID_UNIT:
case TYPEID_PLAYER:
m_targets.SetUnitTarget((Unit*)result);
break;
default:
break;
}
}
else
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true);
SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW);
finish(false);
}
}
break;
default:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry());
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_TELEPORT_UNITS)
SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, 0);
else if (m_spellInfo->IsPositiveEffect(i))
SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ALLY);
else
SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENEMY);
}
}
break;
}
case SPELL_TARGETS_GO:
{
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id);
if (!conditions.empty())
{
for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST)
{
if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET)
continue;
if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1<<i)))
continue;
if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_GAMEOBJECT)
SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO, (*i_spellST)->mConditionValue2);
}
}
else
{
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_ACTIVATE_OBJECT)
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) (caster Entry: %u) with SPELL_EFFECT_ACTIVATE_OBJECT does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry());
SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO);
}
break;
}
case SPELL_TARGETS_ALLY:
case SPELL_TARGETS_ENEMY:
case SPELL_TARGETS_CHAINHEAL:
case SPELL_TARGETS_ANY:
SearchAreaTarget(unitList, radius, pushType, targetType);
break;
default:
switch (cur.GetTarget())
{
case TARGET_UNIT_AREA_PARTY_SRC:
case TARGET_UNIT_AREA_PARTY_DST:
m_caster->GetPartyMemberInDist(unitList, radius); //fix me
break;
case TARGET_UNIT_TARGET_ALLY_PARTY:
m_targets.GetUnitTarget()->GetPartyMemberInDist(unitList, radius);
break;
case TARGET_UNIT_PARTY_CASTER:
m_caster->GetPartyMemberInDist(unitList, radius);
break;
case TARGET_UNIT_RAID_CASTER:
m_caster->GetRaidMember(unitList, radius);
break;
case TARGET_UNIT_TARGET_CLASS_RAID:
{
Player* targetPlayer = m_targets.GetUnitTarget() && m_targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER
? (Player*)m_targets.GetUnitTarget() : NULL;
Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
if (pGroup)
{
for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if (Target && targetPlayer->IsWithinDistInMap(Target, radius) && targetPlayer->getClass() == Target->getClass() && !m_caster->IsHostileTo(Target))
AddUnitTarget(Target, i);
}
}
else if (m_targets.GetUnitTarget())
AddUnitTarget(m_targets.GetUnitTarget(), i);
break;
}
default:
break;
}
break;
}
if (!unitList.empty())
{
// Special target selection for smart heals and energizes
uint32 maxSize = 0;
int32 power = -1;
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (m_spellInfo->Id)
{
case 52759: // Ancestral Awakening
case 71610: // Echoes of Light (Althor's Abacus normal version)
case 71641: // Echoes of Light (Althor's Abacus heroic version)
maxSize = 1;
power = POWER_HEALTH;
break;
case 54968: // Glyph of Holy Light
maxSize = m_spellInfo->MaxAffectedTargets;
power = POWER_HEALTH;
break;
case 57669: // Replenishment
// In arenas Replenishment may only affect the caster
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena())
{
unitList.clear();
unitList.push_back(m_caster);
break;
}
maxSize = 10;
power = POWER_MANA;
break;
default:
break;
}
break;
case SPELLFAMILY_PRIEST:
if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing
{
maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing
power = POWER_HEALTH;
}
else if (m_spellInfo->Id == 64844) // Divine Hymn
{
maxSize = 3;
power = POWER_HEALTH;
}
else if (m_spellInfo->Id == 64904) // Hymn of Hope
{
maxSize = 3;
power = POWER_MANA;
}
else
break;
// Remove targets outside caster's raid
for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();)
{
if (!(*itr)->IsInRaidWith(m_caster))
itr = unitList.erase(itr);
else
++itr;
}
break;
case SPELLFAMILY_DRUID:
if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth
{
maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth
power = POWER_HEALTH;
}
else if (m_spellInfo->SpellFamilyFlags[2] == 0x0100) // Starfall
{
// Remove targets not in LoS or in stealth
for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();)
{
if ((*itr)->HasStealthAura() || (*itr)->HasInvisibilityAura() || !(*itr)->IsWithinLOSInMap(m_caster))
itr = unitList.erase(itr);
else
++itr;
}
break;
}
else
break;
// Remove targets outside caster's raid
for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();)
if (!(*itr)->IsInRaidWith(m_caster))
itr = unitList.erase(itr);
else
++itr;
break;
default:
break;
}
if (maxSize && power != -1)
{
if (Powers(power) == POWER_HEALTH)
{
if (unitList.size() > maxSize)
{
unitList.sort(Trinity::HealthPctOrderPred());
unitList.resize(maxSize);
}
}
else
{
for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();)
if ((*itr)->getPowerType() != (Powers)power)
itr = unitList.erase(itr);
else
++itr;
if (unitList.size() > maxSize)
{
unitList.sort(Trinity::PowerPctOrderPred((Powers)power));
unitList.resize(maxSize);
}
}
}
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
{
Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
if ((*j)->IsAffectedOnSpell(m_spellInfo))
maxTargets += (*j)->GetAmount();
if (m_spellInfo->Id == 5246) //Intimidating Shout
unitList.remove(m_targets.GetUnitTarget());
Trinity::RandomResizeList(unitList, maxTargets);
}
CallScriptAfterUnitTargetSelectHandlers(unitList, SpellEffIndex(i));
for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
AddUnitTarget(*itr, i);
}
if (!gobjectList.empty())
{
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
{
Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
if ((*j)->IsAffectedOnSpell(m_spellInfo))
maxTargets += (*j)->GetAmount();
Trinity::RandomResizeList(gobjectList, maxTargets);
}
for (std::list<GameObject*>::iterator itr = gobjectList.begin(); itr != gobjectList.end(); ++itr)
AddGOTarget(*itr, i);
}
}
}
void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura)
{
if (m_CastItem)
m_castItemGUID = m_CastItem->GetGUID();
else
m_castItemGUID = 0;
m_targets = *targets;
if (!m_targets.GetUnitTargetGUID() && m_spellInfo->Targets & TARGET_FLAG_UNIT)
{
Unit* target = NULL;
if (m_caster->GetTypeId() == TYPEID_UNIT)
target = m_caster->getVictim();
else
target = ObjectAccessor::GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection());
if (target && IsValidSingleTargetSpell(target))
m_targets.SetUnitTarget(target);
else
{
SendCastResult(SPELL_FAILED_BAD_TARGETS);
finish(false);
return;
}
}
if (Player* plrCaster = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself())
{
//check for special spell conditions
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id);
if (!conditions.empty())
if (!sConditionMgr->IsPlayerMeetToConditions(plrCaster, conditions))
{
//SendCastResult(SPELL_FAILED_DONT_REPORT);
SendCastResult(plrCaster, m_spellInfo, m_cast_count, SPELL_FAILED_DONT_REPORT);
finish(false);
return;
}
}
if (!m_targets.HasSrc() && m_spellInfo->Targets & TARGET_FLAG_SOURCE_LOCATION)
m_targets.SetSrc(*m_caster);
if (!m_targets.HasDst() && m_spellInfo->Targets & TARGET_FLAG_DEST_LOCATION)
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
{
if (m_caster->GetTypeId() == TYPEID_UNIT)
target = m_caster->getVictim();
else
target = ObjectAccessor::GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection());
}
if (target)
m_targets.SetDst(*target);
else
{
SendCastResult(SPELL_FAILED_BAD_TARGETS);
finish(false);
return;
}
}
// Fill aura scaling information
if (m_caster->IsControlledByPlayer() && !m_spellInfo->IsPassive() && m_spellInfo->SpellLevel && !m_spellInfo->IsChanneled() && !(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_SCALING))
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA)
{
// Change aura with ranks only if basepoints are taken from spellInfo and aura is positive
if (m_spellInfo->IsPositiveEffect(i))
{
m_auraScaleMask |= (1 << i);
if (m_spellValue->EffectBasePoints[i] != m_spellInfo->Effects[i].BasePoints)
{
m_auraScaleMask = 0;
break;
}
}
}
}
}
m_spellState = SPELL_STATE_PREPARING;
if (triggeredByAura)
m_triggeredByAuraSpell = triggeredByAura->GetSpellInfo();
// create and add update event for this spell
SpellEvent* Event = new SpellEvent(this);
m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
//Prevent casting at cast another spell (ServerSide check)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS) && m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
{
SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
finish(false);
return;
}
if (sDisableMgr->IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster))
{
SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
finish(false);
return;
}
LoadScripts();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
// Fill cost data (not use power for item casts
m_powerCost = m_CastItem ? 0 : m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask);
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
// Set combo point requirement
if ((_triggeredCastFlags & TRIGGERED_IGNORE_COMBO_POINTS) || m_CastItem || !m_caster->m_movedPlayer)
m_needComboPoints = false;
SpellCastResult result = CheckCast(true);
if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
{
if (triggeredByAura && !triggeredByAura->GetBase()->IsPassive())
{
SendChannelUpdate(0);
triggeredByAura->GetBase()->SetDuration(0);
}
SendCastResult(result);
finish(false);
return;
}
// Prepare data for triggers
prepareDataForTriggerSystem(triggeredByAura);
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
// calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
m_casttime = m_spellInfo->CalcCastTime(m_caster, this);
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
// don't allow channeled spells / spells with cast time to be casted while moving
// (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in)
if ((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->isMoving() && m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT)
{
SendCastResult(SPELL_FAILED_MOVING);
finish(false);
return;
}
// set timer base at cast time
ReSetTimer();
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::prepare: spell id %u source %u caster %d customCastFlags %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, _triggeredCastFlags, m_targets.GetTargetMask());
//Containers for channeled spells have to be set
//TODO:Apply this to all casted spells if needed
// Why check duration? 29350: channelled triggers channelled
if ((_triggeredCastFlags & TRIGGERED_CAST_DIRECTLY) && (!m_spellInfo->IsChanneled() || !m_spellInfo->GetMaxDuration()))
cast(true);
else
{
// stealth must be removed at cast starting (at show channel bar)
// skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS) && m_spellInfo->IsBreakingStealth())
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST);
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_spellInfo->Effects[i].GetRequiredTargetType() == SPELL_REQUIRE_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK);
break;
}
}
m_caster->SetCurrentCastedSpell(this);
SendSpellStart();
// set target for proper facing
if (m_casttime && !(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING))
if (uint64 target = m_targets.GetUnitTargetGUID())
if (m_caster->GetGUID() != target && m_caster->GetTypeId() == TYPEID_UNIT)
m_caster->FocusTarget(this, target);
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_GCD))
TriggerGlobalCooldown();
//item: first cast may destroy item and second cast causes crash
if (!m_casttime && !m_spellInfo->StartRecoveryTime && !m_castItemGUID && GetCurrentContainer() == CURRENT_GENERIC_SPELL)
cast(true);
}
}
void Spell::cancel()
{
if (m_spellState == SPELL_STATE_FINISHED)
return;
uint32 oldState = m_spellState;
m_spellState = SPELL_STATE_FINISHED;
m_autoRepeat = false;
switch (oldState)
{
case SPELL_STATE_PREPARING:
CancelGlobalCooldown();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RestoreSpellMods(this);
case SPELL_STATE_DELAYED:
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
break;
case SPELL_STATE_CASTING:
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
SendChannelUpdate(0);
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
// spell is canceled-take mods and clear list
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->RemoveSpellMods(this);
m_appliedMods.clear();
break;
default:
break;
}
SetReferencedFromCurrent(false);
if (m_selfContainer && *m_selfContainer == this)
*m_selfContainer = NULL;
m_caster->RemoveDynObject(m_spellInfo->Id);
m_caster->RemoveGameObject(m_spellInfo->Id, true);
//set state back so finish will be processed
m_spellState = oldState;
finish(false);
}
void Spell::cast(bool skipCheck)
{
// update pointers base at GUIDs to prevent access to non-existed already object
UpdatePointers();
if (Unit* target = m_targets.GetUnitTarget())
{
// three check: prepare, cast (m_casttime > 0), hit (delayed)
if (m_casttime && target->isAlive() && !target->IsFriendlyTo(m_caster) && !m_caster->canSeeOrDetect(target))
{
SendCastResult(SPELL_FAILED_BAD_TARGETS);
SendInterrupted(0);
finish(false);
return;
}
}
else
{
// cancel at lost main target unit
if (m_targets.GetUnitTargetGUID() && m_targets.GetUnitTargetGUID() != m_caster->GetGUID())
{
cancel();
return;
}
}
// now that we've done the basic check, now run the scripts
// should be done before the spell is actually executed
if (Player* playerCaster = m_caster->ToPlayer())
sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck);
SetExecutedCurrently(true);
if (m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.GetUnitTarget() && m_targets.GetUnitTarget() != m_caster)
m_caster->SetInFront(m_targets.GetUnitTarget());
// Should this be done for original caster?
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
// Set spell which will drop charges for triggered cast spells
// if not successfully casted, will be remove in finish(false)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
}
// skip check if done already (for instant cast spells for example)
if (!skipCheck)
{
SpellCastResult castResult = CheckCast(false);
if (castResult != SPELL_CAST_OK)
{
SendCastResult(castResult);
SendInterrupted(0);
//restore spell mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
finish(false);
SetExecutedCurrently(false);
return;
}
// additional check after cast bar completes (must not be in CheckCast)
// if trade not complete then remember it in trade data
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (TradeData* my_trade = m_caster->ToPlayer()->GetTradeData())
{
if (!my_trade->IsInAcceptProcess())
{
// Spell will be casted at completing the trade. Silently ignore at this place
my_trade->SetSpell(m_spellInfo->Id, m_CastItem);
SendCastResult(SPELL_FAILED_DONT_REPORT);
SendInterrupted(0);
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
finish(false);
SetExecutedCurrently(false);
return;
}
}
}
}
}
SelectSpellTargets();
// Spell may be finished after target map check
if (m_spellState == SPELL_STATE_FINISHED)
{
SendInterrupted(0);
//restore spell mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_caster->ToPlayer()->RestoreSpellMods(this);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
finish(false);
SetExecutedCurrently(false);
return;
}
PrepareTriggersExecutedOnHit();
// traded items have trade slot instead of guid in m_itemTargetGUID
// set to real guid to be sent later to the client
m_targets.UpdateTradeSlotItem();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) && m_CastItem)
{
m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_ITEM, m_CastItem->GetEntry());
m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
}
m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
// Powers have to be taken before SendSpellGo
TakePower();
TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
}
else if (Item* targetItem = m_targets.GetItemTarget())
{
/// Not own traded item (in trader trade slot) req. reagents including triggered spell case
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
TakeReagents();
}
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_DIRECT_DAMAGE)
CalculateDamageDoneForAllTargets();
// CAST SPELL
SendSpellCooldown();
PrepareScriptHitHandlers();
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch(m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_CHARGE:
case SPELL_EFFECT_CHARGE_DEST:
case SPELL_EFFECT_JUMP:
case SPELL_EFFECT_JUMP_DEST:
case SPELL_EFFECT_LEAP_BACK:
case SPELL_EFFECT_ACTIVATE_RUNE:
HandleEffects(NULL, NULL, NULL, i);
m_effectMask |= (1<<i);
break;
}
}
// we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
SendSpellGo();
// Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
if ((m_spellInfo->Speed > 0.0f && !m_spellInfo->IsChanneled()) || m_spellInfo->Id == 14157)
{
// Remove used for cast item if need (it can be already NULL after TakeReagents call
// in case delayed spell remove item at cast delay start
TakeCastItem();
// Okay, maps created, now prepare flags
m_immediateHandled = false;
m_spellState = SPELL_STATE_DELAYED;
SetDelayStart(0);
if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
m_caster->ClearUnitState(UNIT_STAT_CASTING);
}
else
{
// Immediate spell, no big deal
handle_immediate();
}
if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id))
{
for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
if (*i < 0)
m_caster->RemoveAurasDueToSpell(-(*i));
else
m_caster->CastSpell(m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster, *i, true);
}
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
SetExecutedCurrently(false);
}
void Spell::handle_immediate()
{
// start channeling if applicable
if (m_spellInfo->IsChanneled())
{
int32 duration = m_spellInfo->GetDuration();
if (duration)
{
// First mod_duration then haste - see Missile Barrage
// Apply duration mod
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
// Apply haste mods
if (m_spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION)
m_caster->ModSpellCastTime(m_spellInfo, duration, this);
m_spellState = SPELL_STATE_CASTING;
m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
SendChannelStart(duration);
}
}
PrepareTargetProcessing();
// process immediate effects (items, ground, etc.) also initialize some variables
_handle_immediate_phase();
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
FinishTargetProcessing();
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
// Remove used for cast item if need (it can be already NULL after TakeReagents call
TakeCastItem();
if (m_spellState != SPELL_STATE_CASTING)
finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
}
uint64 Spell::handle_delayed(uint64 t_offset)
{
UpdatePointers();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
uint64 next_time = 0;
PrepareTargetProcessing();
if (!m_immediateHandled)
{
_handle_immediate_phase();
m_immediateHandled = true;
}
bool single_missile = (m_targets.HasDst());
// now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->processed == false)
{
if (single_missile || ihit->timeDelay <= t_offset)
{
ihit->timeDelay = t_offset;
DoAllEffectOnTarget(&(*ihit));
}
else if (next_time == 0 || ihit->timeDelay < next_time)
next_time = ihit->timeDelay;
}
}
// now recheck gameobject targeting correctness
for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
{
if (ighit->processed == false)
{
if (single_missile || ighit->timeDelay <= t_offset)
DoAllEffectOnTarget(&(*ighit));
else if (next_time == 0 || ighit->timeDelay < next_time)
next_time = ighit->timeDelay;
}
}
FinishTargetProcessing();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
// All targets passed - need finish phase
if (next_time == 0)
{
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
finish(true); // successfully finish spell cast
// return zero, spell is finished now
return 0;
}
else
{
// spell is unfinished, return next execution time
return next_time;
}
}
void Spell::_handle_immediate_phase()
{
m_spellAura = NULL;
// handle some immediate features of the spell here
HandleThreatSpells();
PrepareScriptHitHandlers();
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].Effect == 0)
continue;
// apply Send Event effect to ground in case empty target lists
if (m_spellInfo->Effects[j].Effect == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j))
{
HandleEffects(NULL, NULL, NULL, j);
continue;
}
}
// initialize Diminishing Returns Data
m_diminishLevel = DIMINISHING_LEVEL_1;
m_diminishGroup = DIMINISHING_NONE;
// process items
for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
if (!m_originalCaster)
return;
uint8 oldEffMask = m_effectMask;
// process ground
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].Effect == 0)
continue;
if (m_spellInfo->Effects[j].GetRequiredTargetType() == SPELL_REQUIRE_DEST)
{
if (!m_targets.HasDst()) // FIXME: this will ignore dest set in effect
m_targets.SetDst(*m_caster);
HandleEffects(m_originalCaster, NULL, NULL, j);
m_effectMask |= (1<<j);
}
else if (m_spellInfo->Effects[j].GetRequiredTargetType() == SPELL_REQUIRE_NONE)
{
HandleEffects(m_originalCaster, NULL, NULL, j);
m_effectMask |= (1<<j);
}
}
if (oldEffMask != m_effectMask && m_UniqueTargetInfo.empty())
{
uint32 procAttacker = m_procAttacker;
if (!procAttacker)
{
bool positive = true;
for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
// If at least one effect negative spell is negative hit
if (m_effectMask & (1<<i) && !m_spellInfo->IsPositiveEffect(i))
{
positive = false;
break;
}
switch(m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
if (positive)
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS;
else
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
break;
case SPELL_DAMAGE_CLASS_NONE:
if (positive)
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS;
else
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
break;
}
}
// Proc damage for spells which have only dest targets (2484 should proc 51486 for example)
m_originalCaster->ProcDamageAndSpell(0, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell);
}
}
void Spell::_handle_finish_phase()
{
if (m_caster->m_movedPlayer)
{
// Take for real after all targets are processed
if (m_needComboPoints)
m_caster->m_movedPlayer->ClearComboPoints();
// Real add combo points from effects
if (m_comboPointGain)
m_caster->m_movedPlayer->GainSpellComboPoints(m_comboPointGain);
}
// TODO: trigger proc phase finish here
}
void Spell::SendSpellCooldown()
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* _player = (Player*)m_caster;
// mana/health/etc potions, disabled by client (until combat out as declarate)
if (m_CastItem && m_CastItem->IsPotion())
{
// need in some way provided data for Spell::finish SendCooldownEvent
_player->SetLastPotionId(m_CastItem->GetEntry());
return;
}
// have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation)
if (m_spellInfo->Attributes & (SPELL_ATTR0_DISABLED_WHILE_ACTIVE | SPELL_ATTR0_PASSIVE) || (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD))
return;
_player->AddSpellAndCategoryCooldowns(m_spellInfo, m_CastItem ? m_CastItem->GetEntry() : 0, this);
}
void Spell::update(uint32 difftime)
{
// update pointers based at it's GUIDs
UpdatePointers();
if (m_targets.GetUnitTargetGUID() && !m_targets.GetUnitTarget())
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %u is cancelled due to removal of target.", m_spellInfo->Id);
cancel();
return;
}
// check if the player caster has moved before the spell finished
if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) &&
(m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
{
// don't cancel for melee, autorepeat, triggered and instant spells
if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered())
cancel();
}
switch(m_spellState)
{
case SPELL_STATE_PREPARING:
{
if (m_timer)
{
if (difftime >= m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
// don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example
cast(!m_casttime);
} break;
case SPELL_STATE_CASTING:
{
if (m_timer > 0)
{
// check if there are alive targets left
if (!UpdateChanneledTargetList())
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id);
SendChannelUpdate(0);
finish();
}
if (difftime >= m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
if (m_timer == 0)
{
SendChannelUpdate(0);
// channeled spell processed independently for quest targeting
// cast at creature (or GO) quest objectives update at successful cast channel finished
// ignore autorepeat/melee casts for speed (not exist quest for spells (hm...)
if (!IsAutoRepeat() && !IsNextMeleeSwingSpell())
{
if (Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself())
{
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
TargetInfo* target = &*ihit;
if (!IS_CRE_OR_VEH_GUID(target->targetGUID))
continue;
Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
if (unit == NULL)
continue;
p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
}
for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
{
GOTargetInfo* target = &*ihit;
GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
if (!go)
continue;
p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
}
}
}
finish();
}
} break;
default:
{
}break;
}
}
void Spell::finish(bool ok)
{
if (!m_caster)
return;
if (m_spellState == SPELL_STATE_FINISHED)
return;
m_spellState = SPELL_STATE_FINISHED;
if (m_spellInfo->IsChanneled())
m_caster->UpdateInterruptMask();
if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
m_caster->ClearUnitState(UNIT_STAT_CASTING);
// Unsummon summon as possessed creatures on spell cancel
if (m_spellInfo->IsChanneled() && m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (Unit *charm = m_caster->GetCharm())
if (charm->GetTypeId() == TYPEID_UNIT
&& charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET)
&& charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id)
((Puppet*)charm)->UnSummon();
}
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_caster->ReleaseFocus(this);
if (!ok)
return;
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isSummon())
{
// Unsummon statue
uint32 spell = m_caster->GetUInt32Value(UNIT_CREATED_BY_SPELL);
SpellInfo const *spellInfo = sSpellMgr->GetSpellInfo(spell);
if (spellInfo && spellInfo->SpellIconID == 2056)
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id);
m_caster->setDeathState(JUST_DIED);
return;
}
}
if (IsAutoActionResetSpell())
{
bool found = false;
Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET);
for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i)
{
if ((*i)->IsAffectedOnSpell(m_spellInfo))
{
found = true;
break;
}
}
if (!found && !(m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
{
m_caster->resetAttackTimer(BASE_ATTACK);
if (m_caster->haveOffhandWeapon())
m_caster->resetAttackTimer(OFF_ATTACK);
m_caster->resetAttackTimer(RANGED_ATTACK);
}
}
// potions disabled by client, send event "not in combat" if need
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (!m_triggeredByAuraSpell)
m_caster->ToPlayer()->UpdatePotionCooldown(this);
// triggered spell pointer can be not set in some cases
// this is needed for proper apply of triggered spell mods
m_caster->ToPlayer()->SetSpellModTakingSpell(this, true);
// Take mods after trigger spell (needed for 14177 to affect 48664)
// mods are taken only on succesfull cast and independantly from targets of the spell
m_caster->ToPlayer()->RemoveSpellMods(this);
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
}
// Stop Attack for some spells
if (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET)
m_caster->AttackStop();
}
void Spell::SendCastResult(SpellCastResult result)
{
if (result == SPELL_CAST_OK)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
if (m_caster->ToPlayer()->GetSession()->PlayerLoading()) // don't send cast results at loading time
return;
SendCastResult(m_caster->ToPlayer(), m_spellInfo, m_cast_count, result, m_customError);
}
void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/)
{
if (result == SPELL_CAST_OK)
return;
WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
data << uint8(cast_count); // single cast or multi 2.3 (0/1)
data << uint32(spellInfo->Id);
data << uint8(result); // problem
switch (result)
{
case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
data << uint32(spellInfo->RequiresSpellFocus);
break;
case SPELL_FAILED_REQUIRES_AREA:
// hardcode areas limitation case
switch(spellInfo->Id)
{
case 41617: // Cenarion Mana Salve
case 41619: // Cenarion Healing Salve
data << uint32(3905);
break;
case 41618: // Bottled Nethergon Energy
case 41620: // Bottled Nethergon Vapor
data << uint32(3842);
break;
case 45373: // Bloodberry Elixir
data << uint32(4075);
break;
default: // default case (don't must be)
data << uint32(0);
break;
}
break;
case SPELL_FAILED_TOTEMS:
if (spellInfo->Totem[0])
data << uint32(spellInfo->Totem[0]);
if (spellInfo->Totem[1])
data << uint32(spellInfo->Totem[1]);
break;
case SPELL_FAILED_TOTEM_CATEGORY:
if (spellInfo->TotemCategory[0])
data << uint32(spellInfo->TotemCategory[0]);
if (spellInfo->TotemCategory[1])
data << uint32(spellInfo->TotemCategory[1]);
break;
case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
data << uint32(spellInfo->EquippedItemClass);
data << uint32(spellInfo->EquippedItemSubClassMask);
//data << uint32(spellInfo->EquippedItemInventoryTypeMask);
break;
case SPELL_FAILED_TOO_MANY_OF_ITEM:
{
uint32 item = 0;
for (int8 x = 0;x < 3; x++)
if (spellInfo->EffectItemType[x])
item = spellInfo->EffectItemType[x];
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (pProto && pProto->ItemLimitCategory)
data << uint32(pProto->ItemLimitCategory);
break;
}
case SPELL_FAILED_CUSTOM_ERROR:
data << uint32(customError);
break;
default:
break;
}
caster->GetSession()->SendPacket(&data);
}
void Spell::SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/)
{
if (result == SPELL_CAST_OK)
return;
WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
data << uint8(cast_count); // single cast or multi 2.3 (0/1)
data << uint32(spellInfo->Id);
data << uint8(result); // problem
switch (result)
{
case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
data << uint32(spellInfo->RequiresSpellFocus);
break;
case SPELL_FAILED_REQUIRES_AREA:
// hardcode areas limitation case
switch(spellInfo->Id)
{
case 41617: // Cenarion Mana Salve
case 41619: // Cenarion Healing Salve
data << uint32(3905);
break;
case 41618: // Bottled Nethergon Energy
case 41620: // Bottled Nethergon Vapor
data << uint32(3842);
break;
case 45373: // Bloodberry Elixir
data << uint32(4075);
break;
default: // default case (don't must be)
data << uint32(0);
break;
}
break;
case SPELL_FAILED_TOTEMS:
if (spellInfo->Totem[0])
data << uint32(spellInfo->Totem[0]);
if (spellInfo->Totem[1])
data << uint32(spellInfo->Totem[1]);
break;
case SPELL_FAILED_TOTEM_CATEGORY:
if (spellInfo->TotemCategory[0])
data << uint32(spellInfo->TotemCategory[0]);
if (spellInfo->TotemCategory[1])
data << uint32(spellInfo->TotemCategory[1]);
break;
case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
data << uint32(spellInfo->EquippedItemClass);
data << uint32(spellInfo->EquippedItemSubClassMask);
//data << uint32(spellInfo->EquippedItemInventoryTypeMask);
break;
case SPELL_FAILED_TOO_MANY_OF_ITEM:
{
uint32 item = 0;
for (int8 x = 0;x < 3; x++)
if (spellInfo->Effects[x].ItemType)
item = spellInfo->Effects[x].ItemType;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (pProto && pProto->ItemLimitCategory)
data << uint32(pProto->ItemLimitCategory);
break;
}
case SPELL_FAILED_CUSTOM_ERROR:
data << uint32(customError);
break;
default:
break;
}
caster->GetSession()->SendPacket(&data);
}
void Spell::SendSpellStart()
{
if (!IsNeedSendToClient())
return;
//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
uint32 castFlags = CAST_FLAG_UNKNOWN_2;
if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell)
castFlags |= CAST_FLAG_PENDING;
if (m_spellInfo->Attributes & SPELL_ATTR0_REQ_AMMO)
castFlags |= CAST_FLAG_AMMO;
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet()))
&& m_spellInfo->PowerType != POWER_HEALTH)
castFlags |= CAST_FLAG_POWER_LEFT_SELF;
if (m_spellInfo->RuneCostID && m_spellInfo->PowerType == POWER_RUNE)
castFlags |= CAST_FLAG_UNKNOWN_19;
WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
if (m_CastItem)
data.append(m_CastItem->GetPackGUID());
else
data.append(m_caster->GetPackGUID());
data.append(m_caster->GetPackGUID());
data << uint8(m_cast_count); // pending spell cast?
data << uint32(m_spellInfo->Id); // spellId
data << uint32(castFlags); // cast flags
data << uint32(m_timer); // delay?
m_targets.Write(data);
if (castFlags & CAST_FLAG_POWER_LEFT_SELF)
data << uint32(m_caster->GetPower((Powers)m_spellInfo->PowerType));
if (castFlags & CAST_FLAG_AMMO)
WriteAmmoToPacket(&data);
if (castFlags & CAST_FLAG_UNKNOWN_23)
{
data << uint32(0);
data << uint32(0);
}
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendSpellGo()
{
// not send invisible spell casting
if (!IsNeedSendToClient())
return;
//sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
uint32 castFlags = CAST_FLAG_UNKNOWN_9;
// triggered spells with spell visual != 0
if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell)
castFlags |= CAST_FLAG_PENDING;
if (m_spellInfo->Attributes & SPELL_ATTR0_REQ_AMMO)
castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet()))
&& m_spellInfo->PowerType != POWER_HEALTH)
castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible
if ((m_caster->GetTypeId() == TYPEID_PLAYER)
&& (m_caster->getClass() == CLASS_DEATH_KNIGHT)
&& m_spellInfo->RuneCostID
&& m_spellInfo->PowerType == POWER_RUNE)
{
castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
castFlags |= CAST_FLAG_UNKNOWN_9; // ??
}
if (m_spellInfo->HasEffect(SPELL_EFFECT_ACTIVATE_RUNE))
{
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
}
WorldPacket data(SMSG_SPELL_GO, 50); // guess size
if (m_CastItem)
data.append(m_CastItem->GetPackGUID());
else
data.append(m_caster->GetPackGUID());
data.append(m_caster->GetPackGUID());
data << uint8(m_cast_count); // pending spell cast?
data << uint32(m_spellInfo->Id); // spellId
data << uint32(castFlags); // cast flags
data << uint32(getMSTime()); // timestamp
/*
// statement below seems to be wrong - i've seen spells with both unit and dest target
// Can't have TARGET_FLAG_UNIT when *_LOCATION is present - it breaks missile visuals
if (m_targets.GetTargetMask() & (TARGET_FLAG_SOURCE_LOCATION | TARGET_FLAG_DEST_LOCATION))
m_targets.setTargetMask(m_targets.GetTargetMask() & ~TARGET_FLAG_UNIT);
else if (m_targets.getIntTargetFlags() & FLAG_INT_UNIT)
m_targets.setTargetMask(m_targets.GetTargetMask() | TARGET_FLAG_UNIT);
*/
WriteSpellGoTargets(&data);
m_targets.Write(data);
if (castFlags & CAST_FLAG_POWER_LEFT_SELF)
data << uint32(m_caster->GetPower((Powers)m_spellInfo->PowerType));
if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list
{
Player* player = m_caster->ToPlayer();
uint8 runeMaskInitial = m_runesState;
uint8 runeMaskAfterCast = player->GetRunesState();
data << uint8(runeMaskInitial); // runes state before
data << uint8(runeMaskAfterCast); // runes state after
for (uint8 i = 0; i < MAX_RUNES; ++i)
{
uint8 mask = (1 << i);
if (mask & runeMaskInitial && !(mask & runeMaskAfterCast)) // usable before andon cooldown now...
{
// float casts ensure the division is performed on floats as we need float result
float baseCd = float(player->GetRuneBaseCooldown(i));
data << uint8((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed
}
}
}
if (castFlags & CAST_FLAG_UNKNOWN_18) // unknown wotlk
{
data << float(0);
data << uint32(0);
}
if (castFlags & CAST_FLAG_AMMO)
WriteAmmoToPacket(&data);
if (castFlags & CAST_FLAG_UNKNOWN_20) // unknown wotlk
{
data << uint32(0);
data << uint32(0);
}
if (m_targets.GetTargetMask() & TARGET_FLAG_DEST_LOCATION)
{
data << uint8(0);
}
m_caster->SendMessageToSet(&data, true);
}
void Spell::WriteAmmoToPacket(WorldPacket * data)
{
uint32 ammoInventoryType = 0;
uint32 ammoDisplayID = 0;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK);
if (pItem)
{
ammoInventoryType = pItem->GetTemplate()->InventoryType;
if (ammoInventoryType == INVTYPE_THROWN)
ammoDisplayID = pItem->GetTemplate()->DisplayInfoID;
else
{
uint32 ammoID = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID);
if (ammoID)
{
ItemTemplate const *pProto = sObjectMgr->GetItemTemplate(ammoID);
if (pProto)
{
ammoDisplayID = pProto->DisplayInfoID;
ammoInventoryType = pProto->InventoryType;
}
}
else if (m_caster->HasAura(46699)) // Requires No Ammo
{
ammoDisplayID = 5996; // normal arrow
ammoInventoryType = INVTYPE_AMMO;
}
}
}
}
else
{
for (uint8 i = 0; i < 3; ++i)
{
if (uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i))
{
if (ItemEntry const* itemEntry = sItemStore.LookupEntry(item_id))
{
if (itemEntry->Class == ITEM_CLASS_WEAPON)
{
switch(itemEntry->SubClass)
{
case ITEM_SUBCLASS_WEAPON_THROWN:
ammoDisplayID = itemEntry->DisplayId;
ammoInventoryType = itemEntry->InventoryType;
break;
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
ammoDisplayID = 5996; // is this need fixing?
ammoInventoryType = INVTYPE_AMMO;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
ammoDisplayID = 5998; // is this need fixing?
ammoInventoryType = INVTYPE_AMMO;
break;
}
if (ammoDisplayID)
break;
}
}
}
}
}
*data << uint32(ammoDisplayID);
*data << uint32(ammoInventoryType);
}
void Spell::WriteSpellGoTargets(WorldPacket * data)
{
// This function also fill data for channeled spells:
// m_needAliveTargetMask req for stop channelig if one target die
uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
uint32 miss = 0;
for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
{
// possibly SPELL_MISS_IMMUNE2 for this??
ihit->missCondition = SPELL_MISS_IMMUNE2;
++miss;
}
else if ((*ihit).missCondition == SPELL_MISS_NONE)
++hit;
else
++miss;
}
*data << (uint8)hit;
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
{
*data << uint64(ihit->targetGUID);
m_channelTargetEffectMask |=ihit->effectMask;
}
}
for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
*data << uint64(ighit->targetGUID); // Always hits
*data << (uint8)miss;
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition != SPELL_MISS_NONE) // Add only miss
{
*data << uint64(ihit->targetGUID);
*data << uint8(ihit->missCondition);
if (ihit->missCondition == SPELL_MISS_REFLECT)
*data << uint8(ihit->reflectResult);
}
}
// Reset m_needAliveTargetMask for non channeled spell
if (!m_spellInfo->IsChanneled())
m_channelTargetEffectMask = 0;
}
void Spell::SendLogExecute()
{
WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
data.append(m_caster->GetPackGUID());
data << uint32(m_spellInfo->Id);
uint8 effCount = 0;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_effectExecuteData[i])
++effCount;
}
if (!effCount)
return;
data << uint32(effCount);
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!m_effectExecuteData[i])
continue;
data << uint32(m_spellInfo->Effects[i].Effect); // spell effect
data.append(*m_effectExecuteData[i]);
delete m_effectExecuteData[i];
m_effectExecuteData[i] = NULL;
}
m_caster->SendMessageToSet(&data, true);
}
void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 powerTaken, float gainMultiplier)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(target->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(powerTaken);
*m_effectExecuteData[effIndex] << uint32(powerType);
*m_effectExecuteData[effIndex] << float(gainMultiplier);
}
void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 attCount)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(victim->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(attCount);
}
void Spell::ExecuteLogEffectInterruptCast(uint8 effIndex, Unit* victim, uint32 spellId)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(victim->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(spellId);
}
void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, uint32 /*itemslot*/, uint32 damage)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(victim->GetPackGUID());
*m_effectExecuteData[effIndex] << uint32(m_spellInfo->Id);
*m_effectExecuteData[effIndex] << uint32(damage);
}
void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object * obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry)
{
InitEffectExecuteData(effIndex);
*m_effectExecuteData[effIndex] << uint32(entry);
}
void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry)
{
InitEffectExecuteData(effIndex);
*m_effectExecuteData[effIndex] << uint32(entry);
}
void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject * obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject * obj)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(obj->GetPackGUID());
}
void Spell::ExecuteLogEffectResurrect(uint8 effIndex, Unit* target)
{
InitEffectExecuteData(effIndex);
m_effectExecuteData[effIndex]->append(target->GetPackGUID());
}
void Spell::SendInterrupted(uint8 result)
{
WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
data.append(m_caster->GetPackGUID());
data << uint8(m_cast_count);
data << uint32(m_spellInfo->Id);
data << uint8(result);
m_caster->SendMessageToSet(&data, true);
data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
data.append(m_caster->GetPackGUID());
data << uint8(m_cast_count);
data << uint32(m_spellInfo->Id);
data << uint8(result);
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendChannelUpdate(uint32 time)
{
if (time == 0)
{
m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
}
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(MSG_CHANNEL_UPDATE, 8+4);
data.append(m_caster->GetPackGUID());
data << uint32(time);
m_caster->SendMessageToSet(&data, true);
}
void Spell::SendChannelStart(uint32 duration)
{
WorldObject* target = NULL;
// select first not resisted target from target list for first available effect
if (!m_UniqueTargetInfo.empty())
{
for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
{
for (uint8 effIndex = EFFECT_0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
if ((itr->effectMask & (1 << effIndex)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
{
target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
break;
}
}
}
}
else if (!m_UniqueGOTargetInfo.empty())
{
for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
{
for (uint8 effIndex = EFFECT_0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
if (itr->effectMask & (1 << effIndex))
{
target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
break;
}
}
}
}
WorldPacket data(MSG_CHANNEL_START, (8+4+4));
data.append(m_caster->GetPackGUID());
data << uint32(m_spellInfo->Id);
data << uint32(duration);
m_caster->SendMessageToSet(&data, true);
m_timer = duration;
if (target)
m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
}
void Spell::SendResurrectRequest(Player* target)
{
// get ressurector name for creature resurrections, otherwise packet will be not accepted
// for player resurrections the name is looked up by guid
char const* resurrectorName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(resurrectorName)+1+1+1+4));
data << uint64(m_caster->GetGUID()); // resurrector guid
data << uint32(strlen(resurrectorName) + 1);
data << resurrectorName;
data << uint8(0); // null terminator
data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1); // "you'll be afflicted with resurrection sickness"
// override delay sent with SMSG_CORPSE_RECLAIM_DELAY, set instant resurrection for spells with this attribute
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_IGNORE_RESURRECTION_TIMER)
data << uint32(0);
target->GetSession()->SendPacket(&data);
}
void Spell::TakeCastItem()
{
if (!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// not remove cast item at triggered spell (equipping, weapon damage, etc)
if (_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM)
return;
ItemTemplate const *proto = m_CastItem->GetTemplate();
if (!proto)
{
// This code is to avoid a crash
// I'm not sure, if this is really an error, but I guess every item needs a prototype
sLog->outError("Cast item has no item prototype highId=%d, lowId=%d", m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
return;
}
bool expendable = false;
bool withoutCharges = false;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
if (proto->Spells[i].SpellId)
{
// item has limited charges
if (proto->Spells[i].SpellCharges)
{
if (proto->Spells[i].SpellCharges < 0)
expendable = true;
int32 charges = m_CastItem->GetSpellCharges(i);
// item has charges left
if (charges)
{
(charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
if (proto->Stackable == 1)
m_CastItem->SetSpellCharges(i, charges);
m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
}
// all charges used
withoutCharges = (charges == 0);
}
}
}
if (expendable && withoutCharges)
{
uint32 count = 1;
m_caster->ToPlayer()->DestroyItemCount(m_CastItem, count, true);
// prevent crash at access to deleted m_targets.GetItemTarget
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(NULL);
m_CastItem = NULL;
}
}
void Spell::TakePower()
{
if (m_CastItem || m_triggeredByAuraSpell)
return;
bool hit = true;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (m_spellInfo->PowerType == POWER_RAGE || m_spellInfo->PowerType == POWER_ENERGY || m_spellInfo->PowerType == POWER_RUNE)
if (uint64 targetGUID = m_targets.GetUnitTargetGUID())
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if (ihit->targetGUID == targetGUID)
{
if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS/* && ihit->targetGUID != m_caster->GetGUID()*/)
hit = false;
if (ihit->missCondition != SPELL_MISS_NONE)
{
//lower spell cost on fail (by talent aura)
if (Player *modOwner = m_caster->ToPlayer()->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost);
}
break;
}
}
Powers powerType = Powers(m_spellInfo->PowerType);
if (powerType == POWER_RUNE)
{
TakeRunePower(hit);
return;
}
if (!m_powerCost)
return;
// health as power used
if (m_spellInfo->PowerType == POWER_HEALTH)
{
m_caster->ModifyHealth(-(int32)m_powerCost);
return;
}
if (m_spellInfo->PowerType >= MAX_POWERS)
{
sLog->outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->PowerType);
return;
}
if (hit)
m_caster->ModifyPower(powerType, -m_powerCost);
else
m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4));
// Set the five second timer
if (powerType == POWER_MANA && m_powerCost > 0)
m_caster->SetLastManaUse(getMSTime());
}
void Spell::TakeAmmo()
{
if (m_attackType == RANGED_ATTACK && m_caster->GetTypeId() == TYPEID_PLAYER)
{
Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK);
// wands don't have ammo
if (!pItem || pItem->IsBroken() || pItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_WAND)
return;
if (pItem->GetTemplate()->InventoryType == INVTYPE_THROWN)
{
if (pItem->GetMaxStackCount() == 1)
{
// decrease durability for non-stackable throw weapon
m_caster->ToPlayer()->DurabilityPointLossForEquipSlot(EQUIPMENT_SLOT_RANGED);
}
else
{
// decrease items amount for stackable throw weapon
uint32 count = 1;
m_caster->ToPlayer()->DestroyItemCount(pItem, count, true);
}
}
else if (uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID))
m_caster->ToPlayer()->DestroyItemCount(ammo, 1, true);
}
}
SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
{
if (m_spellInfo->PowerType != POWER_RUNE || !runeCostID)
return SPELL_CAST_OK;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_CAST_OK;
Player *plr = (Player*)m_caster;
if (plr->getClass() != CLASS_DEATH_KNIGHT)
return SPELL_CAST_OK;
SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
if (!src)
return SPELL_CAST_OK;
if (src->NoRuneCost())
return SPELL_CAST_OK;
int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
for (uint32 i = 0; i < RUNE_DEATH; ++i)
{
runeCost[i] = src->RuneCost[i];
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
}
runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = plr->GetCurrentRune(i);
if ((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
runeCost[rune]--;
}
for (uint32 i = 0; i < RUNE_DEATH; ++i)
if (runeCost[i] > 0)
runeCost[RUNE_DEATH] += runeCost[i];
if (runeCost[RUNE_DEATH] > MAX_RUNES)
return SPELL_FAILED_NO_POWER; // not sure if result code is correct
return SPELL_CAST_OK;
}
void Spell::TakeRunePower(bool didHit)
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_caster->getClass() != CLASS_DEATH_KNIGHT)
return;
SpellRuneCostEntry const *runeCostData = sSpellRuneCostStore.LookupEntry(m_spellInfo->RuneCostID);
if (!runeCostData || (runeCostData->NoRuneCost() && runeCostData->NoRunicPowerGain()))
return;
Player *player = m_caster->ToPlayer();
m_runesState = player->GetRunesState(); // store previous state
int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
for (uint32 i = 0; i < RUNE_DEATH; ++i)
{
runeCost[i] = runeCostData->RuneCost[i];
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
}
runeCost[RUNE_DEATH] = 0; // calculated later
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = player->GetCurrentRune(i);
if (!player->GetRuneCooldown(i) && runeCost[rune] > 0)
{
player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN));
player->SetLastUsedRune(rune);
runeCost[rune]--;
}
}
runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
if (runeCost[RUNE_DEATH] > 0)
{
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType rune = player->GetCurrentRune(i);
if (!player->GetRuneCooldown(i) && rune == RUNE_DEATH)
{
player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown(i) : uint32(RUNE_MISS_COOLDOWN));
player->SetLastUsedRune(rune);
runeCost[rune]--;
// keep Death Rune type if missed
if (didHit)
player->RestoreBaseRune(i);
if (runeCost[RUNE_DEATH] == 0)
break;
}
}
}
// you can gain some runic power when use runes
if (didHit)
if (int32 rp = int32(runeCostData->runePowerGain * sWorld->getRate(RATE_POWER_RUNICPOWER_INCOME)))
player->ModifyPower(POWER_RUNIC_POWER, int32(rp));
}
void Spell::TakeReagents()
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// do not take reagents for these item casts
if (m_CastItem && m_CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)
return;
Player* p_caster = (Player*)m_caster;
if (p_caster->CanNoReagentCast(m_spellInfo))
return;
for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x)
{
if (m_spellInfo->Reagent[x] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[x];
uint32 itemcount = m_spellInfo->ReagentCount[x];
// if CastItem is also spell reagent
if (m_CastItem)
{
ItemTemplate const *proto = m_CastItem->GetTemplate();
if (proto && proto->ItemId == itemid)
{
for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
{
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(s);
if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
m_CastItem = NULL;
}
}
// if GetItemTarget is also spell reagent
if (m_targets.GetItemTargetEntry() == itemid)
m_targets.SetItemTarget(NULL);
p_caster->DestroyItemCount(itemid, itemcount, true);
}
}
void Spell::HandleThreatSpells()
{
if (!m_targets.GetUnitTarget())
return;
if (!m_targets.GetUnitTarget()->CanHaveThreatList())
return;
uint16 threat = sSpellMgr->GetSpellThreat(m_spellInfo->Id);
if (!threat)
return;
m_targets.GetUnitTarget()->AddThreat(m_caster, float(threat));
sLog->outStaticDebug("Spell %u, rank %u, added an additional %i threat", m_spellInfo->Id, m_spellInfo->GetRank(), threat);
}
void Spell::HandleEffects(Unit *pUnitTarget, Item *pItemTarget, GameObject *pGOTarget, uint32 i)
{
//effect has been handled, skip it
if (m_effectMask & (1<<i))
return;
unitTarget = pUnitTarget;
itemTarget = pItemTarget;
gameObjTarget = pGOTarget;
uint8 eff = m_spellInfo->Effects[i].Effect;
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell: %u Effect : %u", m_spellInfo->Id, eff);
//we do not need DamageMultiplier here.
damage = CalculateDamage(i, NULL);
bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i);
if (!preventDefault && eff < TOTAL_SPELL_EFFECTS)
{
(this->*SpellEffects[eff])((SpellEffIndex)i);
}
}
SpellCastResult Spell::CheckCast(bool strict)
{
OutdoorPvPWG *pvpWG = (OutdoorPvPWG*)sOutdoorPvPMgr->GetOutdoorPvPToZoneId(4197);
// check death state
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && !m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD))
return SPELL_FAILED_CASTER_DEAD;
// check cooldowns to prevent cheating
if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE))
{
//can cast triggered (by aura only?) spells while have this flag
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && m_caster->ToPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY))
return SPELL_FAILED_SPELL_IN_PROGRESS;
if (m_caster->ToPlayer()->HasSpellCooldown(m_spellInfo->Id))
{
if (m_triggeredByAuraSpell)
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NOT_READY;
}
}
if (m_spellInfo->AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL && !m_caster->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS))
return SPELL_FAILED_SPELL_UNAVAILABLE;
// Check global cooldown
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_GCD) && HasGlobalCooldown())
return SPELL_FAILED_NOT_READY;
// only triggered spells can be processed an ended battleground
if (!IsTriggered() && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() == STATUS_WAIT_LEAVE)
return SPELL_FAILED_DONT_REPORT;
if (m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled())
{
if (m_spellInfo->Attributes & SPELL_ATTR0_OUTDOORS_ONLY &&
!m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_OUTDOORS;
if (m_spellInfo->Attributes & SPELL_ATTR0_INDOORS_ONLY &&
m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_INDOORS;
}
// only check at first call, Stealth auras are already removed at second call
// for now, ignore triggered spells
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_SHAPESHIFT))
{
bool checkForm = true;
// Ignore form req aura
Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(m_spellInfo))
continue;
checkForm = false;
break;
}
if (checkForm)
{
// Cannot be used in this stance/form
SpellCastResult shapeError = m_spellInfo->CheckShapeshift(m_caster->GetShapeshiftForm());
if (shapeError != SPELL_CAST_OK)
return shapeError;
if ((m_spellInfo->Attributes & SPELL_ATTR0_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
return SPELL_FAILED_ONLY_STEALTHED;
}
}
bool reqCombat=true;
Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
{
if ((*j)->IsAffectedOnSpell(m_spellInfo))
{
m_needComboPoints = false;
if ((*j)->GetMiscValue() == 1)
{
reqCombat=false;
break;
}
}
}
// caster state requirements
// not for triggered spells (needed by execute)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE))
{
if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraState), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
// Note: spell 62473 requres casterAuraSpell = triggering spell
if (m_spellInfo->CasterAuraSpell && !m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->CasterAuraSpell, m_caster)))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->ExcludeCasterAuraSpell && m_caster->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->ExcludeCasterAuraSpell, m_caster)))
return SPELL_FAILED_CASTER_AURASTATE;
if (reqCombat && m_caster->isInCombat() && !m_spellInfo->CanBeUsedInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
}
// cancel autorepeat spells if cast start when moving
// (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving())
{
// skip stuck spell to allow use it in falling case and apply spell limitations at movement
if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK) &&
(IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0))
return SPELL_FAILED_MOVING;
}
Vehicle* vehicle = m_caster->GetVehicle();
if (vehicle && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE))
{
uint16 checkMask = 0;
for (uint8 effIndex = EFFECT_0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
SpellEffectInfo const* effInfo = &m_spellInfo->Effects[effIndex];
if (effInfo->ApplyAuraName == SPELL_AURA_MOD_SHAPESHIFT)
{
SpellShapeshiftEntry const* shapeShiftEntry = sSpellShapeshiftStore.LookupEntry(effInfo->MiscValue);
if (shapeShiftEntry && (shapeShiftEntry->flags1 & 1) == 0) // unk flag
checkMask |= VEHICLE_SEAT_FLAG_UNCONTROLLED;
break;
}
}
if (m_spellInfo->HasAura(SPELL_AURA_MOUNTED))
checkMask |= VEHICLE_SEAT_FLAG_CAN_CAST_MOUNT_SPELL;
if (!checkMask)
checkMask = VEHICLE_SEAT_FLAG_CAN_ATTACK;
VehicleSeatEntry const* vehicleSeat = vehicle->GetSeatForPassenger(m_caster);
if (!(m_spellInfo->AttributesEx6 & SPELL_ATTR6_CASTABLE_WHILE_ON_VEHICLE) && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)
&& (vehicleSeat->m_flags & checkMask) != checkMask)
return SPELL_FAILED_DONT_REPORT;
}
/* Was haben die da schon weider eingebaut ....
// Don't check explicit target for passive spells (workaround) (check should be skipped only for learn case)
// those spells may have incorrect target entries or not filled at all (for example 15332)
// such spells when learned are not targeting anyone using targeting system, they should apply directly to caster instead
// also, such casts shouldn't be sent to client
if (!((m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster) || m_caster->isSummon())
{
// Check explicit target for m_originalCaster - todo: get rid of such workarounds
SpellCastResult castResult = m_spellInfo->CheckExplicitTarget(m_originalCaster ? m_originalCaster : m_caster, m_targets.GetObjectTarget(), m_targets.GetItemTarget());
if (castResult != SPELL_CAST_OK)
return castResult;
}*/
Unit* target = m_targets.GetUnitTarget();
// In pure self-cast spells, the client won't send any unit target
if (!target && (m_targets.GetTargetMask() == TARGET_FLAG_SELF || m_targets.GetTargetMask() & TARGET_FLAG_UNIT_ALLY)) // TARGET_FLAG_SELF == 0, remember!
target = m_caster;
if (target)
{
// target state requirements (not allowed state), apply to self also
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_AURASTATE) && m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraStateType(m_spellInfo->TargetAuraStateNot), m_spellInfo, m_caster))
return SPELL_FAILED_TARGET_AURASTATE;
if (m_spellInfo->TargetAuraSpell && !target->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->TargetAuraSpell, m_caster)))
return SPELL_FAILED_TARGET_AURASTATE;
if (m_spellInfo->ExcludeTargetAuraSpell && target->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->ExcludeTargetAuraSpell, m_caster)))
return SPELL_FAILED_TARGET_AURASTATE;
if (!IsTriggered() && target == m_caster && m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_TARGET_SELF)
return SPELL_FAILED_BAD_TARGETS;
bool non_caster_target = target != m_caster && m_spellInfo->IsRequiringSelectedTarget();
if (non_caster_target)
{
// target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_AURASTATE) && m_spellInfo->TargetAuraState && !target->HasAuraState(AuraStateType(m_spellInfo->TargetAuraState), m_spellInfo, m_caster))
return SPELL_FAILED_TARGET_AURASTATE;
// Not allow casting on flying player or on vehicle player (if caster isnt vehicle)
if (target->HasUnitState(UNIT_STAT_IN_FLIGHT) /*|| (target->HasUnitState(UNIT_STAT_ONVEHICLE) && target->GetVehicleBase() != m_caster)*/)
return SPELL_FAILED_BAD_TARGETS;
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_DETECTABILITY) && !m_caster->canSeeOrDetect(target))
return SPELL_FAILED_BAD_TARGETS;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
// Do not allow these spells to target creatures not tapped by us (Banish, Polymorph, many quest spells)
if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_CANT_TARGET_TAPPED)
if (Creature *targetCreature = target->ToCreature())
if (targetCreature->hasLootRecipient() && !targetCreature->isTappedBy(m_caster->ToPlayer()))
return SPELL_FAILED_CANT_CAST_ON_TAPPED;
if (m_spellInfo->AttributesCu & SPELL_ATTR0_CU_PICKPOCKET)
{
if (target->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
else if ((target->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0)
return SPELL_FAILED_TARGET_NO_POCKETS;
}
// Not allow disarm unarmed player
if (m_spellInfo->Mechanic == MECHANIC_DISARM)
{
if (target->GetTypeId() == TYPEID_PLAYER)
{
Player* player = target->ToPlayer();
if (!player->GetWeaponForAttack(BASE_ATTACK) || !player->IsUseEquipedWeapon(true))
return SPELL_FAILED_TARGET_NO_WEAPONS;
}
else if (!target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID))
return SPELL_FAILED_TARGET_NO_WEAPONS;
}
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_LOS) && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
return SPELL_FAILED_LINE_OF_SIGHT;
}
else if (m_caster == target)
{
if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster
{
// Additional check for some spells
// If 0 spell effect empty - client not send target data (need use selection)
// TODO: check it on next client version
if (m_targets.GetTargetMask() == TARGET_FLAG_SELF &&
m_spellInfo->Effects[1].TargetA.GetTarget() == TARGET_UNIT_TARGET_ENEMY)
{
target = m_caster->GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection());
if (target)
m_targets.SetUnitTarget(target);
else
return SPELL_FAILED_BAD_TARGETS;
}
// Lay on Hands - cannot be self-cast on paladin with Forbearance or after using Avenging Wrath
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags[0] & 0x0008000)
if (target->HasAura(61988)) // Immunity shield marker
return SPELL_FAILED_TARGET_AURASTATE;
}
}
// check pet presents
for (int j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].TargetA.GetTarget() == TARGET_UNIT_PET)
{
target = m_caster->GetGuardianPet();
if (!target)
{
if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NO_PET;
}
break;
}
}
// check creature type
// ignore self casts (including area casts when caster selected as target)
if (non_caster_target)
{
if (!CheckTargetCreatureType(target))
{
if (target->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_TARGET_IS_PLAYER;
else
return SPELL_FAILED_BAD_TARGETS;
}
// Must be behind the target
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET) && target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_BEHIND;
// Target must be facing you
if ((m_spellInfo->AttributesCu & SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER) && !target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_INFRONT;
// Target must not be in combat
if (m_spellInfo->AttributesEx & SPELL_ATTR1_NOT_IN_COMBAT_TARGET && target->isInCombat())
return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
}
if (target)
if (m_spellInfo->IsPositive())
if (target->IsImmunedToSpell(m_spellInfo))
return SPELL_FAILED_TARGET_AURASTATE;
}
// Spell casted only on battleground
if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
if (!m_caster->ToPlayer()->InBattleground())
return SPELL_FAILED_ONLY_BATTLEGROUNDS;
// do not allow spells to be cast in arenas
// - with greater than 10 min CD without SPELL_ATTR4_USABLE_IN_ARENA flag
// - with SPELL_ATTR4_NOT_USABLE_IN_ARENA flag
if ((m_spellInfo->AttributesEx4 & SPELL_ATTR4_NOT_USABLE_IN_ARENA) ||
(m_spellInfo->GetRecoveryTime() > 10 * MINUTE * IN_MILLISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR4_USABLE_IN_ARENA)))
if (MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
if (mapEntry->IsBattleArena())
return SPELL_FAILED_NOT_IN_ARENA;
// zone check
if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->isGameMaster())
{
uint32 zone, area;
m_caster->GetZoneAndAreaId(zone, area);
SpellCastResult locRes= m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area,
m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : NULL);
if (locRes != SPELL_CAST_OK)
return locRes;
}
// not let players cast spells at mount (and let do it to creatures)
if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) &&
!m_spellInfo->IsPassive() && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED))
{
if (m_caster->isInFlight())
return SPELL_FAILED_NOT_ON_TAXI;
else
return SPELL_FAILED_NOT_MOUNTED;
}
SpellCastResult castResult = SPELL_CAST_OK;
// always (except passive spells) check items (focus object can be required for any type casts)
if (!m_spellInfo->IsPassive())
{
castResult = CheckItems();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// Triggered spells also have range check
// TODO: determine if there is some flag to enable/disable the check
castResult = CheckRange(strict);
if (castResult != SPELL_CAST_OK)
return castResult;
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
castResult = CheckPower();
if (castResult != SPELL_CAST_OK)
return castResult;
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS))
{
castResult = CheckCasterAuras();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// script hook
castResult = CallScriptCheckCastHandlers();
if (castResult != SPELL_CAST_OK)
return castResult;
for (int i = 0; i < MAX_SPELL_EFFECTS; i++)
{
// for effects of spells that have only one target
switch(m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_DUMMY:
{
if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
{
if (m_caster->IsInWater())
return SPELL_FAILED_ONLY_ABOVEWATER;
}
else if (m_spellInfo->SpellIconID == 156) // Holy Shock
{
// spell different for friends and enemies
// hurt version required facing
if (m_targets.GetUnitTarget() && !m_caster->IsFriendlyTo(m_targets.GetUnitTarget()) && !m_caster->HasInArc(static_cast<float>(M_PI), m_targets.GetUnitTarget()))
return SPELL_FAILED_UNIT_NOT_INFRONT;
}
else if (m_spellInfo->SpellIconID == 33 && m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_FIRE_NOVA)
{
if (!m_caster->m_SummonSlot[1])
return SPELL_FAILED_SUCCESS;
}
else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] == 0x2000) // Death Coil (DeathKnight)
{
Unit* target = m_targets.GetUnitTarget();
if (!target || (target->IsFriendlyTo(m_caster) && target->GetCreatureType() != CREATURE_TYPE_UNDEAD))
return SPELL_FAILED_BAD_TARGETS;
}
else if (m_spellInfo->Id == 19938) // Awaken Peon
{
Unit *unit = m_targets.GetUnitTarget();
if (!unit || !unit->HasAura(17743))
return SPELL_FAILED_BAD_TARGETS;
}
else if (m_spellInfo->Id == 52264) // Deliver Stolen Horse
{
if (!m_caster->FindNearestCreature(28653, 5))
return SPELL_FAILED_OUT_OF_RANGE;
}
else if (m_spellInfo->Id == 31789) // Righteous Defense
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_DONT_REPORT;
Unit* target = m_targets.GetUnitTarget();
if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty())
return SPELL_FAILED_BAD_TARGETS;
}
break;
}
case SPELL_EFFECT_LEARN_SPELL:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_PET)
break;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
SpellInfo const *learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
break;
}
case SPELL_EFFECT_LEARN_PET_SPELL:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
SpellInfo const *learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
break;
}
case SPELL_EFFECT_APPLY_GLYPH:
{
uint32 glyphId = m_spellInfo->Effects[i].MiscValue;
if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyphId))
if (m_caster->HasAura(gp->SpellId))
return SPELL_FAILED_UNIQUE_GLYPH;
break;
}
case SPELL_EFFECT_FEED_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Item* foodItem = m_targets.GetItemTarget();
if (!foodItem)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (!pet->HaveInDiet(foodItem->GetTemplate()))
return SPELL_FAILED_WRONG_PET_FOOD;
if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel))
return SPELL_FAILED_FOOD_LOWLEVEL;
if (m_caster->isInCombat() || pet->isInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
break;
}
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_POWER_DRAIN:
{
// Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Unit* target = m_targets.GetUnitTarget())
if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->Effects[i].MiscValue))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_CHARGE:
{
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR)
{
// Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process
if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953))
m_caster->RemoveMovementImpairingAuras();
}
if (m_caster->HasUnitState(UNIT_STAT_ROOT))
return SPELL_FAILED_ROOTED;
break;
}
case SPELL_EFFECT_SKINNING:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT)
return SPELL_FAILED_BAD_TARGETS;
if (!(m_targets.GetUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE))
return SPELL_FAILED_TARGET_UNSKINNABLE;
Creature* creature = m_targets.GetUnitTarget()->ToCreature();
if (creature->GetCreatureType() != CREATURE_TYPE_CRITTER && !creature->loot.isLooted())
return SPELL_FAILED_TARGET_NOT_LOOTED;
uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill);
int32 TargetLevel = m_targets.GetUnitTarget()->getLevel();
int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
if (ReqValue > skillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
// chance for fail at orange skinning attempt
if ((m_selfContainer && (*m_selfContainer) == this) &&
skillValue < sWorld->GetConfigMaxSkillValue() &&
(ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37))
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_OPEN_LOCK:
{
if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT &&
m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM)
break;
if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
// we need a go target in case of TARGET_GAMEOBJECT
|| (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT && !m_targets.GetGOTarget()))
return SPELL_FAILED_BAD_TARGETS;
Item *pTempItem = NULL;
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData())
pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.GetItemTargetGUID()));
}
else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM)
pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID());
// we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM &&
!m_targets.GetGOTarget() &&
(!pTempItem || !pTempItem->GetTemplate()->LockID || !pTempItem->IsLocked()))
return SPELL_FAILED_BAD_TARGETS;
if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() &&
m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP))
if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners
!m_caster->ToPlayer()->CanUseBattlegroundObject())
return SPELL_FAILED_TRY_AGAIN;
// get the lock entry
uint32 lockId = 0;
if (GameObject* go = m_targets.GetGOTarget())
{
lockId = go->GetGOInfo()->GetLockId();
if (!lockId)
return SPELL_FAILED_BAD_TARGETS;
}
else if (Item* itm = m_targets.GetItemTarget())
lockId = itm->GetTemplate()->LockID;
SkillType skillId = SKILL_NONE;
int32 reqSkillValue = 0;
int32 skillValue = 0;
// check lock compatibility
SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
if (res != SPELL_CAST_OK)
return res;
// chance for fail at orange mining/herb/LockPicking gathering attempt
// second check prevent fail at rechecks
if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
{
bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
// chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
return SPELL_FAILED_TRY_AGAIN;
}
break;
}
case SPELL_EFFECT_SUMMON_DEAD_PET:
{
Creature *pet = m_caster->GetGuardianPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (pet->isAlive())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
break;
}
// This is generic summon effect
case SPELL_EFFECT_SUMMON:
{
SummonPropertiesEntry const *SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[i].MiscValueB);
if (!SummonProperties)
break;
switch(SummonProperties->Category)
{
case SUMMON_CATEGORY_PET:
if (m_caster->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
case SUMMON_CATEGORY_PUPPET:
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
break;
}
case SPELL_EFFECT_CREATE_TAMED_PET:
{
if (m_targets.GetUnitTarget())
{
if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (m_targets.GetUnitTarget()->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
break;
}
case SPELL_EFFECT_SUMMON_PET:
{
if (m_caster->GetPetGUID()) //let warlock do a replacement summon
{
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK)
{
if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
if (Pet* pet = m_caster->ToPlayer()->GetPet())
pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
}
else
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
case SPELL_EFFECT_SUMMON_PLAYER:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_caster->ToPlayer()->GetSelection())
return SPELL_FAILED_BAD_TARGETS;
Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetSelection());
if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell
return SPELL_FAILED_BAD_TARGETS;
// check if our map is dungeon
// Need to Add Block When Caster and Target Instancebind are not Same or Null
if (sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon())
{
Map const* pMap = m_caster->GetMap();
InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(pMap->GetId());
if (!instance)
return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
if (!target->Satisfy(sObjectMgr->GetAccessRequirement(pMap->GetId(), pMap->GetDifficulty()), pMap->GetId()))
return SPELL_FAILED_BAD_TARGETS;
}
/*
MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId());
if (map->IsDungeon())
{
uint32 mapId = m_caster->GetMap()->GetId();
Difficulty difficulty = m_caster->GetMap()->GetDifficulty();
if (map->IsRaid())
if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty))
if (targetBind->perm && targetBind != m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty))
return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE;
InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId);
if (!instance)
return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId))
return SPELL_FAILED_BAD_TARGETS;
}
*/
break;
}
// RETURN HERE
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
{
if(m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Player* playerCaster = m_caster->ToPlayer();
//
if(!(playerCaster->GetSelection()))
return SPELL_FAILED_BAD_TARGETS;
Player* target = ObjectAccessor::FindPlayer(playerCaster->GetSelection());
if (!target ||
!(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId()))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP:
case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
{
//Do not allow to cast it before BG starts.
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground const *bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() != STATUS_IN_PROGRESS)
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
{
if (m_targets.GetUnitTarget() == m_caster)
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP_BACK:
{
// Spell 781 (Disengage) requires player to be in combat
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Id == 781 && !m_caster->isInCombat())
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
Unit* target = m_targets.GetUnitTarget();
if (m_caster == target && m_caster->HasUnitState(UNIT_STAT_ROOT))
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_ROOTED;
else
return SPELL_FAILED_DONT_REPORT;
}
break;
}
case SPELL_EFFECT_TALENT_SPEC_SELECT:
// can't change during already started arena/battleground
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() == STATUS_IN_PROGRESS)
return SPELL_FAILED_NOT_IN_BATTLEGROUND;
break;
default:
break;
}
}
for (int i = 0; i < MAX_SPELL_EFFECTS; i++)
{
switch(m_spellInfo->Effects[i].ApplyAuraName)
{
case SPELL_AURA_DUMMY:
{
//custom check
switch(m_spellInfo->Id)
{
// Tag Murloc
case 30877:
{
Unit* target = m_targets.GetUnitTarget();
if (!target || target->GetEntry() != 17326)
return SPELL_FAILED_BAD_TARGETS;
break;
}
case 61336:
if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_caster->ToPlayer()->IsInFeralForm())
return SPELL_FAILED_ONLY_SHAPESHIFT;
break;
case 1515:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
Creature* target = m_targets.GetUnitTarget()->ToCreature();
if (target->getLevel() > m_caster->getLevel())
return SPELL_FAILED_HIGHLEVEL;
// use SMSG_PET_TAME_FAILURE?
if (!target->GetCreatureInfo()->isTameable (m_caster->ToPlayer()->CanTameExoticPets()))
return SPELL_FAILED_BAD_TARGETS;
if (m_caster->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
case 44795: // Parachute
{
float x, y, z;
m_caster->GetPosition(x, y, z);
float ground_Z = m_caster->GetMap()->GetHeight(x, y, z);
if (fabs(ground_Z - z) < 0.1f)
return SPELL_FAILED_DONT_REPORT;
break;
}
default:
break;
}
break;
}
case SPELL_AURA_MOD_POSSESS_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NO_PET;
Pet *pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (pet->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
break;
}
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_AOE_CHARM:
{
if (m_caster->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM
|| m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS)
{
if (m_caster->GetPetGUID())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
if (m_caster->GetCharmGUID())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
}
if (Unit* target = m_targets.GetUnitTarget())
{
if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (target->IsMounted())
return SPELL_FAILED_CANT_BE_CHARMED;
if (target->GetCharmerGUID())
return SPELL_FAILED_CHARMED;
int32 damage = CalculateDamage(i, target);
if (damage && int32(target->getLevel()) > damage)
return SPELL_FAILED_HIGHLEVEL;
}
break;
}
case SPELL_AURA_MOUNTED:
{
if (m_caster->IsInWater())
return SPELL_FAILED_ONLY_ABOVEWATER;
// Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena();
InstanceTemplate const *it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId());
if (it)
allowMount = it->AllowMount;
if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->AreaGroupId)
return SPELL_FAILED_NO_MOUNTS_ALLOWED;
if (m_caster->IsInDisallowedMountForm())
return SPELL_FAILED_NOT_SHAPESHIFT;
break;
}
case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
{
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
// can be casted at non-friendly unit or own pet/charm
if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget()))
return SPELL_FAILED_TARGET_FRIENDLY;
break;
}
case SPELL_AURA_FLY:
case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
{
// not allow cast fly spells if not have req. skills (all spells is self target)
// allow always ghost flight spells
if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->isAlive())
{
if (AreaTableEntry const* pArea = GetAreaEntryByAreaID(m_originalCaster->GetAreaId()))
{
if (pArea->flags & AREA_FLAG_NO_FLY_ZONE)
return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE;
// Wintergrasp Antifly check
if (sWorld->getBoolConfig(CONFIG_OUTDOORPVP_WINTERGRASP_ENABLED))
{
if (m_originalCaster->GetZoneId() == 4197 && pvpWG && pvpWG != 0 && pvpWG->isWarTime()==true)
return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE;
}
}
}
break;
}
case SPELL_AURA_PERIODIC_MANA_LEECH:
{
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
break;
if (m_targets.GetUnitTarget()->getPowerType() != POWER_MANA)
return SPELL_FAILED_BAD_TARGETS;
break;
}
default:
break;
}
}
// check trade slot case (last, for allow catch any another cast problems)
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (m_CastItem)
return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NOT_TRADING;
TradeData* my_trade = m_caster->ToPlayer()->GetTradeData();
if (!my_trade)
return SPELL_FAILED_NOT_TRADING;
TradeSlots slot = TradeSlots(m_targets.GetItemTargetGUID());
if (slot != TRADE_SLOT_NONTRADED)
return SPELL_FAILED_BAD_TARGETS;
if (!IsTriggered())
if (my_trade->GetSpell())
return SPELL_FAILED_ITEM_ALREADY_ENCHANTED;
}
// check if caster has at least 1 combo point for spells that require combo points
if (m_needComboPoints)
if (Player* plrCaster = m_caster->ToPlayer())
if (!plrCaster->GetComboPoints())
return SPELL_FAILED_NO_COMBO_POINTS;
// all ok
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckPetCast(Unit* target)
{
if (!m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD))
return SPELL_FAILED_CASTER_DEAD;
if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS)) //prevent spellcast interruption by another spellcast
return SPELL_FAILED_SPELL_IN_PROGRESS;
if (m_caster->isInCombat() && !m_spellInfo->CanBeUsedInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
//dead owner (pets still alive when owners ressed?)
if (Unit *owner = m_caster->GetCharmerOrOwner())
if (!owner->isAlive())
return SPELL_FAILED_CASTER_DEAD;
if (!target && m_targets.GetUnitTarget())
target = m_targets.GetUnitTarget();
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].TargetA.GetType() == TARGET_TYPE_UNIT_TARGET
|| m_spellInfo->Effects[i].TargetA.GetType() == TARGET_TYPE_DEST_TARGET)
{
if (!target)
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
m_targets.SetUnitTarget(target);
break;
}
}
Unit* _target = m_targets.GetUnitTarget();
if (_target) //for target dead/target not valid
{
if (!_target->isAlive())
return SPELL_FAILED_BAD_TARGETS;
if (!IsValidSingleTargetSpell(_target))
return SPELL_FAILED_BAD_TARGETS;
}
//cooldown
if (m_caster->ToCreature()->HasSpellCooldown(m_spellInfo->Id))
return SPELL_FAILED_NOT_READY;
return CheckCast(true);
}
SpellCastResult Spell::CheckCasterAuras() const
{
// spells totally immuned to caster auras (wsg flag drop, give marks etc)
if (m_spellInfo->AttributesEx6 & SPELL_ATTR6_IGNORE_CASTER_AURAS)
return SPELL_CAST_OK;
uint8 school_immune = 0;
uint32 mechanic_immune = 0;
uint32 dispel_immune = 0;
// Check if the spell grants school or mechanic immunity.
// We use bitmasks so the loop is done only once and not on every aura check below.
if (m_spellInfo->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
{
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_SCHOOL_IMMUNITY)
school_immune |= uint32(m_spellInfo->Effects[i].MiscValue);
else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MECHANIC_IMMUNITY)
mechanic_immune |= 1 << uint32(m_spellInfo->Effects[i].MiscValue);
else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_DISPEL_IMMUNITY)
dispel_immune |= SpellInfo::GetDispelMask(DispelType(m_spellInfo->Effects[i].MiscValue));
}
// immune movement impairment and loss of control
if (m_spellInfo->Id == 42292 || m_spellInfo->Id == 59752)
mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
}
bool usableInStun = m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_STUNNED;
// Glyph of Pain Suppression
// there is no other way to handle it
if (m_spellInfo->Id == 33206 && !m_caster->HasAura(63248))
usableInStun = false;
// Check whether the cast should be prevented by any state you might have.
SpellCastResult prevented_reason = SPELL_CAST_OK;
// Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
if (unitflag & UNIT_FLAG_STUNNED)
{
// spell is usable while stunned, check if caster has only mechanic stun auras, another stun types must prevent cast spell
if (usableInStun)
{
bool foundNotStun = false;
Unit::AuraEffectList const& stunAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_STUN);
for (Unit::AuraEffectList::const_iterator i = stunAuras.begin(); i != stunAuras.end(); ++i)
{
if (!((*i)->GetSpellInfo()->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN)))
{
foundNotStun = true;
break;
}
}
if (foundNotStun)
prevented_reason = SPELL_FAILED_STUNNED;
}
else
prevented_reason = SPELL_FAILED_STUNNED;
}
else if (unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED))
prevented_reason = SPELL_FAILED_CONFUSED;
else if (unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED))
prevented_reason = SPELL_FAILED_FLEEING;
else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
prevented_reason = SPELL_FAILED_SILENCED;
else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
prevented_reason = SPELL_FAILED_PACIFIED;
// Attr must make flag drop spell totally immune from all effects
if (prevented_reason != SPELL_CAST_OK)
{
if (school_immune || mechanic_immune || dispel_immune)
{
//Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras();
for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
SpellInfo const* auraInfo = aura->GetSpellInfo();
if (auraInfo->GetAllEffectsMechanicMask() & mechanic_immune)
continue;
if (auraInfo->GetSchoolMask() & school_immune)
continue;
if (auraInfo->GetDispelMask() & dispel_immune)
continue;
//Make a second check for spell failed so the right SPELL_FAILED message is returned.
//That is needed when your casting is prevented by multiple states and you are only immune to some of them.
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (AuraEffect* part = aura->GetEffect(i))
{
switch (part->GetAuraType())
{
case SPELL_AURA_MOD_STUN:
if (!usableInStun || !(auraInfo->GetAllEffectsMechanicMask() & (1<<MECHANIC_STUN)))
return SPELL_FAILED_STUNNED;
break;
case SPELL_AURA_MOD_CONFUSE:
if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED))
return SPELL_FAILED_CONFUSED;
break;
case SPELL_AURA_MOD_FEAR:
if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED))
return SPELL_FAILED_FLEEING;
break;
case SPELL_AURA_MOD_SILENCE:
case SPELL_AURA_MOD_PACIFY:
case SPELL_AURA_MOD_PACIFY_SILENCE:
if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
return SPELL_FAILED_PACIFIED;
else if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
return SPELL_FAILED_SILENCED;
break;
default: break;
}
}
}
}
}
// You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
else
return prevented_reason;
}
return SPELL_CAST_OK;
}
bool Spell::CanAutoCast(Unit* target)
{
uint64 targetguid = target->GetGUID();
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (m_spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA)
{
if (m_spellInfo->StackAmount <= 1)
{
if (target->HasAuraEffect(m_spellInfo->Id, j))
return false;
}
else
{
if (AuraEffect * aureff = target->GetAuraEffect(m_spellInfo->Id, j))
if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount)
return false;
}
}
else if (m_spellInfo->Effects[j].IsAreaAuraEffect())
{
if (target->HasAuraEffect(m_spellInfo->Id, j))
return false;
}
}
SpellCastResult result = CheckPetCast(target);
if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
{
SelectSpellTargets();
//check if among target units, our WANTED target is as well (->only self cast spells return false)
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if (ihit->targetGUID == targetguid)
return true;
}
return false; //target invalid
}
SpellCastResult Spell::CheckRange(bool strict)
{
// Don't check for instant cast spells
if (!strict && m_casttime == 0)
return SPELL_CAST_OK;
uint32 range_type = 0;
if (m_spellInfo->RangeEntry)
{
// self cast doesn't need range checking -- also for Starshards fix
if (m_spellInfo->RangeEntry->ID == 1)
return SPELL_CAST_OK;
range_type = m_spellInfo->RangeEntry->type;
}
Unit* target = m_targets.GetUnitTarget();
float max_range = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo);
float min_range = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo);
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
if (target && target != m_caster)
{
if (range_type == SPELL_RANGE_MELEE)
{
// Because of lag, we can not check too strictly here.
if (!m_caster->IsWithinMeleeRange(target, max_range))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT;
}
else if (!m_caster->IsWithinCombatRange(target, max_range))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; //0x5A;
if (range_type == SPELL_RANGE_RANGED)
{
if (m_caster->IsWithinMeleeRange(target))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT;
}
else if (min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT;
if (m_caster->GetTypeId() == TYPEID_PLAYER &&
(m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target))
return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_UNIT_NOT_INFRONT : SPELL_FAILED_DONT_REPORT;
}
if (m_targets.HasDst() && !m_targets.HasTraj())
{
if (!m_caster->IsWithinDist3d(m_targets.GetDst(), max_range))
return SPELL_FAILED_OUT_OF_RANGE;
if (min_range && m_caster->IsWithinDist3d(m_targets.GetDst(), min_range))
return SPELL_FAILED_TOO_CLOSE;
}
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckPower()
{
// item cast not used power
if (m_CastItem)
return SPELL_CAST_OK;
// health as power used - need check health amount
if (m_spellInfo->PowerType == POWER_HEALTH)
{
if (int32(m_caster->GetHealth()) <= m_powerCost)
return SPELL_FAILED_CASTER_AURASTATE;
return SPELL_CAST_OK;
}
// Check valid power type
if (m_spellInfo->PowerType >= MAX_POWERS)
{
sLog->outError("Spell::CheckPower: Unknown power type '%d'", m_spellInfo->PowerType);
return SPELL_FAILED_UNKNOWN;
}
//check rune cost only if a spell has PowerType == POWER_RUNE
if (m_spellInfo->PowerType == POWER_RUNE)
{
SpellCastResult failReason = CheckRuneCost(m_spellInfo->RuneCostID);
if (failReason != SPELL_CAST_OK)
return failReason;
}
// Check power amount
Powers powerType = Powers(m_spellInfo->PowerType);
if (int32(m_caster->GetPower(powerType)) < m_powerCost)
return SPELL_FAILED_NO_POWER;
else
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckItems()
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_CAST_OK;
Player* p_caster = (Player*)m_caster;
if (!m_CastItem)
{
if (m_castItemGUID)
return SPELL_FAILED_ITEM_NOT_READY;
}
else
{
uint32 itemid = m_CastItem->GetEntry();
if (!p_caster->HasItemCount(itemid, 1))
return SPELL_FAILED_ITEM_NOT_READY;
ItemTemplate const *proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (int i = 0; i < MAX_ITEM_SPELLS; ++i)
if (proto->Spells[i].SpellCharges)
if (m_CastItem->GetSpellCharges(i) == 0)
return SPELL_FAILED_NO_CHARGES_REMAIN;
// consumable cast item checks
if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.GetUnitTarget())
{
// such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
SpellCastResult failReason = SPELL_CAST_OK;
for (int i = 0; i < MAX_SPELL_EFFECTS; i++)
{
// skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.GetUnitTarget() is not the real target but the caster
if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_PET)
continue;
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_HEAL)
{
if (m_targets.GetUnitTarget()->IsFullHealth())
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
// Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
if (m_spellInfo->Effects[i].MiscValue < 0 || m_spellInfo->Effects[i].MiscValue >= int8(MAX_POWERS))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
Powers power = Powers(m_spellInfo->Effects[i].MiscValue);
if (m_targets.GetUnitTarget()->GetPower(power) == m_targets.GetUnitTarget()->GetMaxPower(power))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
}
if (failReason != SPELL_CAST_OK)
return failReason;
}
}
// check target item
if (m_targets.GetItemTargetGUID())
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_targets.GetItemTarget())
return SPELL_FAILED_ITEM_GONE;
if (!m_targets.GetItemTarget()->IsFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// if not item target then required item must be equipped
else
{
if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->ToPlayer()->HasItemFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// check spell focus object
if (m_spellInfo->RequiresSpellFocus)
{
CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
GameObject* ok = NULL;
Trinity::GameObjectFocusCheck go_check(m_caster, m_spellInfo->RequiresSpellFocus);
Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(m_caster, ok, go_check);
TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
Map& map = *m_caster->GetMap();
cell.Visit(p, object_checker, map, *m_caster, m_caster->GetVisibilityRange());
if (!ok)
return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
focusObject = ok; // game object found in range
}
// do not take reagents for these item casts
if (!(m_CastItem && m_CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST))
{
bool checkReagents = !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST) && !p_caster->CanNoReagentCast(m_spellInfo);
// Not own traded item (in trader trade slot) requires reagents even if triggered spell
if (!checkReagents)
if (Item* targetItem = m_targets.GetItemTarget())
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
checkReagents = true;
// check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
if (checkReagents)
{
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++)
{
if (m_spellInfo->Reagent[i] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[i];
uint32 itemcount = m_spellInfo->ReagentCount[i];
// if CastItem is also spell reagent
if (m_CastItem && m_CastItem->GetEntry() == itemid)
{
ItemTemplate const *proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s)
{
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(s);
if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
}
if (!p_caster->HasItemCount(itemid, itemcount))
return SPELL_FAILED_ITEM_NOT_READY; //0x54
}
}
// check totem-item requirements (items presence in inventory)
uint32 totems = 2;
for (int i = 0; i < 2 ; ++i)
{
if (m_spellInfo->Totem[i] != 0)
{
if (p_caster->HasItemCount(m_spellInfo->Totem[i], 1))
{
totems -= 1;
continue;
}
}else
totems -= 1;
}
if (totems != 0)
return SPELL_FAILED_TOTEMS; //0x7C
// Check items for TotemCategory (items presence in inventory)
uint32 TotemCategory = 2;
for (int i= 0; i < 2; ++i)
{
if (m_spellInfo->TotemCategory[i] != 0)
{
if (p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]))
{
TotemCategory -= 1;
continue;
}
}
else
TotemCategory -= 1;
}
if (TotemCategory != 0)
return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
}
// special checks for spell effects
for (int i = 0; i < MAX_SPELL_EFFECTS; i++)
{
switch (m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_CREATE_ITEM_2:
{
if (!IsTriggered() && m_spellInfo->Effects[i].ItemType)
{
ItemPosCountVec dest;
InventoryResult msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
ItemTemplate const *pProto = sObjectMgr->GetItemTemplate(m_spellInfo->Effects[i].ItemType);
// TODO: Needs review
if (pProto && !(pProto->ItemLimitCategory))
{
p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType);
return SPELL_FAILED_DONT_REPORT;
}
else
{
if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000)))
return SPELL_FAILED_TOO_MANY_OF_ITEM;
else if (!(p_caster->HasItemCount(m_spellInfo->Effects[i].ItemType, 1)))
return SPELL_FAILED_TOO_MANY_OF_ITEM;
else
p_caster->CastSpell(m_caster, m_spellInfo->Effects[EFFECT_1].CalcValue(), false); // move this to anywhere
return SPELL_FAILED_DONT_REPORT;
}
}
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM:
if (m_spellInfo->Effects[i].ItemType && m_targets.GetItemTarget()
&& (m_targets.GetItemTarget()->IsWeaponVellum() || m_targets.GetItemTarget()->IsArmorVellum()))
{
// cannot enchant vellum for other player
if (m_targets.GetItemTarget()->GetOwner() != m_caster)
return SPELL_FAILED_NOT_TRADEABLE;
// do not allow to enchant vellum from scroll made by vellum-prevent exploit
if (m_CastItem && m_CastItem->GetTemplate()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)
return SPELL_FAILED_TOTEM_CATEGORY;
ItemPosCountVec dest;
InventoryResult msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->Effects[i].ItemType);
return SPELL_FAILED_DONT_REPORT;
}
}
case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
{
Item* targetItem = m_targets.GetItemTarget();
if (!targetItem)
return SPELL_FAILED_ITEM_NOT_FOUND;
if (targetItem->GetTemplate()->ItemLevel < m_spellInfo->BaseLevel)
return SPELL_FAILED_LOWLEVEL;
bool isItemUsable = false;
for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e)
{
ItemTemplate const *proto = targetItem->GetTemplate();
if (proto->Spells[e].SpellId && (
proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE ||
proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE))
{
isItemUsable = true;
break;
}
}
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->Effects[i].MiscValue);
// do not allow adding usable enchantments to items that have use effect already
if (pEnchant && isItemUsable)
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
if (pEnchant->type[s] == ITEM_ENCHANTMENT_TYPE_USE_SPELL)
return SPELL_FAILED_ON_USE_ENCHANT;
// Not allow enchant in trade slot for some enchant type
if (targetItem->GetOwner() != m_caster)
{
if (!pEnchant)
return SPELL_FAILED_ERROR;
if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
{
Item *item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_ITEM_NOT_FOUND;
// Not allow enchant in trade slot for some enchant type
if (item->GetOwner() != m_caster)
{
uint32 enchant_id = m_spellInfo->Effects[i].MiscValue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return SPELL_FAILED_ERROR;
if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
break;
}
case SPELL_EFFECT_ENCHANT_HELD_ITEM:
// check item existence in effect code (not output errors at offhand hold item effect to main hand for example
break;
case SPELL_EFFECT_DISENCHANT:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_DISENCHANTED;
// prevent disenchanting in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_DISENCHANTED;
ItemTemplate const* itemProto = m_targets.GetItemTarget()->GetTemplate();
if (!itemProto)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
uint32 item_quality = itemProto->Quality;
// 2.0.x addon: Check player enchanting level against the item disenchanting requirements
uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
if (item_disenchantskilllevel == uint32(-1))
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
return SPELL_FAILED_LOW_CASTLEVEL;
if (item_quality > 4 || item_quality < 2)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (!itemProto->DisenchantID)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
break;
}
case SPELL_EFFECT_PROSPECTING:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_PROSPECTED;
//ensure item is a prospectable ore
if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_PROSPECTABLE))
return SPELL_FAILED_CANT_BE_PROSPECTED;
//prevent prospecting in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_PROSPECTED;
//Check for enough skill in jewelcrafting
uint32 item_prospectingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank;
if (item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required ores in inventory
if (m_targets.GetItemTarget()->GetCount() < 5)
return SPELL_FAILED_NEED_MORE_ITEMS;
if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_PROSPECTED;
break;
}
case SPELL_EFFECT_MILLING:
{
if (!m_targets.GetItemTarget())
return SPELL_FAILED_CANT_BE_MILLED;
//ensure item is a millable herb
if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_PROTO_FLAG_MILLABLE))
return SPELL_FAILED_CANT_BE_MILLED;
//prevent milling in trade slot
if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_MILLED;
//Check for enough skill in inscription
uint32 item_millingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank;
if (item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required herbs in inventory
if (m_targets.GetItemTarget()->GetCount() < 5)
return SPELL_FAILED_NEED_MORE_ITEMS;
if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_MILLED;
break;
}
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
if (m_attackType != RANGED_ATTACK)
break;
Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType);
if (!pItem || pItem->IsBroken())
return SPELL_FAILED_EQUIPPED_ITEM;
switch(pItem->GetTemplate()->SubClass)
{
case ITEM_SUBCLASS_WEAPON_THROWN:
{
uint32 ammo = pItem->GetEntry();
if (!m_caster->ToPlayer()->HasItemCount(ammo, 1))
return SPELL_FAILED_NO_AMMO;
}; break;
case ITEM_SUBCLASS_WEAPON_GUN:
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
{
uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID);
if (!ammo)
{
// Requires No Ammo
if (m_caster->HasAura(46699))
break; // skip other checks
return SPELL_FAILED_NO_AMMO;
}
ItemTemplate const *ammoProto = sObjectMgr->GetItemTemplate(ammo);
if (!ammoProto)
return SPELL_FAILED_NO_AMMO;
if (ammoProto->Class != ITEM_CLASS_PROJECTILE)
return SPELL_FAILED_NO_AMMO;
// check ammo ws. weapon compatibility
switch(pItem->GetTemplate()->SubClass)
{
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
if (ammoProto->SubClass != ITEM_SUBCLASS_ARROW)
return SPELL_FAILED_NO_AMMO;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
if (ammoProto->SubClass != ITEM_SUBCLASS_BULLET)
return SPELL_FAILED_NO_AMMO;
break;
default:
return SPELL_FAILED_NO_AMMO;
}
if (!m_caster->ToPlayer()->HasItemCount(ammo, 1))
{
m_caster->ToPlayer()->SetUInt32Value(PLAYER_AMMO_ID, 0);
return SPELL_FAILED_NO_AMMO;
}
}; break;
case ITEM_SUBCLASS_WEAPON_WAND:
break;
default:
break;
}
break;
}
case SPELL_EFFECT_CREATE_MANA_GEM:
{
uint32 item_id = m_spellInfo->Effects[i].ItemType;
ItemTemplate const *pProto = sObjectMgr->GetItemTemplate(item_id);
if (!pProto)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
if (Item* pitem = p_caster->GetItemByEntry(item_id))
{
for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x)
if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
}
break;
}
default:
break;
}
}
// check weapon presence in slots for main/offhand weapons
if (m_spellInfo->EquippedItemClass >=0)
{
// main hand weapon required
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_MAIN_HAND)
{
Item* item = m_caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK);
// skip spell if no weapon in slot or broken
if (!item || item->IsBroken())
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
// skip spell if weapon not fit to triggered spell
if (!item->IsFitToSpellRequirements(m_spellInfo))
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// offhand hand weapon required
if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND)
{
Item* item = m_caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK);
// skip spell if no weapon in slot or broken
if (!item || item->IsBroken())
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
// skip spell if weapon not fit to triggered spell
if (!item->IsFitToSpellRequirements(m_spellInfo))
return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
}
return SPELL_CAST_OK;
}
void Spell::Delayed() // only called in DealDamage()
{
if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER)
return;
//if (m_spellState == SPELL_STATE_DELAYED)
// return; // spell is active and can't be time-backed
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
// spells not loosing casting time (slam, dynamites, bombs..)
//if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
// return;
//check pushback reduce
int32 delaytime = 500; // spellcasting delay is normally 500ms
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPctN(delaytime, -delayReduce);
if (int32(m_timer) + delaytime > m_casttime)
{
delaytime = m_casttime - m_timer;
m_timer = m_casttime;
}
else
m_timer += delaytime;
sLog->outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
data.append(m_caster->GetPackGUID());
data << uint32(delaytime);
m_caster->SendMessageToSet(&data, true);
}
void Spell::DelayedChannel()
{
if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
return;
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
//check pushback reduce
int32 delaytime = CalculatePctN(m_spellInfo->GetDuration(), 25); // channeling delay is normally 25% of its time per hit
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPctN(delaytime, -delayReduce);
if (int32(m_timer) <= delaytime)
{
delaytime = m_timer;
m_timer = 0;
}
else
m_timer -= delaytime;
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime);
// partially interrupt persistent area auras
if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id))
dynObj->Delay(delaytime);
SendChannelUpdate(m_timer);
}
void Spell::UpdatePointers()
{
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld())
m_originalCaster = NULL;
}
if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER)
m_CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID);
m_targets.Update(m_caster);
}
bool Spell::CheckTargetCreatureType(Unit* target) const
{
uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
// Curse of Doom & Exorcism: not find another way to fix spell target check :/
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->Category == 1179)
{
// not allow cast at player
if (target->GetTypeId() == TYPEID_PLAYER)
return false;
spellCreatureTargetMask = 0x7FF;
}
// Dismiss Pet and Taming Lesson skipped
if (m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
spellCreatureTargetMask = 0;
// Polymorph and Grounding Totem
if (target->GetEntry() == 5925 && m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) && m_spellInfo->Effects[0].ApplyAuraName == SPELL_AURA_MOD_CONFUSE)
return true;
if (spellCreatureTargetMask)
{
uint32 TargetCreatureType = target->GetCreatureTypeMask();
return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
}
return true;
}
CurrentSpellTypes Spell::GetCurrentContainer()
{
if (IsNextMeleeSwingSpell())
return(CURRENT_MELEE_SPELL);
else if (IsAutoRepeat())
return(CURRENT_AUTOREPEAT_SPELL);
else if (m_spellInfo->IsChanneled())
return(CURRENT_CHANNELED_SPELL);
else
return(CURRENT_GENERIC_SPELL);
}
bool Spell::CheckTarget(Unit* target, uint32 eff)
{
// Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
if (m_spellInfo->Effects[eff].TargetA.GetTarget() != TARGET_UNIT_CASTER)
{
if (!CheckTargetCreatureType(target))
return false;
}
// Check Aura spell req (need for AoE spells)
if (m_spellInfo->TargetAuraSpell && !target->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->TargetAuraSpell, m_caster)))
return false;
if (m_spellInfo->ExcludeTargetAuraSpell && target->HasAura(sSpellMgr->GetSpellIdForDifficulty(m_spellInfo->ExcludeTargetAuraSpell, m_caster)))
return false;
// Check targets for not_selectable unit flag and remove
// A player can cast spells on his pet (or other controlled unit) though in any state
if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
{
// any unattackable target skipped
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
return false;
// unselectable targets skipped in all cases except TARGET_UNIT_NEARBY_ENTRY targeting
// in case TARGET_UNIT_NEARBY_ENTRY target selected by server always and can't be cheated
/*if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_NEARBY_ENTRY &&
m_spellInfo->EffectImplicitTargetB[eff] != TARGET_UNIT_NEARBY_ENTRY)
return false;*/
}
//Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
if (target != m_caster && target->GetTypeId() == TYPEID_PLAYER)
{
if (!target->ToPlayer()->IsVisible())
return false;
if (target->ToPlayer()->isGameMaster() && !m_spellInfo->IsPositive())
return false;
}
switch(m_spellInfo->Effects[eff].ApplyAuraName)
{
case SPELL_AURA_NONE:
default:
break;
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_MOD_POSSESS_PET:
case SPELL_AURA_AOE_CHARM:
if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
return false;
if (target->IsMounted())
return false;
if (target->GetCharmerGUID())
return false;
if (int32 damage = CalculateDamage(eff, target))
if ((int32)target->getLevel() > damage)
return false;
break;
}
//Do not do further checks for triggered spells
if (IsTriggered())
return true;
//Check targets for LOS visibility (except spells without range limitations)
switch(m_spellInfo->Effects[eff].Effect)
{
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
break;
case SPELL_EFFECT_DUMMY:
if (m_spellInfo->Id != 20577) // Cannibalize
break;
//fall through
case SPELL_EFFECT_RESURRECT_NEW:
// player far away, maybe his corpse near?
if (target != m_caster && !target->IsWithinLOSInMap(m_caster))
{
if (!m_targets.GetCorpseTargetGUID())
return false;
Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID());
if (!corpse)
return false;
if (target->GetGUID() != corpse->GetOwnerGUID())
return false;
if (!corpse->IsWithinLOSInMap(m_caster))
return false;
}
// all ok by some way or another, skip normal check
break;
default: // normal case
// Get GO cast coordinates if original caster -> GO
WorldObject *caster = NULL;
if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
if (!caster)
caster = m_caster;
if (target->GetEntry() == 5925)
return true;
if (target != m_caster && !target->IsWithinLOSInMap(caster))
return false;
break;
}
return true;
}
bool Spell::IsNextMeleeSwingSpell() const
{
return m_spellInfo->Attributes & SPELL_ATTR0_ON_NEXT_SWING;
}
bool Spell::IsAutoActionResetSpell() const
{
return !IsTriggered() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_AUTOATTACK);
}
bool Spell::IsNeedSendToClient() const
{
return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || m_spellInfo->IsChanneled() ||
m_spellInfo->Speed > 0.0f || (!m_triggeredByAuraSpell && !IsTriggered());
}
bool Spell::HaveTargetsForEffect(uint8 effect) const
{
for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
return false;
}
SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
{
m_Spell = spell;
}
SpellEvent::~SpellEvent()
{
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
if (m_Spell->IsDeletable())
{
delete m_Spell;
}
else
{
sLog->outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
(m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
ASSERT(false);
}
}
bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
{
// update spell if it is not finished
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->update(p_time);
// check spell state to process
switch (m_Spell->getState())
{
case SPELL_STATE_FINISHED:
{
// spell was finished, check deletable state
if (m_Spell->IsDeletable())
{
// check, if we do have unfinished triggered spells
return true; // spell is deletable, finish event
}
// event will be re-added automatically at the end of routine)
} break;
case SPELL_STATE_DELAYED:
{
// first, check, if we have just started
if (m_Spell->GetDelayStart() != 0)
{
// no, we aren't, do the typical update
// check, if we have channeled spell on our hands
/*
if (IsChanneledSpell(m_Spell->m_spellInfo))
{
// evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
// check, if we have casting anything else except this channeled spell and autorepeat
if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
{
// another non-melee non-delayed spell is casted now, abort
m_Spell->cancel();
}
else
{
// Set last not triggered spell for apply spellmods
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true);
// do the action (pass spell to channeling state)
m_Spell->handle_immediate();
// And remove after effect handling
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false);
}
// event will be re-added automatically at the end of routine)
}
else
*/
{
// run the spell handler and think about what we can do next
uint64 t_offset = e_time - m_Spell->GetDelayStart();
uint64 n_offset = m_Spell->handle_delayed(t_offset);
if (n_offset)
{
// re-add us to the queue
m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
return false; // event not complete
}
// event complete
// finish update event will be re-added automatically at the end of routine)
}
}
else
{
// delaying had just started, record the moment
m_Spell->SetDelayStart(e_time);
// re-plan the event for the delay moment
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
return false; // event not complete
}
} break;
default:
{
// all other states
// event will be re-added automatically at the end of routine)
} break;
}
// spell processing not complete, plan event on the next update interval
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
return false; // event not complete
}
void SpellEvent::Abort(uint64 /*e_time*/)
{
// oops, the spell we try to do is aborted
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
}
bool SpellEvent::IsDeletable() const
{
return m_Spell->IsDeletable();
}
bool Spell::IsValidSingleTargetEffect(Unit const* target, Targets type) const
{
switch (type)
{
case TARGET_UNIT_TARGET_ENEMY:
return !m_caster->IsFriendlyTo(target);
case TARGET_UNIT_TARGET_ALLY:
case TARGET_UNIT_TARGET_ALLY_PARTY:
return m_caster->IsFriendlyTo(target);
case TARGET_UNIT_TARGET_PARTY:
return m_caster != target && m_caster->IsInPartyWith(target);
case TARGET_UNIT_TARGET_RAID:
return m_caster->IsInRaidWith(target);
case TARGET_UNIT_TARGET_MINIPET:
return target->GetGUID() == m_caster->GetCritterGUID();
default:
break;
}
return true;
}
bool Spell::IsValidSingleTargetSpell(Unit const* target) const
{
if (target->GetMapId() == MAPID_INVALID)
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::IsValidSingleTargetSpell - a spell was cast on '%s' (GUIDLow: %u), but they have an invalid map id!", target->GetName(), target->GetGUIDLow());
return false;
}
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!IsValidSingleTargetEffect(target, m_spellInfo->Effects[i].TargetA.GetTarget()))
return false;
// Need to check B?
//if (!IsValidSingleTargetEffect(m_spellInfo->Effects[i].TargetB, target)
// return false;
}
return true;
}
bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const
{
if (target->isAlive())
return !m_spellInfo->IsRequiringDeadTarget();
if (m_spellInfo->IsAllowingDeadTarget())
return true;
return false;
}
void Spell::CalculateDamageDoneForAllTargets()
{
float multiplier[MAX_SPELL_EFFECTS];
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (m_applyMultiplierMask & (1 << i))
multiplier[i] = m_spellInfo->Effects[i].CalcDamageMultiplier(m_originalCaster, this);
bool usesAmmo = true;
Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_CONSUME_NO_AMMO);
for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
{
if ((*j)->IsAffectedOnSpell(m_spellInfo))
usesAmmo=false;
}
for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
TargetInfo &target = *ihit;
uint32 mask = target.effectMask;
if (!mask)
continue;
Unit* unit = m_caster->GetGUID() == target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID);
if (!unit) // || !unit->isAlive()) do we need to check alive here?
continue;
if (usesAmmo)
{
bool ammoTaken = false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (!(mask & 1<<i))
continue;
switch (m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
ammoTaken=true;
TakeAmmo();
}
if (ammoTaken)
break;
}
}
if (target.missCondition == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
{
target.damage += CalculateDamageDone(unit, mask, multiplier);
target.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType);
}
else if (target.missCondition == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
{
if (target.reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
{
target.damage += CalculateDamageDone(m_caster, mask, multiplier);
target.crit = m_caster->isSpellCrit(m_caster, m_spellInfo, m_spellSchoolMask, m_attackType);
}
}
}
}
int32 Spell::CalculateDamageDone(Unit *unit, const uint32 effectMask, float * multiplier)
{
int32 damageDone = 0;
unitTarget = unit;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (effectMask & (1<<i))
{
m_damage = 0;
damage = CalculateDamage(i, NULL);
switch(m_spellInfo->Effects[i].Effect)
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
SpellDamageSchoolDmg((SpellEffIndex)i);
break;
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
SpellDamageWeaponDmg((SpellEffIndex)i);
break;
case SPELL_EFFECT_HEAL:
SpellDamageHeal((SpellEffIndex)i);
break;
}
if (m_damage > 0)
{
if (m_spellInfo->Effects[i].IsArea())
{
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
uint32 targetAmount = m_UniqueTargetInfo.size();
if (targetAmount > 10)
m_damage = m_damage * 10/targetAmount;
}
}
}
if (m_applyMultiplierMask & (1 << i))
{
m_damage = int32(m_damage * m_damageMultipliers[i]);
m_damageMultipliers[i] *= multiplier[i];
}
damageDone += m_damage;
}
}
return damageDone;
}
SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
{
if (!lockId) // possible case for GO and maybe for items.
return SPELL_CAST_OK;
// Get LockInfo
LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
if (!lockInfo)
return SPELL_FAILED_BAD_TARGETS;
bool reqKey = false; // some locks not have reqs
for (int j = 0; j < MAX_LOCK_CASE; ++j)
{
switch(lockInfo->Type[j])
{
// check key item (many fit cases can be)
case LOCK_KEY_ITEM:
if (lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry() == lockInfo->Index[j])
return SPELL_CAST_OK;
reqKey = true;
break;
// check key skill (only single first fit case can be)
case LOCK_KEY_SKILL:
{
reqKey = true;
// wrong locktype, skip
if (uint32(m_spellInfo->Effects[effIndex].MiscValue) != lockInfo->Index[j])
continue;
skillId = SkillByLockType(LockType(lockInfo->Index[j]));
if (skillId != SKILL_NONE)
{
reqSkillValue = lockInfo->Skill[j];
// castitem check: rogue using skeleton keys. the skill values should not be added in this case.
skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
0 : m_caster->ToPlayer()->GetSkillValue(skillId);
// skill bonus provided by casting spell (mostly item spells)
// add the damage modifier from the spell casted (cheat lock / skeleton key etc.)
if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM)
skillValue += uint32(CalculateDamage(effIndex, NULL));
if (skillValue < reqSkillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
}
return SPELL_CAST_OK;
}
}
}
if (reqKey)
return SPELL_FAILED_BAD_TARGETS;
return SPELL_CAST_OK;
}
void Spell::SetSpellValue(SpellValueMod mod, int32 value)
{
switch (mod)
{
case SPELLVALUE_BASE_POINT0:
m_spellValue->EffectBasePoints[0] = m_spellInfo->Effects[EFFECT_0].CalcBaseValue(value);
break;
case SPELLVALUE_BASE_POINT1:
m_spellValue->EffectBasePoints[1] = m_spellInfo->Effects[EFFECT_1].CalcBaseValue(value);
break;
case SPELLVALUE_BASE_POINT2:
m_spellValue->EffectBasePoints[2] = m_spellInfo->Effects[EFFECT_2].CalcBaseValue(value);
break;
case SPELLVALUE_RADIUS_MOD:
m_spellValue->RadiusMod = (float)value / 10000;
break;
case SPELLVALUE_MAX_TARGETS:
m_spellValue->MaxAffectedTargets = (uint32)value;
break;
case SPELLVALUE_AURA_STACK:
m_spellValue->AuraStackAmount = uint8(value);
break;
}
}
float tangent(float x)
{
x = tan(x);
//if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x;
//if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max();
//if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max();
if (x < 100000.0f && x > -100000.0f) return x;
if (x >= 100000.0f) return 100000.0f;
if (x <= 100000.0f) return -100000.0f;
return 0.0f;
}
#define DEBUG_TRAJ(a) //a
void Spell::SelectTrajTargets()
{
if (!m_targets.HasTraj())
return;
float dist2d = m_targets.GetDist2d();
if (!dist2d)
return;
float dz = m_targets.GetDst()->m_positionZ - m_targets.GetSrc()->m_positionZ;
UnitList unitList;
SearchAreaTarget(unitList, dist2d, PUSH_IN_THIN_LINE, SPELL_TARGETS_ANY);
if (unitList.empty())
return;
unitList.sort(Trinity::ObjectDistanceOrderPred(m_caster));
float b = tangent(m_targets.GetElevation());
float a = (dz - dist2d * b) / (dist2d * dist2d);
if (a > -0.0001f) a = 0;
DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);)
float bestDist = m_spellInfo->GetMaxRange(false);
UnitList::const_iterator itr = unitList.begin();
for (; itr != unitList.end(); ++itr)
{
if (m_caster == *itr || m_caster->IsOnVehicle(*itr) || (*itr)->GetVehicle())//(*itr)->IsOnVehicle(m_caster))
continue;
const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3)
// TODO: all calculation should be based on src instead of m_caster
const float objDist2d = m_targets.GetSrc()->GetExactDist2d(*itr) * cos(m_targets.GetSrc()->GetRelativeAngle(*itr));
const float dz = (*itr)->GetPositionZ() - m_targets.GetSrc()->m_positionZ;
DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);)
float dist = objDist2d - size;
float height = dist * (a * dist + b);
DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)
if (dist < bestDist && height < dz + size && height > dz - size)
{
bestDist = dist > 0 ? dist : 0;
break;
}
#define CHECK_DIST {\
DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\
if (dist > bestDist) continue;\
if (dist < objDist2d + size && dist > objDist2d - size) { bestDist = dist; break; }\
}
if (!a)
{
height = dz - size;
dist = height / b;
CHECK_DIST;
height = dz + size;
dist = height / b;
CHECK_DIST;
continue;
}
height = dz - size;
float sqrt1 = b * b + 4 * a * height;
if (sqrt1 > 0)
{
sqrt1 = sqrt(sqrt1);
dist = (sqrt1 - b) / (2 * a);
CHECK_DIST;
}
height = dz + size;
float sqrt2 = b * b + 4 * a * height;
if (sqrt2 > 0)
{
sqrt2 = sqrt(sqrt2);
dist = (sqrt2 - b) / (2 * a);
CHECK_DIST;
dist = (-sqrt2 - b) / (2 * a);
CHECK_DIST;
}
if (sqrt1 > 0)
{
dist = (-sqrt1 - b) / (2 * a);
CHECK_DIST;
}
}
if (m_targets.GetSrc()->GetExactDist2d(m_targets.GetDst()) > bestDist)
{
float x = m_targets.GetSrc()->m_positionX + cos(m_caster->GetOrientation()) * bestDist;
float y = m_targets.GetSrc()->m_positionY + sin(m_caster->GetOrientation()) * bestDist;
float z = m_targets.GetSrc()->m_positionZ + bestDist * (a * bestDist + b);
if (itr != unitList.end())
{
float distSq = (*itr)->GetExactDistSq(x, y, z);
float sizeSq = (*itr)->GetObjectSize();
sizeSq *= sizeSq;
DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
if (distSq > sizeSq)
{
float factor = 1 - sqrt(sizeSq / distSq);
x += factor * ((*itr)->GetPositionX() - x);
y += factor * ((*itr)->GetPositionY() - y);
z += factor * ((*itr)->GetPositionZ() - z);
distSq = (*itr)->GetExactDistSq(x, y, z);
DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
}
}
Position trajDst;
trajDst.Relocate(x, y, z, m_caster->GetOrientation());
m_targets.ModDst(trajDst);
}
}
void Spell::PrepareTargetProcessing()
{
CheckEffectExecuteData();
}
void Spell::FinishTargetProcessing()
{
SendLogExecute();
}
void Spell::InitEffectExecuteData(uint8 effIndex)
{
ASSERT(effIndex < MAX_SPELL_EFFECTS);
if (!m_effectExecuteData[effIndex])
{
m_effectExecuteData[effIndex] = new ByteBuffer(0x20);
// first dword - target counter
*m_effectExecuteData[effIndex] << uint32(1);
}
else
{
// increase target counter by one
uint32 count = (*m_effectExecuteData[effIndex]).read<uint32>(0);
(*m_effectExecuteData[effIndex]).put<uint32>(0, ++count);
}
}
void Spell::CleanupEffectExecuteData()
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
m_effectExecuteData[i] = NULL;
}
void Spell::CheckEffectExecuteData()
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
ASSERT(!m_effectExecuteData[i]);
}
void Spell::LoadScripts()
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell::LoadScripts");
sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts);
for (std::list<SpellScript *>::iterator itr = m_loadedScripts.begin(); itr != m_loadedScripts.end() ;)
{
if (!(*itr)->_Load(this))
{
std::list<SpellScript *>::iterator bitr = itr;
++itr;
m_loadedScripts.erase(bitr);
continue;
}
(*itr)->Register();
++itr;
}
}
void Spell::PrepareScriptHitHandlers()
{
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
(*scritr)->_InitHit();
}
SpellCastResult Spell::CallScriptCheckCastHandlers()
{
SpellCastResult retVal = SPELL_CAST_OK;
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CHECK_CAST);
std::list<SpellScript::CheckCastHandler>::iterator hookItrEnd = (*scritr)->OnCheckCast.end(), hookItr = (*scritr)->OnCheckCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
{
SpellCastResult tempResult = (*hookItr).Call(*scritr);
if (retVal == SPELL_CAST_OK)
retVal = tempResult;
}
(*scritr)->_FinishScriptCall();
}
return retVal;
}
bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex)
{
// execute script effect handler hooks and check if effects was prevented
bool preventDefault = false;
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_EFFECT);
std::list<SpellScript::EffectHandler>::iterator effEndItr = (*scritr)->OnEffect.end(), effItr = (*scritr)->OnEffect.begin();
for (; effItr != effEndItr ; ++effItr)
// effect execution can be prevented
if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex))
(*effItr).Call(*scritr, effIndex);
if (!preventDefault)
preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex);
(*scritr)->_FinishScriptCall();
}
return preventDefault;
}
void Spell::CallScriptBeforeHitHandlers()
{
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin();
for (; hookItr != hookItrEnd ; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnHitHandlers()
{
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin();
for (; hookItr != hookItrEnd ; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterHitHandlers()
{
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT);
std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin();
for (; hookItr != hookItrEnd ; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterUnitTargetSelectHandlers(std::list<Unit*>& unitTargets, SpellEffIndex effIndex)
{
for (std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_UNIT_TARGET_SELECT);
std::list<SpellScript::UnitTargetHandler>::iterator hookItrEnd = (*scritr)->OnUnitTargetSelect.end(), hookItr = (*scritr)->OnUnitTargetSelect.begin();
for (; hookItr != hookItrEnd ; ++hookItr)
if ((*hookItr).IsEffectAffected(m_spellInfo, effIndex))
(*hookItr).Call(*scritr, unitTargets);
(*scritr)->_FinishScriptCall();
}
}
bool Spell::CanExecuteTriggersOnHit(uint8 effMask) const
{
// check which effects can trigger proc
// don't allow to proc for dummy-only spell target hits
// prevents triggering/procing effects twice from spells like Eviscerate
for (uint8 i = 0;effMask && i < MAX_SPELL_EFFECTS; ++i)
{
if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_DUMMY)
effMask &= ~(1<<i);
}
return effMask;
}
void Spell::PrepareTriggersExecutedOnHit()
{
// todo: move this to scripts
if (m_spellInfo->SpellFamilyName)
{
SpellInfo const* excludeCasterSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeCasterAuraSpell);
if (excludeCasterSpellInfo && !excludeCasterSpellInfo->IsPositive())
m_preCastSpell = m_spellInfo->ExcludeCasterAuraSpell;
SpellInfo const* excludeTargetSpellInfo = sSpellMgr->GetSpellInfo(m_spellInfo->ExcludeTargetAuraSpell);
if (excludeTargetSpellInfo && !excludeTargetSpellInfo->IsPositive())
m_preCastSpell = m_spellInfo->ExcludeTargetAuraSpell;
}
// todo: move this to scripts
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
m_preCastSpell = 11196; // Recently Bandaged
break;
}
case SPELLFAMILY_MAGE:
{
// Permafrost
if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220)
m_preCastSpell = 68391;
break;
}
}
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras:
// save auras which were present on spell caster on cast, to prevent triggered auras from affecting caster
// and to correctly calculate proc chance when combopoints are present
Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER);
for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
{
if (!(*i)->IsAffectedOnSpell(m_spellInfo))
continue;
SpellInfo const *auraSpellInfo = (*i)->GetSpellInfo();
uint32 auraSpellIdx = (*i)->GetEffIndex();
if (SpellInfo const *spellInfo = sSpellMgr->GetSpellInfo(auraSpellInfo->Effects[auraSpellIdx].TriggerSpell))
{
// calculate the chance using spell base amount, because aura amount is not updated on combo-points change
// this possibly needs fixing
int32 auraBaseAmount = (*i)->GetBaseAmount();
int32 chance = m_caster->CalculateSpellDamage(NULL, auraSpellInfo, auraSpellIdx, &auraBaseAmount);
// proc chance is stored in effect amount
m_hitTriggerSpells.push_back(std::make_pair(spellInfo, chance * (*i)->GetBase()->GetStackAmount()));
}
}
}
// Global cooldowns management
enum GCDLimits
{
MIN_GCD = 1000,
MAX_GCD = 1500
};
bool Spell::HasGlobalCooldown()
{
// Only player or controlled units have global cooldown
if (m_caster->GetCharmInfo())
return m_caster->GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
return m_caster->ToPlayer()->GetGlobalCooldownMgr().HasGlobalCooldown(m_spellInfo);
else
return false;
}
void Spell::TriggerGlobalCooldown()
{
int32 gcd = m_spellInfo->StartRecoveryTime;
if (!gcd)
return;
// Global cooldown can't leave range 1..1.5 secs
// There are some spells (mostly not casted directly by player) that have < 1 sec and > 1.5 sec global cooldowns
// but as tests show are not affected by any spell mods.
if (m_spellInfo->StartRecoveryTime >= MIN_GCD && m_spellInfo->StartRecoveryTime <= MAX_GCD)
{
// gcd modifier auras are applied only to own spells and only players have such mods
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this);
// Apply haste rating
gcd = int32(float(gcd) * m_caster->GetFloatValue(UNIT_MOD_CAST_SPEED));
if (gcd < MIN_GCD)
gcd = MIN_GCD;
else if (gcd > MAX_GCD)
gcd = MAX_GCD;
}
// Only players or controlled units have global cooldown
if (m_caster->GetCharmInfo())
m_caster->GetCharmInfo()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd);
}
void Spell::CancelGlobalCooldown()
{
if (!m_spellInfo->StartRecoveryTime)
return;
// Cancel global cooldown when interrupting current cast
if (m_caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) != this)
return;
// Only players or controlled units have global cooldown
if (m_caster->GetCharmInfo())
m_caster->GetCharmInfo()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo);
else if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo);
}
| gpl-2.0 |
kunik-ru/UCT | src/main/java/ru/kunik/uct/horner/HornerCalculator.java | 6608 | package ru.kunik.uct.horner;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.math.Fraction;
import ru.kunik.uct.gui.HornerGUI;
import ru.kunik.uct.util.Filters;
public class HornerCalculator implements Runnable {
private String str;
private final HornerGUI horner;
public HornerCalculator(HornerGUI horner, String str) {
this.horner = horner;
this.str = str;
}
public void run() {
HornerHandler.hornerMultipliers.clear();
String replaced = str.replace(" ", "");
String[] splited = replaced.split(",");
for (String strSpl : splited) {
if (Filters.isDouble(strSpl)) {
HornerHandler.hornerMultipliers.add(Double.parseDouble(strSpl));
}
else {
this.horner.setInfo("Неверные входные данные");
this.horner.getHandler().getLogger().writeLog("Неверные входные данные" + ": " + str);
return;
}
}
int total = HornerHandler.hornerMultipliers.size();
StringBuilder strBuilder = new StringBuilder("<html>");
Iterator iter = HornerHandler.hornerMultipliers.listIterator();
boolean flagFirst = true;
while (iter.hasNext()) {
total -= 1;
double i = ((Double) iter.next()).doubleValue();
if (flagFirst && i < 0) {
strBuilder.append("-");
}
if (i >= 0) {
strBuilder.append("+");
}
strBuilder.append(i);
if (total >= 1) strBuilder.append("x");
strBuilder.append("<sup>");
if (total > 1) strBuilder.append(total);
strBuilder.append("</sup>");
}
strBuilder.append("</html>");
this.horner.setEquation(strBuilder.deleteCharAt(6).toString());
StringBuilder strAns = new StringBuilder();
HornerHandler.hornerAnswer.clear();
calculateHorner(HornerHandler.hornerMultipliers);
for (double d : HornerHandler.hornerAnswer) {
if (d != ((Double)d).intValue()) {
int numerator = Fraction.getFraction(d).getNumerator();
int denominator = Fraction.getFraction(d).getDenominator();
strAns.append(numerator);
strAns.append("/");
strAns.append(denominator);
}
else {
strAns.append(d);
}
strAns.append(", ");
}
this.horner.setInfo("Вычислено");
if (!strAns.toString().isEmpty()) {
strAns.deleteCharAt(strAns.toString().length() - 1);
strAns.deleteCharAt(strAns.toString().length() - 1);
this.horner.setAnswer(strAns.toString());
this.horner.getHandler().getLogger().writeLog("Для введенных коэффициентов уравнения: " + this.str + " корни:");
this.horner.getHandler().getLogger().writeLog(strAns.toString());
}
else {
this.horner.setAnswer("Корней не найдено");
this.horner.getHandler().getLogger().writeLog("Корней не найдено");
}
}
public static void calculateHorner(List<Double> lst) {
List<Double> timedMult = new LinkedList<Double>();
double start = lst.get(lst.size() - 1);
List<Double> hornerDividers = calculateRationalDividersArray(start, lst.get(0));
Iterator iterDiv = hornerDividers.listIterator();
while (iterDiv.hasNext()) {
double div = (Double) iterDiv.next();
Iterator iterMult = lst.listIterator();
double mult = ((Double) iterMult.next());
timedMult.clear();
while (iterMult.hasNext()) {
timedMult.add(mult);
mult = (div * mult) + ((Double) iterMult.next());
}
if (mult == 0.0D) {
if (!HornerHandler.hornerAnswer.contains(div)) HornerHandler.hornerAnswer.add(div);
if (lst.size() == 3) addQuadraticRadixes(lst, HornerHandler.hornerAnswer);
if (timedMult.size() == 3) addQuadraticRadixes(timedMult, HornerHandler.hornerAnswer);
calculateHorner(timedMult);
}
}
}
/**
* Old method
*
private static List<Double> calculateRationalDividersArray(double num) {
List<Double> hornerDividers = new ArrayList<Double>();
num = Math.abs(num);
double iter = 1.0D;
while (iter <= num) {
if (num % iter == 0) hornerDividers.add(iter);
iter++;
}
List<Double> timedList = new ArrayList<Double>();
Iterator divIter = hornerDividers.listIterator();
while(divIter.hasNext()) {
double d = (Double) divIter.next();
timedList.add(- d);
if (d != 1) {
timedList.add(1 / d);
timedList.add(- 1 / d);
}
}
hornerDividers.addAll(timedList);
return hornerDividers;
}
*/
private static List<Double> calculateIntegerDividersArray(double num) {
List<Double> hornerDividers = new ArrayList<Double>();
num = Math.abs(num);
for (double iter = (-num); iter <= num; iter++) {
if (num % iter == 0) hornerDividers.add(iter);
}
return hornerDividers;
}
private static List<Double> calculateRationalDividersArray(double num, double den) {
List<Double> hornerDividers = new ArrayList<Double>();
double preAns;
for (double dNum : calculateIntegerDividersArray(num)) {
for (double dDen : calculateIntegerDividersArray(den)) {
preAns = dNum / dDen;
if (!hornerDividers.contains(preAns)) {
hornerDividers.add(preAns);
}
}
}
return hornerDividers;
}
public static void addQuadraticRadixes(List<Double> timedMult, List<Double> ans) {
double d = Math.pow(timedMult.get(1), 2) - 4 * timedMult.get(0) * timedMult.get(2);
if (d >= 0) {
double rd = (-timedMult.get(1) + Math.sqrt(d))/(2 * timedMult.get(0));
if (!ans.contains(rd)) ans.add(rd);
rd = (-timedMult.get(1) - Math.sqrt(d))/(2 * timedMult.get(0));
if (!ans.contains(rd)) ans.add(rd);
}
}
}
| gpl-2.0 |
taconaut/pms-mlx | core/src/main/java/net/pms/medialibrary/commons/dataobjects/comboboxitems/ScreeResolutionCBItem.java | 2280 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2012 Ph.Waeber
*
* 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; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.medialibrary.commons.dataobjects.comboboxitems;
import net.pms.medialibrary.commons.enumarations.ScreenResolution;
public class ScreeResolutionCBItem implements Comparable<ScreeResolutionCBItem>{
private ScreenResolution screenResolution;
private String displayName;
public ScreeResolutionCBItem(ScreenResolution autoFolderProperty, String displayName){
this.setScreenResolution(autoFolderProperty);
this.setDisplayName(displayName);
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public void setScreenResolution(ScreenResolution screenResolution) {
this.screenResolution = screenResolution;
}
public ScreenResolution getScreenResolution() {
return screenResolution;
}
@Override
public String toString(){
return getDisplayName();
}
@Override
public boolean equals(Object o){
if(!(o instanceof ScreeResolutionCBItem)){
return false;
}
ScreeResolutionCBItem compObj = (ScreeResolutionCBItem)o;
if(getDisplayName() == compObj.getDisplayName()
&& getScreenResolution() == compObj.getScreenResolution()){
return true;
}
return false;
}
@Override
public int hashCode(){
int hashCode = 24 + getDisplayName().hashCode();
hashCode *= 24 + getScreenResolution().hashCode();
return hashCode;
}
@Override
public int compareTo(ScreeResolutionCBItem o) {
return getDisplayName().compareTo(o.getDisplayName());
}
}
| gpl-2.0 |
artbeatads/messermeister_ab_rackservers | plugins/content/sigplus/engines/captions.boxplus.caption.php | 3001 | <?php
/**
* @file
* @brief sigplus Image Gallery Plus boxplus mouse-over caption engine
* @author Levente Hunyadi
* @version 1.4.2
* @remarks Copyright (C) 2009-2011 Levente Hunyadi
* @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
* @see http://hunyadi.info.hu/projects/sigplus
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
require_once JPATH_PLUGINS.DIRECTORY_SEPARATOR.'content'.DIRECTORY_SEPARATOR.'sigplus'.DIRECTORY_SEPARATOR.'params.php';
/**
* Support class for jQuery-based boxplus mouse-over caption engine.
* @see http://hunyadi.info.hu/projects/boxplus/
*/
class SIGPlusBoxPlusCaptionEngine extends SIGPlusCaptionsEngine {
public function getIdentifier() {
return 'boxplus.caption';
}
public function addStyles() {
$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base(true).'/plugins/content/sigplus/engines/boxplus/caption/css/'.$this->getStyleFilename());
// include style sheet in HTML head section to target Internet Explorer
$this->addCustomTag('<!--[if lt IE 9]><link rel="stylesheet" href="'.JURI::base(true).'/plugins/content/sigplus/engines/boxplus/caption/css/boxplus.caption.ie8.css" type="text/css" /><![endif]-->');
$this->addCustomTag('<!--[if lt IE 8]><link rel="stylesheet" href="'.JURI::base(true).'/plugins/content/sigplus/engines/boxplus/caption/css/boxplus.caption.ie7.css" type="text/css" /><![endif]-->');
}
public function addScripts($id, $params) {
$this->addJQuery();
$this->addScript('/plugins/content/sigplus/engines/boxplus/caption/js/'.$this->getScriptFilename());
$this->addScript('/plugins/content/sigplus/engines/boxplus/lang/'.$this->getScriptFilename('boxplus.lang'));
$engineservices = SIGPlusEngineServices::instance();
if ($params->metadata) {
$metadatabox = $engineservices->getMetadataEngine($params->lightbox);
if ($metadatabox) {
$metadatabox->addStyles();
$metadatafun = $metadatabox->getMetadataFunction();
}
}
$language = JFactory::getLanguage();
list($lang, $country) = explode('-', $language->getTag());
$script =
'__jQuery__("#'.$id.'").boxplusCaptionGallery(__jQuery__.extend('.$this->getCustomParameters($params).', { '.
'position:'.($params->imagecaptions != 'overlay' ? '"figure"' : '"overlay"').', '.
'caption:function (image) { var c = __jQuery__("#" + image.attr("id") + "_caption"); return c.size() ? c.html() : image.attr("alt"); }, '.
'download:'.($params->download ? 'function (image) { var d = __jQuery__("#" + image.attr("id") + "_metadata a[rel=download]"); return d.size() ? d.attr("href") : false; }' : 'false').', '.
'metadata:'.(isset($metadatafun) ? 'function (image) { var m = __jQuery__("#" + image.attr("id") + "_iptc"); return m.size() ? m : false; }' : 'false').', '.
'dialog:'.(isset($metadatafun) ? $metadatafun : 'false').
' })); '.
'__jQuery__.boxplusLanguage("'.$lang.'", "'.$country.'");';
$this->addOnReadyScript($script);
}
} | gpl-2.0 |
liberator44/kindle-publish | kernel/classes/packagecreators/ezcontentobject/ezcontentobjectpackagecreator.php | 12893 | <?php
//
// Definition of eZContentObjectPackageCreator class
//
// Created on: <09-Mar-2004 12:39:59 kk>
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Publish
// SOFTWARE RELEASE: 4.4.0
// COPYRIGHT NOTICE: Copyright (C) 1999-2010 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// 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 version 2.0 of the GNU General
// Public License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
/*! \file
*/
/*!
\ingroup package
\class eZContentObjectPackageCreator ezcontentclasspackagecreator.php
\brief A package creator for content objects
*/
class eZContentObjectPackageCreator extends eZPackageCreationHandler
{
function eZContentObjectPackageCreator( $id )
{
$steps = array();
$steps[] = array( 'id' => 'object',
'name' => ezpI18n::tr( 'kernel/package', 'Content objects to include' ),
'methods' => array( 'initialize' => 'initializeObjectList',
'load' => 'loadObjectList',
'validate' => 'validateObjectList' ),
'template' => 'object_select.tpl' );
$steps[] = array( 'id' => 'object_limits',
'name' => ezpI18n::tr( 'kernel/package', 'Content object limits' ),
'methods' => array( 'initialize' => 'initializeObjectLimits',
'load' => 'loadObjectLimits',
'validate' => 'validateObjectLimits' ),
'template' => 'object_limit.tpl' );
$steps[] = $this->packageInformationStep();
$steps[] = $this->packageMaintainerStep();
$steps[] = $this->packageChangelogStep();
$this->eZPackageCreationHandler( $id,
ezpI18n::tr( 'kernel/package', 'Content object export' ),
$steps );
}
/*!
Creates the package and adds the selected content classes.
*/
function finalize( &$package, $http, &$persistentData )
{
$this->createPackage( $package, $http, $persistentData, $cleanupFiles );
$objectHandler = eZPackage::packageHandler( 'ezcontentobject' );
$nodeList = $persistentData['node_list'];
$options = $persistentData['object_options'];
foreach( $nodeList as $nodeInfo )
{
$objectHandler->addNode( $nodeInfo['id'], $nodeInfo['type'] == 'subtree' );
}
$objectHandler->generatePackage( $package, $options );
$package->setAttribute( 'is_active', true );
$package->store();
}
/*!
Returns \c 'stable', content class packages are always stable.
*/
function packageInitialState( $package, &$persistentData )
{
return 'stable';
}
/*!
\return \c 'contentclass'.
*/
function packageType( $package, &$persistentData )
{
return 'contentobject';
}
function initializeObjectList( $package, $http, $step, &$persistentData, $tpl )
{
$persistentData['node_list'] = array();
}
function loadObjectList( $package, $http, $step, &$persistentData, $tpl, &$module )
{
if ( $http->hasPostVariable( 'AddSubtree' ) )
{
eZContentBrowse::browse( array( 'action_name' => 'FindLimitationSubtree',
'description_template' => 'design:package/creators/ezcontentobject/browse_subtree.tpl',
'from_page' => '/package/create',
'persistent_data' => array( 'PackageStep' => $http->postVariable( 'PackageStep' ),
'CreatorItemID' => $http->postVariable( 'CreatorItemID' ),
'CreatorStepID' => $http->postVariable( 'CreatorStepID' ),
'Subtree' => 1 ) ),
$module );
}
else if ( $http->hasPostVariable( 'AddNode' ) )
{
eZContentBrowse::browse( array( 'action_name' => 'FindLimitationNode',
'description_template' => 'design:package/creators/ezcontentobject/browse_node.tpl',
'from_page' => '/package/create',
'persistent_data' => array( 'PackageStep' => $http->postVariable( 'PackageStep' ),
'CreatorItemID' => $http->postVariable( 'CreatorItemID' ),
'CreatorStepID' => $http->postVariable( 'CreatorStepID' ),
'Node' => 1) ),
$module );
}
else if( $http->hasPostVariable( 'RemoveSelected' ) )
{
foreach ( array_keys( $persistentData['node_list'] ) as $key )
{
if ( in_array( $persistentData['node_list'][$key]['id'], $http->postVariable( 'DeleteIDArray' ) ) )
{
unset( $persistentData['node_list'][$key] );
}
}
}
else if( $http->hasPostVariable( 'SelectedNodeIDArray' ) && !$http->hasPostVariable( 'BrowseCancelButton' ) )
{
if ( $http->hasPostVariable( 'Subtree' ) &&
$http->hasPostVariable( 'Subtree' ) == 1 )
{
foreach( $http->postVariable( 'SelectedNodeIDArray' ) as $nodeID )
{
$persistentData['node_list'][] = array( 'id' => $nodeID,
'type' => 'subtree' );
}
}
else if ( $http->hasPostVariable( 'Node' ) &&
$http->hasPostVariable( 'Node' ) == 1 )
{
foreach( $http->postVariable( 'SelectedNodeIDArray' ) as $nodeID )
{
$persistentData['node_list'][] = array( 'id' => $nodeID,
'type' => 'node' );
}
}
}
$tpl->setVariable( 'node_list', $persistentData['node_list'] );
}
/*!
Checks if at least one content class has been selected.
*/
function validateObjectList( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList )
{
if ( count( $persistentData['node_list'] ) == 0 )
{
$errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Selected nodes' ),
'description' => ezpI18n::tr( 'kernel/package', 'You must select one or more node(s)/subtree(s) for export.' ) );
return false;
}
return true;
}
function initializeObjectLimits( $package, $http, $step, &$persistentData, $tpl )
{
$persistentData['object_options'] = array( 'include_classes' => 1,
'include_templates' => 1,
'site_access_array' => array(),
'versions' => 'current',
'language_array' => array(),
'node_assignment' => 'selected',
'related_objects' => 'selected',
'embed_objects' => 'selected' );
$ini = eZINI::instance();
$persistentData['object_options']['site_access_array'] = array( $ini->variable( 'SiteSettings', 'DefaultAccess' ) );
$availableLanguages = eZContentObject::translationList();
foreach ( $availableLanguages as $language )
{
$persistentData['object_options']['language_array'][] = $language->attribute( 'locale_code' );
}
}
function loadObjectLimits( $package, $http, $step, &$persistentData, $tpl, &$module )
{
$ini = eZINI::instance();
$availableSiteAccesses = $ini->variable( 'SiteAccessSettings', 'RelatedSiteAccessList' );
$availableLanguages = eZContentObject::translationList();
$availableLanguageArray = array();
foreach ( $availableLanguages as $language )
{
$availableLanguageArray[] = array( 'name' => $language->attribute( 'language_name' ),
'locale' => $language->attribute( 'locale_code' ) );
}
$tpl->setVariable( 'available_site_accesses', $availableSiteAccesses );
$tpl->setVariable( 'available_languages', $availableLanguageArray );
$tpl->setVariable( 'options', $persistentData['object_options'] );
}
/*!
Checks if at least one content class has been selected.
*/
function validateObjectLimits( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList )
{
$options =& $persistentData['object_options'];
$options['include_classes'] = $http->hasPostVariable( 'IncludeClasses' ) ? $http->postVariable( 'IncludeClasses' ) : false;
$options['include_templates'] = $http->hasPostVariable( 'IncludeTemplates' ) ? $http->postVariable( 'IncludeTemplates' ) : false;
$options['site_access_array'] = $http->postVariable( 'SiteAccesses' );
$options['versions'] = $http->postVariable( 'VersionExport' );
$options['language_array'] = $http->postVariable( 'Languages' );
$options['node_assignment'] = $http->postVariable( 'NodeAssignment' );
$options['related_objects'] = $http->postVariable( 'RelatedObjects' );
$options['minimal_template_set'] = $http->hasPostVariable( 'MinimalTemplateSet' ) ? $http->postVariable( 'MinimalTemplateSet' ) : false;
$result = true;
if ( count( $persistentData['object_options']['language_array'] ) == 0 )
{
$errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Selected nodes' ),
'description' => ezpI18n::tr( 'kernel/package', 'You must choose one or more languages.' ) );
$result = false;
}
if ( $persistentData['object_options']['include_templates'] &&
count( $persistentData['object_options']['site_access_array'] ) == 0 )
{
$errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Selected nodes' ),
'description' => ezpI18n::tr( 'kernel/package', 'You must choose one or more site access.' ) );
$result = false;
}
return $result;
}
/*!
Fetches the selected content classes and generates a name, summary and description from the selection.
*/
function generatePackageInformation( &$packageInformation, $package, $http, $step, &$persistentData )
{
$nodeList = $persistentData['node_list'];
$options = $persistentData['object_options'];
$nodeCount = 0;
$description = 'This package contains the following nodes :' . "\n";
$nodeNames = array();
foreach( $nodeList as $nodeInfo )
{
$contentNode = eZContentObjectTreeNode::fetch( $nodeInfo['id'] );
$description .= $contentNode->attribute( 'name' ) . ' - ' . $nodeInfo['type'] . "\n";
$nodeNames[] = trim( $contentNode->attribute( 'name' ) );
if ( $nodeInfo['type'] == 'node' )
{
++$nodeCount;
}
else if ( $nodeInfo['type'] == 'subtree' )
{
$nodeCount += $contentNode->subTreeCount();
}
}
$packageInformation['name'] = implode( ',', $nodeNames );
$packageInformation['summary'] = implode( ', ', $nodeNames );
$packageInformation['description'] = $description;
}
}
?>
| gpl-2.0 |
gecgooden/gamepad | gamepad.cpp | 2200 | /***********************************************************************
* mcp3008SpiTest.cpp. Sample program that tests the mcp3008Spi class.
* an mcp3008Spi class object (a2d) is created. the a2d object is instantiated
* using the overloaded constructor. which opens the spidev0.0 device with
* SPI_MODE_0 (MODE 0) (defined in linux/spi/spidev.h), speed = 1MHz &
* bitsPerWord=8.
*
* call the spiWriteRead function on the a2d object 20 times. Each time make sure
* that conversion is configured for single ended conversion on CH0
* i.e. transmit -> byte1 = 0b00000001 (start bit)
* byte2 = 0b1000000 (SGL/DIF = 1, D2=D1=D0=0)
* byte3 = 0b00000000 (Don't care)
* receive -> byte1 = junk
* byte2 = junk + b8 + b9
* byte3 = b7 - b0
*
* after conversion must merge data[1] and data[2] to get final result
*
*
*
* *********************************************************************/
#include "mcp3008Spi.h"
using namespace std;
int main(void)
{
mcp3008Spi a2d("/dev/spidev0.0", SPI_MODE_0, 1000000, 8);
int i = 20;
int a2dVal = 0;
int a2dVal2 = 0;
int a2dChannel = 0;
int a2dChannel2 = 1;
unsigned char data[3];
unsigned char other[3];
while(1)
{
data[0] = 1; // first byte transmitted -> start bit
data[1] = 0b10000000 |( ((a2dChannel & 7) << 4)); // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0)
data[2] = 0; // third byte transmitted....don't care
a2d.spiWriteRead(data, sizeof(data) );
a2dVal = 0;
a2dVal = (data[1]<< 8) & 0b1100000000; //merge data[1] & data[2] to get result
a2dVal |= (data[2] & 0xff);
other[0] = 1; // first byte transmitted -> start bit
other[1] = 0b10000000 |( ((a2dChannel2 & 7) << 4)); // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0)
other[2] = 0; // third byte transmitted....don't care
a2d.spiWriteRead(other, sizeof(other));
a2dVal2 = 0;
a2dVal2 = (other[1]<< 8) & 0b1100000000;
a2dVal2 |= (other[2] & 0xff);
cout << "The Result is: " << a2dVal << ", " << a2dVal2 << endl;
i--;
}
return 0;
}
| gpl-2.0 |
cladjidane/D-mo-HTML5-CSS3 | administrator/components/com_jce/classes/installer.php | 32374 | <?php
/**
* @version $Id: installer.php 255 2011-06-29 18:10:57Z happy_noodle_boy $
* @package JCE
* @copyright Copyright © 2009-2011 Ryan Demmer. All rights reserved.
* @copyright Copyright © 2005 - 2007 Open Source Matters. All rights reserved.
* @license GNU/GPL 2 or later
* This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
// Do not allow direct access
defined('_JEXEC') or die('RESTRICTED');
class WFInstaller extends JObject
{
var $version = '2.0.1';
/**
* @var Boolean Profiles table exists
*/
var $profiles;
/**
* @var Boolean Profiles / Plugins tables exist
*/
var $tables;
/**
* Constructor activating the default information of the class
*
* @access protected
*/
function __construct()
{
$language = JFactory::getLanguage();
$language->load('com_jce', JPATH_ADMINISTRATOR);
JTable::addIncludePath(dirname(dirname(__FILE__)) . DS . 'tables');
}
/**
* Returns a reference to a editor object
*
* This method must be invoked as:
* <pre> $browser =JContentEditor::getInstance();</pre>
*
* @access public
* @return WF_The editor object.
* @since 1.5
*/
function &getInstance()
{
static $instance;
if (!is_object($instance)) {
$instance = new WFInstaller();
}
return $instance;
}
/**
* Check upgrade / database status
*/
function check()
{
$this->profiles = $this->checkTable('#__wf_profiles');
if ($this->profiles) {
$this->profiles = $this->checkTableContents('#__wf_profiles');
}
if (!$this->checkComponent()) {
return $this->install(true);
}
// Check Profiles DB
if (!$this->profiles) {
return $this->redirect();
}
// Check Editor is installed
if (!$this->checkEditorFiles()) {
return $this->redirect(WFText::_('WF_EDITOR_FILES_ERROR'), 'error');
}
if (!$this->checkEditor() && $this->checkEditorFiles()) {
$link = JHTML::link('index.php?option=com_jce&task=repair&type=editor', WFText::_('WF_EDITOR_INSTALL'));
return $this->redirect(WFText::_('WF_EDITOR_INSTALLED_MANUAL_ERROR') . ' - ' . $link, 'error');
}
// Check Editor is installed
if (!$this->checkEditor()) {
return $this->redirect(WFText::_('WF_EDITOR_INSTALLED_ERROR'), 'error');
}
// Check Editor is enabled
if (!$this->checkEditorEnabled()) {
return $this->redirect(WFText::_('WF_EDITOR_ENABLED_ERROR'), 'error');
}
}
function log($msg)
{
jimport('joomla.error.log');
$log = JLog::getInstance('upgrade.txt');
$log->addEntry(array(
'comment' => 'LOG: ' . $msg
));
}
/**
* Repair an installation
*/
function repair()
{
$type = JRequest::getWord('type', 'tables');
switch ($type) {
case 'tables':
return $this->repairTables();
break;
case 'editor':
$source = dirname(dirname(__FILE__)) . DS . 'plugin';
if (is_dir($source)) {
return $this->installEditor($source);
}
break;
}
}
/**
* Redirect with message
* @param object $msg[optional] Message to display
* @param object $state[optional] Message type
*/
function redirect($msg = '', $state = '')
{
$mainframe = JFactory::getApplication();
if ($msg) {
$mainframe->enqueueMessage($msg, $state);
}
JRequest::setVar('view', 'cpanel');
JRequest::setVar('task', '');
return false;
}
/**
* Upgrade database tables and remove legacy folders
* @return Boolean
*/
function upgrade($version)
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
wfimport('admin.helpers.parameter');
wfimport('admin.helpers.xml');
$base = dirname(dirname(__FILE__));
if (version_compare($version, '2.0.0beta2', '<')) {
if ($this->checkTable('#__jce_profiles')) {
// get all groups data
$query = 'SELECT * FROM #__jce_profiles';
$db->setQuery($query);
$profiles = $db->loadObjectList();
if ($this->createProfilesTable()) {
$row = JTable::getInstance('profiles', 'WFTable');
foreach ($profiles as $profile) {
$row->bind($profile);
$row->store();
}
}
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_profiles';
$db->setQuery($query);
$db->query();
}
}
// upgrade from 1.5.x to 2.0.0 (only in Joomla! 1.5)
if (version_compare($version, '2.0.0', '<') && WF_JOOMLA15) {
// check for groups table / data
if ($this->checkTable('#__jce_groups') && $this->checkTableContents('#__jce_groups')) {
// get plugin
$plugin = JPluginHelper::getPlugin('editors', 'jce');
// get JCE component
$table = JTable::getInstance('component');
$table->loadByOption('com_jce');
// process params to JSON string
$params = WFParameterHelper::toObject($table->params);
// set params
$table->params = json_encode(array('editor' => $params));
// store
$table->store();
// get all groups data
$query = 'SELECT * FROM #__jce_groups';
$db->setQuery($query);
$groups = $db->loadObjectList();
// get all plugin data
$query = 'SELECT id, name, icon FROM #__jce_plugins';
$db->setQuery($query);
$plugins = $db->loadAssocList('id');
if ($this->createProfilesTable()) {
foreach ($groups as $group) {
$row = JTable::getInstance('profiles', 'WFTable');
// transfer row ids to names
foreach (explode(';', $group->rows) as $item) {
$icons = array();
foreach (explode(',', $item) as $id) {
// spacer
if ($id == '00') {
$icons[] = 'spacer';
} else {
if (isset($plugins[$id])) {
$icons[] = $plugins[$id]['icon'];
}
}
}
$rows[] = implode(',', $icons);
}
$group->rows = implode(';', $rows);
$names = array();
// transfer plugin ids to names
foreach (explode(',', $group->plugins) as $id) {
if (isset($plugins[$id])) {
$items[] = $plugins[$id]['name'];
}
}
$group->plugins = implode(',', $names);
// convert params to JSON
$params = WFParameterHelper::toObject($group->params);
$data = new StdClass();
foreach($params as $key => $value) {
$parts = explode('_', $key);
$node = array_shift($parts);
// special consideration for imgmanager_ext!!
if (strpos($key, 'imgmanager_ext_') !== false) {
$node = $node . '_' . array_shift($parts);
}
// convert some keys
if ($key == 'advlink') {
$key = 'link';
}
$key = implode('_', $parts);
if ($value !== '') {
if (isset($data->$node) && is_object($data->$node)) {
$data->$node->$key = $value;
} else {
$data->$node = new StdClass();
$this->log(json_encode(array($node, $key, $value)));
$data->$node->$key = $value;
}
}
}
$group->params = json_encode($data);
// bind data
$row->bind($group);
// add area data
if ($row->name == 'Default') {
$row->area = 0;
}
if ($row->name == 'Front End') {
$row->area = 1;
}
if (!$row->store()) {
$mainframe->enqueueMessage('Conversion of group data failed : ' . $row->name, 'error');
}
}
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_groups';
$db->setQuery($query);
$db->query();
// If profiles table empty due to error, install profiles data
if (!$this->checkTableContents('#__wf_profiles')) {
$this->installProfiles(true);
}
} else {
return false;
}
// Install profiles
} else {
$this->installProfiles(true);
}
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_plugins';
$db->setQuery($query);
$db->query();
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_extensions';
$db->setQuery($query);
$db->query();
// Remove Plugins menu item
$query = 'DELETE FROM #__components' . ' WHERE admin_menu_link = ' . $db->Quote('option=com_jce&type=plugins');
$db->setQuery($query);
$db->query();
// Update Component Name
$query = 'UPDATE #__components' . ' SET name = ' . $db->Quote('COM_JCE') . ' WHERE ' . $db->Quote('option') . '=' . $db->Quote('com_jce') . ' AND parent = 0';
$db->setQuery($query);
$db->query();
// Fix links for other views and edit names
$menus = array(
'install' => 'installer',
'group' => 'profiles',
'groups' => 'profiles',
'config' => 'config'
);
$row = JTable::getInstance('component');
foreach ($menus as $k => $v) {
$query = 'SELECT id FROM #__components' . ' WHERE admin_menu_link = ' . $db->Quote('option=com_jce&type=' . $k);
$db->setQuery($query);
$id = $db->loadObject();
if ($id) {
$row->load($id);
$row->name = $v;
$row->admin_menu_link = 'option=com_jce&view=' . $v;
if (!$row->store()) {
$mainframe->enqueueMessage('Unable to update Component Links for view : ' . strtoupper($v), 'error');
}
}
}
} // end JCE 1.5 upgrade
return true;
}
/**
* Install Editor and Plugin packages
* @return
*/
function install($manual = false)
{
jimport('joomla.installer.installer');
jimport('joomla.installer.helper');
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
$installer = JInstaller::getInstance();
// set base path
$base = dirname(dirname(__FILE__));
$state = false;
// Install the Administration Component
if ($manual) {
if (!$this->installComponent()) {
$mainframe->enqueueMessage(WFText::_('WF_COMPONENT_MANUAL_INSTALL_FAIL'), 'error');
$mainframe->redirect('index.php');
} else {
$mainframe->enqueueMessage(WFText::_('WF_COMPONENT_MANUAL_INSTALL_SUCCESS'));
}
}
$upgrade = false;
$version = $this->version;
// check for upgrade
$xml_file = $base . DS . 'jce.xml';
if (is_file($xml_file)) {
$xml = JApplicationHelper::parseXMLInstallFile($xml_file);
if (preg_match('/([0-9\.]+)(beta|rc|dev|alpha)?([0-9]+?)/i', $xml['version'])) {
// component version is less than current
if (version_compare($xml['version'], $this->version, '<')) {
$upgrade = true;
$version = $xml['version'];
}
// invalid component version, check for groups table
} else {
// check for old tables
if ($this->checkTable('#__jce_groups')) {
$version = '1.5.0';
}
// check for old tables
if ($this->checkTable('#__jce_profiles')) {
$version = '2.0.0beta1';
}
}
} else {
// check for old tables
if ($this->checkTable('#__jce_groups')) {
$version = '1.5.0';
}
}
// perform upgrade
if (version_compare($version, $this->version, '<')) {
$state = $this->upgrade($version);
} else {
// install plugins first
$state = $this->installProfiles(true);
}
if ($state) {
if ($manual) {
$mainframe->redirect('index.php?option=com_jce');
}
$source = $installer->getPath('source');
$packages = $source . DS . 'packages';
$backup = $source . DS . 'backup';
$language = JFactory::getLanguage();
$language->load('com_jce', JPATH_ADMINISTRATOR);
$manifest = $installer->getPath('manifest');
$version = $this->version;
// Component data
if ($xml = JApplicationHelper::parseXMLInstallFile($manifest)) {
$version = $xml['version'];
}
$message = '<table class="adminlist">' . '<thead><th colspan="3">' . WFText::_('WF_INSTALL_SUMMARY') . '</th>' . '<thead><th class="title" style="width:65%">' . WFText::_('WF_INSTALLER_EXTENSION') . '</th><th class="title" style="width:30%">' . WFText::_('WF_ADMIN_VERSION') . '</th><th class="title" style="width:5%"> </th></thead>' . '<tr><td>' . WFText::_('WF_ADMIN_TITLE') . '</td><td>' . $version . '</td><td class="title" style="text-align:center;">' . JHTML::image(JURI::root() . 'administrator/components/com_jce/media/img/tick.png', WFText::_('WF_ADMIN_SUCCESS')) . '</td></tr>' . '<tr><td colspan="3">' . WFText::_('WF_ADMIN_DESC') . '</td></tr>';
// legacy cleanup
if (get_parent_class($installer) == 'JAdapter') {
$this->_legacyCleanup();
}
// set editor plugin package dir
$editor = $base . DS . 'plugin';
// install editor plugin
if (is_dir($editor) && is_file($editor . DS . 'jce.php') && is_file($editor . DS . 'jce.xml')) {
$xml = JApplicationHelper::parseXMLInstallFile($editor . DS . 'jce.xml');
if ($result = $this->installEditor($editor, true)) {
$message .= $result;
} else {
$message .= '<tr><td>' . WFText::_('WF_EDITOR_TITLE') . '</td><td>' . $xml['version'] . '</td><td class="title" style="text-align:center;">' . JHTML::image(JURI::root() . 'administrator/components/com_jce/media/img/error.png', WFText::_('WF_LABEL_ERROR')) . '</td></tr>';
}
}
$message .= '</table>';
$installer->set('message', $message);
// post-install
$this->addIndexfiles();
} else {
$installer->abort();
}
}
function addIndexfiles()
{
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
// get the base file
$file = dirname(dirname(__FILE__)) . DS . 'index.html';
if (is_file($file)) {
// admin component
$folders = JFolder::folders(dirname($file), '.', true, true);
foreach ($folders as $folder) {
JFile::copy($file, $folder . DS . basename($file));
}
// site component
$site = JPATH_SITE . DS . 'components' . DS . 'com_jce';
if (is_dir($site)) {
$folders = JFolder::folders($site, '.', true, true);
foreach ($folders as $folder) {
JFile::copy($file, $folder . DS . basename($file));
}
}
// plugin
$plugin = JPATH_PLUGINS . DS . 'jce';
// only needed for Joomla! 1.6+
if (is_dir($plugin)) {
JFile::copy($file, $plugin . DS . basename($file));
}
}
}
function uninstall()
{
// remove profiles table if empty
if (!$this->checkTableContents('#__wf_profiles')) {
$this->removeTable('#__wf_profiles');
}
$this->removeEditor();
}
function _legacyCleanup()
{
$path = JPATH_PLUGINS . DS . 'editors';
// cleanup old installation
if (is_file($path . DS . 'jce.php')) {
@JFile::delete($path . DS . 'jce.php');
}
if (is_file($path . DS . 'jce.xml')) {
@JFile::delete($path . DS . 'jce.xml');
}
if (is_dir($path . DS . 'jce')) {
@JFolder::delete($path . DS . 'jce');
}
$db = JFactory::getDBO();
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_groups';
$db->setQuery($query);
$db->query();
// Drop tables
$query = 'DROP TABLE IF EXISTS #__jce_plugins';
$db->setQuery($query);
$db->query();
// remove menu items so they are re-installed to prevent errors in Joomla! 1.6
$this->_removeMenus();
}
function _removeMenus()
{
$db = JFactory::getDBO();
$query = 'SELECT id FROM #__menu'
. ' WHERE client_id = 1'
. ' AND type = ' . $db->Quote('component')
. ' AND path = ' . $db->Quote('jce')
. ' AND component_id = 0'
;
$db->setQuery($query);
$id = $db->loadResult();
if ($id) {
$query = 'SELECT id FROM #__menu'
. ' WHERE client_id = 1'
. ' AND parent_id = ' . (int) $id
;
$db->setQuery($query);
$ids = $db->loadResultArray();
$menu = JTable::getInstance('menu');
if (count($ids)) {
// Iterate the items to delete each one.
foreach($ids as $menuid){
if (!$menu->delete((int) $menuid)) {
$this->setError($menu->getError());
return false;
}
}
}
// remove parent
if (!$menu->delete((int) $id)) {
$this->setError($menu->getError());
return false;
}
// Rebuild the whole tree
$menu->rebuild();
}
}
/* TODO : */
function installFromBackup()
{
return true;
}
/**
* Remove a table
* @return boolean
* @param string $table Table to remove
*/
function removeTable($table)
{
$db = JFactory::getDBO();
$query = 'DROP TABLE IF EXISTS #__jce_' . $table;
$db->setQuery($query);
return $db->query();
}
/**
* Check whether the component is installed
* @return
*/
function checkComponent()
{
$component = JComponentHelper::getComponent('com_jce', true);
return $component->enabled;
}
/**
* Check whether a table exists
* @return boolean
* @param string $table Table name
*/
function checkTable($table)
{
$db = JFactory::getDBO();
$tables = $db->getTableList();
if (!empty($tables)) {
// swap array values with keys, convert to lowercase and return array keys as values
$tables = array_keys(array_change_key_case(array_flip($tables)));
$app = JFactory::getApplication();
foreach($tables as $item) {
if (strpos($item, $app->getCfg('dbprefix', '') . str_replace('#__', '', $table)) !== false) {
return true;
}
}
return false;
}
// try with query
$query = 'SELECT COUNT(id) FROM ' . $table;
$db->setQuery($query);
return $db->query();
}
/**
* Check table contents
* @return boolean
* @param string $table Table name
*/
function checkTableContents($table)
{
$db = JFactory::getDBO();
$query = 'SELECT COUNT(id) FROM ' . $table;
$db->setQuery($query);
return $db->loadResult();
}
/**
* Check whether a field exists
* @return boolean
* @param string $table Table name
*/
function checkField($table, $field)
{
$db = JFactory::getDBO();
$fields = $db->getTableFields($table);
return array_key_exists($field, $fields[$table]);
}
/**
* Remove all tables
*/
function removeTables($uninstall = false)
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
$tables = array(
'plugins',
'extensions',
'groups',
'profiles'
);
foreach ($tables as $table) {
if (!$this->removeTable($table)) {
$msg = JText::sprintf('WF_DB_REMOVE_ERROR', ucfirst($table));
$state = 'error';
} else {
$msg = JText::sprintf('WF_DB_REMOVE_SUCCESS', ucfirst($table));
$state = '';
}
$mainframe->enqueueMessage($msg, $state);
}
if (!$uninstall) {
$mainframe->redirect('index.php?option=com_jce');
}
}
function repairTables()
{
$table = JRequest::getString('table');
if ($table) {
$method = 'install' . ucfirst($table);
if (method_exists($this, $method)) {
return $this->$method();
}
}
}
/**
* Check if all tables exist
* @return boolean
*/
function checkTables()
{
$ret = false;
$tables = array(
'plugins',
'profiles'
);
foreach ($tables as $table) {
$ret = $this->checkTable($table);
}
return $ret;
}
/**
* Remove all backup tables
*/
function cleanupDB()
{
$db = JFactory::getDBO();
$tables = array(
'plugins',
'profiles',
'groups',
'extensions'
);
foreach ($tables as $table) {
$query = 'DROP TABLE IF EXISTS #__jce_' . $table . '_tmp';
$db->setQuery($query);
$db->query();
}
}
/**
* Check whether the editor is installed
* @return boolean
*/
function checkEditor()
{
require_once(JPATH_LIBRARIES . DS . 'joomla' . DS . 'plugin' . DS . 'helper.php');
return JPluginHelper::getPlugin('editors', 'jce');
}
/**
* Check for existence of editor files and folder
* @return boolean
*/
function checkEditorFiles()
{
$path = WF_JOOMLA15 ? JPATH_PLUGINS . DS . 'editors' : JPATH_PLUGINS . DS . 'editors' . DS . 'jce';
// Check for JCE plugin files
return file_exists($path . DS . 'jce.php') && file_exists($path . DS . 'jce.xml');
}
/**
* Check if the editor is enabled
* @return boolean
*/
function checkEditorEnabled()
{
return true;
}
/**
* Check the installed component version
* @return Version message
*/
function checkEditorVersion()
{
jimport('joomla.filesystem.file');
$file = WF_JOOMLA15 ? JPATH_PLUGINS . DS . 'editors' . DS . 'jce.xml' : JPATH_PLUGINS . DS . 'editors' . DS . 'jce' . DS . 'jce.xml';
if (!JFile::exists($file)) {
JError::raiseNotice('SOME ERROR CODE', WFText::_('WF_EDITOR_VERSION_ERROR'));
return false;
} else {
if ($xml = JApplicationHelper::parseXMLInstallFile($file)) {
$version = $xml['version'];
// Development version
if (strpos($this->version, '2.0.1') !== false || strpos($version, '2.0.1') !== false) {
return true;
}
if (version_compare($version, $this->version, '<')) {
JError::raiseNotice('SOME ERROR CODE', JText::sprintf('WF_EDITOR_VERSION_ERROR', $this->version));
return false;
}
}
}
}
/**
* Create the Profiles table
* @return boolean
*/
function createProfilesTable()
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
$query = "CREATE TABLE IF NOT EXISTS `#__wf_profiles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`users` text NOT NULL,
`types` varchar(255) NOT NULL,
`components` text NOT NULL,
`area` tinyint(3) NOT NULL,
`rows` text NOT NULL,
`plugins` text NOT NULL,
`published` tinyint(3) NOT NULL,
`ordering` int(11) NOT NULL,
`checked_out` tinyint(3) NOT NULL,
`checked_out_time` datetime NOT NULL,
`params` text NOT NULL,
PRIMARY KEY (`id`)
);";
$db->setQuery($query);
if (!$db->query()) {
$mainframe->enqueueMessage(WFText::_('WF_INSTALL_TABLE_PROFILES_ERROR') . $db->stdErr(), 'error');
return false;
} else {
return true;
}
}
/**
* Install Profiles
* @return boolean
* @param object $install[optional]
*/
function installProfiles($install = false)
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
$ret = false;
JTable::addIncludePath(dirname(dirname(__FILE__)) . DS . 'profiles');
if ($this->createProfilesTable()) {
$ret = true;
$query = 'SELECT count(id) FROM #__wf_profiles';
$db->setQuery($query);
$profiles = array(
'Default' => false,
'Front End' => false
);
// No Profiles table data
if (!$db->loadResult()) {
$path = dirname(dirname(__FILE__)) . DS . 'models';
JModel::addIncludePath($path);
$model = JModel::getInstance('profiles', 'WFModel');
$xml = $path . 'profiles.xml';
// try root profiles.xml first
if (!is_file($xml)) {
$xml = $path . DS . 'profiles.xml';
}
if (is_file($xml)) {
if (!$model->processImport($xml, true)) {
$mainframe->enqueueMessage(WFText::_('WF_INSTALL_PROFILES_ERROR'), 'error');
}
} else {
$mainframe->enqueueMessage(WFText::_('WF_INSTALL_PROFILES_NOFILE_ERROR'), 'error');
}
}
}
if (!$install) {
//$this->redirect();
$mainframe->redirect('index.php?option=com_jce');
}
return $ret;
}
/**
* Install the editor package
* @return Array or false
* @param object $path[optional] Path to package folder
*/
function installEditor($source, $install = false)
{
jimport('joomla.installer.installer');
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
$result = '';
JTable::addIncludePath(JPATH_LIBRARIES . DS . 'joomla' . DS . 'database' . DS . 'table');
$version = '';
$name = '';
if ($xml = JApplicationHelper::parseXMLInstallFile($source . DS . 'jce.xml')) {
$version = $xml['version'];
$name = $xml['name'];
}
$installer = new JInstaller();
if ($installer->install($source)) {
if ($install) {
$language = JFactory::getLanguage();
$language->load('plg_editors_jce', JPATH_ADMINISTRATOR);
$result = '<tr><td>' . WFText::_('WF_EDITOR_TITLE') . '</td><td>' . $version . '</td><td class="title" style="text-align:center;">' . JHTML::image(JURI::root() . 'administrator/components/com_jce/media/img/tick.png', WFText::_('WF_ADMIN_SUCCESS')) . '</td></tr>';
if ($installer->message) {
$result .= '<tr><td colspan="3">' . WFText::_($installer->message, $installer->message) . '</td></tr>';
}
} else {
$mainframe->enqueueMessage(WFText::_('WF_EDITOR_INSTALL_SUCCESS'));
}
} else {
if (!$install) {
$mainframe->enqueueMessage(WFText::_('WF_EDITOR_INSTALL_FAILED'));
}
}
if (!$install) {
$mainframe->redirect('index.php?option=com_jce');
}
return $result;
}
/**
* Install the Editor Component
* @return boolean
*/
function installComponent()
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
jimport('joomla.installer.installer');
require_once(JPATH_LIBRARIES . DS . 'joomla' . DS . 'installer' . DS . 'adapters' . DS . 'component.php');
$installer = JInstaller::getInstance();
$installer->setPath('source', dirname(dirname(__FILE__)));
$component = new JInstallerComponent($installer, $db);
$component->install();
return $this->checkComponent();
}
/**
* Uninstall the editor
* @return boolean
*/
function removeEditor()
{
$mainframe = JFactory::getApplication();
$db = JFactory::getDBO();
// load extension helper
require_once(dirname(dirname(__FILE__)) . DS . 'helpers' . DS . 'extension.php');
$plugin = WFExtensionHelper::getPlugin();
if (isset($plugin->id)) {
jimport('joomla.installer.installer');
$installer = new JInstaller();
if (!$installer->uninstall('plugin', $plugin->id)) {
$mainframe->enqueueMessage(WFText::_('WF_EDITOR_REMOVE_ERROR'));
return false;
} else {
$mainframe->enqueueMessage(WFText::_('WF_EDITOR_REMOVE_SUCCESS'));
return true;
}
$mainframe->enqueueMessage($msg);
return $ret;
} else {
$mainframe->enqueueMessage(WFText::_('WF_EDITOR_REMOVE_NOT_FOUND'), 'error');
return false;
}
}
}
?> | gpl-2.0 |
legoktm/wikihow-src | extensions/wikihow/editfinder/EditFinder.php | 1180 | <?php
if ( ! defined( 'MEDIAWIKI' ) )
die();
$wgExtensionCredits['specialpage'][] = array(
'name' => 'EditFinder',
'author' => 'Scott Cushman',
'description' => 'Tool for experienced users to edit articles that need it.',
);
$wgSpecialPages['EditFinder'] = 'EditFinder';
$wgAutoloadClasses['EditFinder'] = dirname( __FILE__ ) . '/EditFinder.body.php';
$wgExtensionMessagesFiles['EditFinder'] = dirname(__FILE__) . '/EditFinder.i18n.php';
$wgLogTypes[] = 'ef_format';
$wgLogNames['ef_format'] = 'editfinder_format';
$wgLogHeaders['ef_format'] = 'editfindertext_format';
$wgLogTypes[] = 'ef_stub';
$wgLogNames['ef_stub'] = 'editfinder_stub';
$wgLogHeaders['ef_stub'] = 'editfindertext_stub';
$wgLogTypes[] = 'ef_topic';
$wgLogNames['ef_topic'] = 'editfinder_topic';
$wgLogHeaders['ef_topic'] = 'editfindertext_topic';
$wgLogTypes[] = 'ef_cleanup';
$wgLogNames['ef_cleanup'] = 'editfinder_cleanup';
$wgLogHeaders['ef_cleanup'] = 'editfindertext_cleanup';
// Log type names can only be 10 chars
$wgLogTypes[] = 'ef_copyedi';
$wgLogNames['ef_copyedi'] = 'editfinder_copyedit';
$wgLogHeaders['ef_copyedi'] = 'editfindertext_copyedit';
| gpl-2.0 |
joebushi/joomla | administrator/components/com_banners/controller.php | 1342 | <?php
/**
* @version $Id$
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
/**
* Banners master display controller.
*
* @package Joomla.Administrator
* @subpackage com_banners
* @since 1.6
*/
class BannersController extends JController
{
/**
* Method to display a view.
*/
public function display()
{
require_once JPATH_COMPONENT.'/helpers/banners.php';
BannersHelper::updateReset();
// Get the document object.
$document = JFactory::getDocument();
// Set the default view name and format from the Request.
$vName = JRequest::getWord('view', 'banners');
$vFormat = $document->getType();
$lName = JRequest::getWord('layout', 'default');
// Get and render the view.
if ($view = &$this->getView($vName, $vFormat))
{
// Get the model for the view.
$model = &$this->getModel($vName);
// Push the model into the view (as default).
$view->setModel($model, true);
$view->setLayout($lName);
// Push document object into the view.
$view->assignRef('document', $document);
$view->display();
// Load the submenu.
BannersHelper::addSubmenu($vName);
}
}
}
| gpl-2.0 |
jamer/slow | src/slowers/unix.hpp | 313 | #ifndef SRC_SLOWERS_UNIX_HPP_
#define SRC_SLOWERS_UNIX_HPP_
#include <signal.h>
#include <stdio.h>
#include "src/slower.hpp"
class UnixSlower : public Slower {
public:
UnixSlower(int pid);
~UnixSlower() = default;
void _pause();
void _resume();
private:
pid_t pid;
};
#endif // SRC_SLOWERS_UNIX_HPP_
| gpl-2.0 |
jcsky/solveissue | db/migrate/20151230145454_create_districts.rb | 202 | class CreateDistricts < ActiveRecord::Migration
def change
create_table(:districts, id: :uuid) do |t|
t.string :name
t.uuid :city_id, index: true
t.timestamps
end
end
end
| gpl-2.0 |
refugeehackathon/interpreteer-backend | interpreteer/wsgi.py | 2361 | """
WSGI config for interpreteer project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
#import sys
#import site
#import subprocess
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__) + "../../")
# Add the virtualenv packages to the site directory. This uses the technique
# described at http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
# Remember original sys.path.
#prev_sys_path = list(sys.path)
# Get the path to the env's site-packages directory
#site_packages = subprocess.check_output([
# os.path.join(PROJECT_ROOT, '.virtualenv/bin/python'),
# '-c',
# 'from distutils.sysconfig import get_python_lib;'
# 'print get_python_lib(),'
#]).strip()
# Add the virtualenv site-packages to the site packages
#site.addsitedir(site_packages)
# Reorder sys.path so the new directories are at the front.
#new_sys_path = []
#for item in list(sys.path):
# if item not in prev_sys_path:
# new_sys_path.append(item)
# sys.path.remove(item)
#sys.path[:0] = new_sys_path
# Add the app code to the path
#sys.path.append(PROJECT_ROOT)
os.environ['CELERY_LOADER'] = 'django'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "interpreteer.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
# from django.core.wsgi import get_wsgi_application
# application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
| gpl-2.0 |
iqbalsublime/NullPointer | src/main/java/com/sublime/np/entity/Comment.java | 1331 | package com.sublime.np.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Size;
@Entity
public class Comment {
@Id
@GeneratedValue
private Integer id;
@Size(min=5, message = "Comment must be at least 5 characters !" )
private String commentText;
@Column(name = "published_date")
private Date publishedDate;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
@ManyToOne
@JoinColumn(name="question_id")
private Question question;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
}
| gpl-2.0 |
edii/dimai | wp-content/themes/Grimag/framework/functions/classes/class-envato-protected-api.php | 9805 | <?php
/**
* Envato Protected API
*
* Wrapper class for the Envato marketplace protected API methods specific
* to the Envato WordPress Toolkit plugin.
*
* @package WordPress
* @subpackage Envato WordPress Toolkit
* @author Derek Herman <[email protected]>
* @since 1.0
*/
class Envato_Protected_API {
/**
* The buyer's Username
*
* @var string
*
* @access public
* @since 1.0
*/
public $user_name;
/**
* The buyer's API Key
*
* @var string
*
* @access public
* @since 1.0
*/
public $api_key;
/**
* The default API URL
*
* @var string
*
* @access private
* @since 1.0
*/
protected $public_url = 'http://marketplace.envato.com/api/edge/set.json';
/**
* Error messages
*
* @var array
*
* @access public
* @since 1.0
*/
public $errors = array( 'errors' => '' );
/**
* Class contructor method
*
* @param string The buyer's Username
* @param string The buyer's API Key can be accessed on the marketplaces via My Account -> My Settings -> API Key
* @return void Sets error messages if any.
*
* @access public
* @since 1.0
*/
public function __construct( $user_name = '', $api_key = '' ) {
if ( $user_name == '' ) {
$this->set_error( 'user_name', __( 'Please enter your Envato Marketplace Username.', 'envato' ) );
}
if ( $api_key == '' ) {
$this->set_error( 'api_key', __( 'Please enter your Envato Marketplace API Key.', 'envato' ) );
}
$this->user_name = $user_name;
$this->api_key = $api_key;
}
/**
* Get private user data.
*
* @param string Available sets: 'vitals', 'earnings-and-sales-by-month', 'statement', 'recent-sales', 'account', 'verify-purchase', 'download-purchase', 'wp-list-themes', 'wp-download'
* @param string The buyer/author username to test against.
* @param string Additional set data such as purchase code or item id.
* @param bool Allow API calls to be cached. Default false.
* @param int Set transient timeout. Default 300 seconds (5 minutes).
* @return array An array of values (possibly cached) from the requested set, or an error message.
*
* @access public
* @since 1.0
* @updated 1.3
*/
public function private_user_data( $set = '', $user_name = '', $set_data = '', $allow_cache = false, $timeout = 300 ) {
if ( $set == '' ) {
$this->set_error( 'set', __( 'The API "set" is a required parameter.', 'envato' ) );
}
if ( $user_name == '' ) {
$user_name = $this->user_name;
}
if ( $set_data !== '' ) {
$set_data = ":$set_data";
}
$url = "http://marketplace.envato.com/api/edge/$user_name/$this->api_key/$set$set_data.json";
/* set transient ID for later */
$transient = $user_name . '_' . $set . $set_data;
if ( $allow_cache ) {
$cache_results = $this->set_cache( $transient, $url, $timeout );
$results = $cache_results;
} else {
$results = $this->remote_request( $url );
}
if ( isset( $results->error ) ) {
$this->set_error( 'error_' . $set, $results->error );
}
if ( $errors = $this->api_errors() ) {
$this->clear_cache( $transient );
return $errors;
}
if ( isset( $results->$set ) ) {
return $results->$set;
}
return false;
}
/**
* Used to list purchased themes.
*
* @param bool Allow API calls to be cached. Default true.
* @param int Set transient timeout. Default 300 seconds (5 minutes).
* @return object If user has purchased themes, returns an object containing those details.
*
* @access public
* @since 1.0
* @updated 1.3
*/
public function wp_list_themes( $allow_cache = true, $timeout = 300 ) {
return $this->private_user_data( 'wp-list-themes', $this->user_name, '', $allow_cache, $timeout );
}
/**
* Used to download a purchased item.
*
* This method does not allow caching.
*
* @param string The purchased items id
* @return string|bool If item purchased, returns the download URL.
*
* @access public
* @since 1.0
*/
public function wp_download( $item_id ) {
if ( ! isset( $item_id ) ) {
$this->set_error( 'item_id', __( 'The Envato Marketplace "item ID" is a required parameter.', 'envato' ) );
}
$download = $this->private_user_data( 'wp-download', $this->user_name, $item_id );
if ( $errors = $this->api_errors() ) {
return $errors;
} else if ( isset( $download->url ) ) {
return $download->url;
}
return false;
}
/**
* Retrieve the details for a specific marketplace item.
*
* @param string $item_id The id of the item you need information for.
* @return object Details for the given item.
*
* @access public
* @since 1.0
* @updated 1.3
*/
public function item_details( $item_id, $allow_cache = true, $timeout = 300 ) {
$url = preg_replace( '/set/i', 'item:' . $item_id, $this->public_url );
/* set transient ID for later */
$transient = 'item_' . $item_id;
if ( $allow_cache ) {
$cache_results = $this->set_cache( $transient, $url, $timeout );
$results = $cache_results;
} else {
$results = $this->remote_request( $url );
}
if ( isset( $results->error ) ) {
$this->set_error( 'error_item_' . $item_id, $results->error );
}
if ( $errors = $this->api_errors() ) {
$this->clear_cache( $transient );
return $errors;
}
if ( isset( $results->item ) ) {
return $results->item;
}
return false;
}
/**
* Set cache with the Transients API.
*
* @link http://codex.wordpress.org/Transients_API
*
* @param string Transient ID.
* @param string The URL of the API request.
* @param int Set transient timeout. Default 300 seconds (5 minutes).
* @return mixed
*
* @access public
* @since 1.3
*/
public function set_cache( $transient = '', $url = '', $timeout = 300 ) {
if ( $transient == '' || $url == '' ) {
return false;
}
/* keep the code below cleaner */
$transient = $this->validate_transient( $transient );
$transient_timeout = '_transient_timeout_' . $transient;
/* set original cache before we destroy it */
$old_cache = get_option( $transient_timeout ) < time() ? get_option( $transient ) : '';
/* look for a cached result and return if exists */
if ( false !== $results = get_transient( $transient ) ) {
return $results;
}
/* create the cache and allow filtering before it's saved */
if ( $results = apply_filters( 'envato_api_set_cache', $this->remote_request( $url ), $transient ) ) {
set_transient( $transient, $results, $timeout );
return $results;
}
return false;
}
/**
* Clear cache with the Transients API.
*
* @link http://codex.wordpress.org/Transients_API
*
* @param string Transient ID.
* @return void
*
* @access public
* @since 1.3
*/
public function clear_cache( $transient = '' ) {
delete_transient( $transient );
}
/**
* Helper function to validate transient ID's.
*
* @param string The transient ID.
* @return string Returns a DB safe transient ID.
*
* @access public
* @since 1.3
*/
public function validate_transient( $id = '' ) {
return preg_replace( '/[^A-Za-z0-9\_\-]/i', '', str_replace( ':', '_', $id ) );
}
/**
* Helper function to set error messages.
*
* @param string The error array id.
* @param string The error message.
* @return void
*
* @access public
* @since 1.0
*/
public function set_error( $id, $error ) {
$this->errors['errors'][$id] = $error;
}
/**
* Helper function to return the set errors.
*
* @return array The errors array.
*
* @access public
* @since 1.0
*/
public function api_errors() {
if ( ! empty( $this->errors['errors'] ) ) {
return $this->errors['errors'];
}
}
/**
* Helper function to query the marketplace API via wp_remote_request.
*
* @param string The url to access.
* @return object The results of the wp_remote_request request.
*
* @access private
* @since 1.0
*/
protected function remote_request( $url ) {
if ( empty( $url ) ) {
return false;
}
$request = wp_remote_request( $url );
if ( is_wp_error( $request ) ) {
return false;
}
$data = json_decode( $request['body'] );
if ( $request['response']['code'] == 200 ) {
return $data;
} else {
$this->set_error( 'http_code', $request['response']['code'] );
}
if ( isset( $data->error ) ) {
$this->set_error( 'api_error', $data->error );
}
return false;
}
/**
* Helper function to print arrays to the screen ofr testing.
*
* @param array The array to print out
* @return string
*
* @access public
* @since 1.0
*/
public function pretty_print( $array ) {
echo '<pre>';
print_r( $array );
echo '</pre>';
}
}
/* End of file class-envato-api.php */
/* Location: ./includes/class-envato-api.php */ | gpl-2.0 |
xuyuan/spark-spl-release | lib/kerosin/sceneserver/sphere.cpp | 1408 | /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "sphere.h"
#include <kerosin/openglserver/openglserver.h>
#include <kerosin/materialserver/material.h>
using namespace kerosin;
using namespace zeitgeist;
using namespace boost;
using namespace salt;
Sphere::Sphere() : SingleMatNode()
{
}
Sphere::~Sphere()
{
}
void Sphere::OnLink()
{
Load("StdUnitSphere");
}
float Sphere::GetRadius() const
{
return mScale[0];
}
void Sphere::SetRadius(float radius)
{
mScale[0] = radius;
mScale[1] = radius;
mScale[2] = radius;
CalcBoundingBox();
}
| gpl-2.0 |
tbaumeist/CommonGraph | src/main/java/com/tbaumeist/common/utils/DistanceTools.java | 598 | package com.tbaumeist.common.utils;
public class DistanceTools {
public static double getDistance(double a, double b) {
if (a > b)
return Math.min(a - b, 1.0 - a + b);
return Math.min(b - a, 1.0 - b + a);
}
public static double calcMidPt(double locA, double locB) {
// distance = (( next +1 ) - me) % 1
double dist = ((locB + 1) - locA) % 1;
// middle = (( distance/2 ) + me ) % 1
return ((dist / 2.0) + locA) % 1;
}
public static double round(double d) {
return Math.round(d * 100000) / 100000.0;
}
}
| gpl-2.0 |
wazuh/wazuh-kibana-app | public/components/overview/compliance-table/components/subrequirements/subrequirements.tsx | 10020 | /*
* Wazuh app - Mitre alerts components
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* 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.
*
* Find more information about this on the LICENSE file.
*/
import React, { Component } from 'react';
import {
EuiFacetButton,
EuiFlexGroup,
EuiFlexGrid,
EuiFlexItem,
EuiTitle,
EuiFieldSearch,
EuiSpacer,
EuiCallOut,
EuiToolTip,
EuiSwitch,
EuiPopover,
EuiText,
EuiIcon,
EuiOverlayMask,
EuiLoadingSpinner,
} from '@elastic/eui';
import { AppNavigate } from '../../../../../react-services/app-navigate';
import { AppState } from '../../../../../react-services/app-state';
import { RequirementFlyout } from '../requirement-flyout/requirement-flyout'
import { WAZUH_ALERTS_PATTERN } from '../../../../../../common/constants';
import { getDataPlugin } from '../../../../../kibana-services';
export class ComplianceSubrequirements extends Component {
_isMount = false;
state: {
}
props!: {
};
constructor(props) {
super(props);
this.state = {
hideAlerts: false,
searchValue: "",
}
}
hideAlerts() {
this.setState({ hideAlerts: !this.state.hideAlerts })
}
onSearchValueChange = e => {
this.setState({ searchValue: e.target.value });
}
/**
* Adds a new filter with format { "filter_key" : "filter_value" }, e.g. {"agent.id": "001"}
* @param filter
*/
addFilter(filter) {
const { filterManager } = getDataPlugin().query;
const matchPhrase = {};
matchPhrase[filter.key] = filter.value;
const newFilter = {
"meta": {
"disabled": false,
"key": filter.key,
"params": { "query": filter.value },
"type": "phrase",
"negate": filter.negate || false,
"index": AppState.getCurrentPattern() || WAZUH_ALERTS_PATTERN
},
"query": { "match_phrase": matchPhrase },
"$state": { "store": "appState" }
}
filterManager.addFilters([newFilter]);
}
getRequirementKey() {
if (this.props.section === 'pci') {
return 'rule.pci_dss';
}
if (this.props.section === 'gdpr') {
return 'rule.gdpr';
}
if (this.props.section === 'nist') {
return 'rule.nist_800_53';
}
if (this.props.section === 'hipaa') {
return 'rule.hipaa';
}
if (this.props.section === 'tsc') {
return 'rule.tsc';
}
return "pci_dss"
}
openDashboardCurrentWindow(requirementId) {
this.addFilter({ key: this.getRequirementKey(), value: requirementId, negate: false });
this.props.onSelectedTabChanged('dashboard');
}
openDiscoverCurrentWindow(requirementId) {
this.addFilter({ key: this.getRequirementKey(), value: requirementId, negate: false });
this.props.onSelectedTabChanged('events');
}
openDiscover(e, requirementId) {
const filters = {};
filters[this.getRequirementKey()] = requirementId;
AppNavigate.navigateToModule(e, 'overview', { "tab": this.props.section, "tabView": "discover", filters, }, () => this.openDiscoverCurrentWindow(requirementId))
}
openDashboard(e, requirementId) {
const filters = {};
filters[this.getRequirementKey()] = requirementId;
AppNavigate.navigateToModule(e, 'overview', { "tab": this.props.section, "tabView": "panels", filters }, () => this.openDashboardCurrentWindow(requirementId))
}
renderFacet() {
const { complianceObject } = this.props;
const { requirementsCount } = this.props;
const tacticsToRender: Array<any> = [];
const showTechniques = {};
Object.keys(complianceObject).forEach((key, inx) => {
const currentTechniques = complianceObject[key];
if (this.props.selectedRequirements[key]) {
currentTechniques.forEach((technique, idx) => {
if (!showTechniques[technique] && ((technique.toLowerCase().includes(this.state.searchValue.toLowerCase())) || this.props.descriptions[technique].toLowerCase().includes(this.state.searchValue.toLowerCase()))) {
const quantity = (requirementsCount.find(item => item.key === technique) || {}).doc_count || 0;
if (!this.state.hideAlerts || (this.state.hideAlerts && quantity > 0)) {
showTechniques[technique] = true;
tacticsToRender.push({
id: technique,
label: `${technique} - ${this.props.descriptions[technique]}`,
quantity
})
}
}
});
}
});
const tacticsToRenderOrdered = tacticsToRender.sort((a, b) => b.quantity - a.quantity).map((item, idx) => {
const tooltipContent = `View details of ${item.id}`
const toolTipAnchorClass = "wz-display-inline-grid" + (this.state.hover === item.id ? " wz-mitre-width" : " ");
return (
<EuiFlexItem
onMouseEnter={() => this.setState({ hover: item.id })}
onMouseLeave={() => this.setState({ hover: "" })}
key={idx} style={{ border: "1px solid #8080804a", maxWidth: "calc(25% - 8px)", maxHeight: 41 }}>
<EuiPopover
id="techniqueActionsContextMenu"
anchorClassName="wz-width-100"
button={(
<EuiFacetButton
style={{ width: "100%", padding: "0 5px 0 5px", lineHeight: "40px", maxHeight: "40px" }}
quantity={item.quantity}
className={"module-table"}
onClick={() => { this.showFlyout(item.id) }}>
<EuiToolTip position="top" content={tooltipContent} anchorClassName={toolTipAnchorClass}>
<span style={{
display: "block",
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
}}>
{item.id} - {this.props.descriptions[item.id]}
</span>
</EuiToolTip>
{this.state.hover === item.id &&
<span style={{ float: "right", position: 'fixed' }}>
<EuiToolTip position="top" content={"Show " + item.id + " in Dashboard"} >
<EuiIcon onMouseDown={(e) => { this.openDashboard(e, item.id); e.stopPropagation() }} color="primary" type="visualizeApp"></EuiIcon>
</EuiToolTip>
<EuiToolTip position="top" content={"Inspect " + item.id + " in Events"} >
<EuiIcon onMouseDown={(e) => { this.openDiscover(e, item.id); e.stopPropagation() }} color="primary" type="discoverApp"></EuiIcon>
</EuiToolTip>
</span>
}
</EuiFacetButton>
)
}
isOpen={this.state.actionsOpen === item.id}
closePopover={() => { }}
panelPaddingSize="none"
style={{ width: "100%" }}
anchorPosition="downLeft">xxx
</EuiPopover>
</EuiFlexItem>
);
})
if (tacticsToRender.length) {
return (
<EuiFlexGrid columns={4} gutterSize="s" style={{ maxHeight: "calc(100vh - 420px)", overflow: "overlay", overflowX: "hidden", maxWidth: "82vw", paddingRight: 10 }}>
{tacticsToRenderOrdered}
</EuiFlexGrid>
)
} else {
return <EuiCallOut title='There are no results.' iconType='help' color='warning'></EuiCallOut>
}
}
onChangeFlyout = (flyoutOn) => {
this.setState({ flyoutOn });
}
closeFlyout() {
this.setState({ flyoutOn: false });
}
showFlyout(requirement) {
this.setState({
selectedRequirement: requirement,
flyoutOn: true
})
}
render() {
return (
<div style={{ padding: 10 }}>
<EuiFlexGroup>
<EuiFlexItem grow={true}>
<EuiTitle size="m">
<h1>Requirements</h1>
</EuiTitle>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiFlexGroup>
<EuiFlexItem grow={false}>
<EuiText grow={false}>
<span>Hide requirements with no alerts </span>
<EuiSwitch
label=""
checked={this.state.hideAlerts}
onChange={e => this.hideAlerts()}
/>
</EuiText>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
<EuiSpacer size="xs" />
<EuiFieldSearch
fullWidth={true}
placeholder="Filter requirements"
value={this.state.searchValue}
onChange={e => this.onSearchValueChange(e)}
isClearable={true}
aria-label="Use aria labels when no actual label is in use"
/>
<EuiSpacer size="s" />
<div>
{this.props.loadingAlerts
? <EuiFlexItem style={{ height: "calc(100vh - 410px)", alignItems: 'center' }} >
<EuiLoadingSpinner size='xl' style={{ margin: 0, position: 'absolute', top: '50%', transform: 'translateY(-50%)' }} />
</EuiFlexItem>
: this.props.requirementsCount && this.renderFacet()
}
</div>
{this.state.flyoutOn &&
<EuiOverlayMask
headerZindexLocation="below"
onClick={() => this.closeFlyout() } >
<RequirementFlyout
currentRequirement={this.state.selectedRequirement}
onChangeFlyout={this.onChangeFlyout}
description={this.props.descriptions[this.state.selectedRequirement]}
getRequirementKey={() => { return this.getRequirementKey() }}
openDashboard={(e, itemId) => this.openDashboard(e, itemId)}
openDiscover={(e, itemId) => this.openDiscover(e, itemId)}
/>
</EuiOverlayMask>}
</div>
)
}
}
| gpl-2.0 |
VasilyNemkov/percona-xtrabackup | storage/innobase/rem/rem0cmp.cc | 39162 | /*****************************************************************************
Copyright (c) 1994, 2012, Oracle and/or its affiliates. All Rights Reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/*******************************************************************//**
@file rem/rem0cmp.cc
Comparison services for records
Created 7/1/1994 Heikki Tuuri
************************************************************************/
#include "rem0cmp.h"
#ifdef UNIV_NONINL
#include "rem0cmp.ic"
#endif
#include "ha_prototypes.h"
#include "handler0alter.h"
#include "srv0srv.h"
/* ALPHABETICAL ORDER
==================
The records are put into alphabetical order in the following
way: let F be the first field where two records disagree.
If there is a character in some position n where the
records disagree, the order is determined by comparison of
the characters at position n, possibly after
collating transformation. If there is no such character,
but the corresponding fields have different lengths, then
if the data type of the fields is paddable,
shorter field is padded with a padding character. If the
data type is not paddable, longer field is considered greater.
Finally, the SQL null is bigger than any other value.
At the present, the comparison functions return 0 in the case,
where two records disagree only in the way that one
has more fields than the other. */
#ifdef UNIV_DEBUG
/*************************************************************//**
Used in debug checking of cmp_dtuple_... .
This function is used to compare a data tuple to a physical record. If
dtuple has n fields then rec must have either m >= n fields, or it must
differ from dtuple in some of the m fields rec has.
@return 1, 0, -1, if dtuple is greater, equal, less than rec,
respectively, when only the common first fields are compared */
static
int
cmp_debug_dtuple_rec_with_match(
/*============================*/
const dtuple_t* dtuple, /*!< in: data tuple */
const rec_t* rec, /*!< in: physical record which differs from
dtuple in some of the common fields, or which
has an equal number or more fields than
dtuple */
const ulint* offsets,/*!< in: array returned by rec_get_offsets() */
ulint n_cmp, /*!< in: number of fields to compare */
ulint* matched_fields);/*!< in/out: number of already
completely matched fields; when function
returns, contains the value for current
comparison */
#endif /* UNIV_DEBUG */
/*************************************************************//**
This function is used to compare two data fields for which the data type
is such that we must use MySQL code to compare them. The prototype here
must be a copy of the one in ha_innobase.cc!
@return 1, 0, -1, if a is greater, equal, less than b, respectively */
extern
int
innobase_mysql_cmp(
/*===============*/
int mysql_type, /*!< in: MySQL type */
uint charset_number, /*!< in: number of the charset */
const unsigned char* a, /*!< in: data field */
unsigned int a_length, /*!< in: data field length,
not UNIV_SQL_NULL */
const unsigned char* b, /*!< in: data field */
unsigned int b_length); /*!< in: data field length,
not UNIV_SQL_NULL */
/*************************************************************//**
This function is used to compare two data fields for which the data type
is such that we must use MySQL code to compare them. The prototype here
must be a copy of the one in ha_innobase.cc!
@return 1, 0, -1, if a is greater, equal, less than b, respectively */
extern
int
innobase_mysql_cmp_prefix(
/*======================*/
int mysql_type, /*!< in: MySQL type */
uint charset_number, /*!< in: number of the charset */
const unsigned char* a, /*!< in: data field */
unsigned int a_length, /*!< in: data field length,
not UNIV_SQL_NULL */
const unsigned char* b, /*!< in: data field */
unsigned int b_length); /*!< in: data field length,
not UNIV_SQL_NULL */
/*********************************************************************//**
Transforms the character code so that it is ordered appropriately for the
language. This is only used for the latin1 char set. MySQL does the
comparisons for other char sets.
@return collation order position */
UNIV_INLINE
ulint
cmp_collate(
/*========*/
ulint code) /*!< in: code of a character stored in database record */
{
return((ulint) srv_latin1_ordering[code]);
}
/*************************************************************//**
Returns TRUE if two columns are equal for comparison purposes.
@return TRUE if the columns are considered equal in comparisons */
UNIV_INTERN
ibool
cmp_cols_are_equal(
/*===============*/
const dict_col_t* col1, /*!< in: column 1 */
const dict_col_t* col2, /*!< in: column 2 */
ibool check_charsets)
/*!< in: whether to check charsets */
{
if (dtype_is_non_binary_string_type(col1->mtype, col1->prtype)
&& dtype_is_non_binary_string_type(col2->mtype, col2->prtype)) {
/* Both are non-binary string types: they can be compared if
and only if the charset-collation is the same */
if (check_charsets) {
return(dtype_get_charset_coll(col1->prtype)
== dtype_get_charset_coll(col2->prtype));
} else {
return(TRUE);
}
}
if (dtype_is_binary_string_type(col1->mtype, col1->prtype)
&& dtype_is_binary_string_type(col2->mtype, col2->prtype)) {
/* Both are binary string types: they can be compared */
return(TRUE);
}
if (col1->mtype != col2->mtype) {
return(FALSE);
}
if (col1->mtype == DATA_INT
&& (col1->prtype & DATA_UNSIGNED)
!= (col2->prtype & DATA_UNSIGNED)) {
/* The storage format of an unsigned integer is different
from a signed integer: in a signed integer we OR
0x8000... to the value of positive integers. */
return(FALSE);
}
return(col1->mtype != DATA_INT || col1->len == col2->len);
}
/*************************************************************//**
Innobase uses this function to compare two data fields for which the data type
is such that we must compare whole fields or call MySQL to do the comparison
@return 1, 0, -1, if a is greater, equal, less than b, respectively */
static
int
cmp_whole_field(
/*============*/
ulint mtype, /*!< in: main type */
ulint prtype, /*!< in: precise type */
const byte* a, /*!< in: data field */
unsigned int a_length, /*!< in: data field length,
not UNIV_SQL_NULL */
const byte* b, /*!< in: data field */
unsigned int b_length) /*!< in: data field length,
not UNIV_SQL_NULL */
{
float f_1;
float f_2;
double d_1;
double d_2;
int swap_flag = 1;
switch (mtype) {
case DATA_DECIMAL:
/* Remove preceding spaces */
for (; a_length && *a == ' '; a++, a_length--) { }
for (; b_length && *b == ' '; b++, b_length--) { }
if (*a == '-') {
if (*b != '-') {
return(-1);
}
a++; b++;
a_length--;
b_length--;
swap_flag = -1;
} else if (*b == '-') {
return(1);
}
while (a_length > 0 && (*a == '+' || *a == '0')) {
a++; a_length--;
}
while (b_length > 0 && (*b == '+' || *b == '0')) {
b++; b_length--;
}
if (a_length != b_length) {
if (a_length < b_length) {
return(-swap_flag);
}
return(swap_flag);
}
while (a_length > 0 && *a == *b) {
a++; b++; a_length--;
}
if (a_length == 0) {
return(0);
}
if (*a > *b) {
return(swap_flag);
}
return(-swap_flag);
case DATA_DOUBLE:
d_1 = mach_double_read(a);
d_2 = mach_double_read(b);
if (d_1 > d_2) {
return(1);
} else if (d_2 > d_1) {
return(-1);
}
return(0);
case DATA_FLOAT:
f_1 = mach_float_read(a);
f_2 = mach_float_read(b);
if (f_1 > f_2) {
return(1);
} else if (f_2 > f_1) {
return(-1);
}
return(0);
case DATA_BLOB:
if (prtype & DATA_BINARY_TYPE) {
ut_print_timestamp(stderr);
fprintf(stderr,
" InnoDB: Error: comparing a binary BLOB"
" with a character set sensitive\n"
"InnoDB: comparison!\n");
}
/* fall through */
case DATA_VARMYSQL:
case DATA_MYSQL:
return(innobase_mysql_cmp(
(int)(prtype & DATA_MYSQL_TYPE_MASK),
(uint) dtype_get_charset_coll(prtype),
a, a_length, b, b_length));
default:
fprintf(stderr,
"InnoDB: unknown type number %lu\n",
(ulong) mtype);
ut_error;
}
return(0);
}
/*****************************************************************
This function is used to compare two dfields where at least the first
has its data type field set. */
UNIV_INTERN
int
cmp_dfield_dfield_like_prefix(
/*==========================*/
/* out: 1, 0, -1, if dfield1 is greater, equal,
less than dfield2, respectively */
dfield_t* dfield1,/* in: data field; must have type field set */
dfield_t* dfield2)/* in: data field */
{
const dtype_t* type;
int ret;
ut_ad(dfield_check_typed(dfield1));
type = dfield_get_type(dfield1);
if (type->mtype >= DATA_FLOAT) {
ret = innobase_mysql_cmp_prefix(
static_cast<int>(type->prtype & DATA_MYSQL_TYPE_MASK),
static_cast<uint>(dtype_get_charset_coll(type->prtype)),
static_cast<byte*>(dfield_get_data(dfield1)),
static_cast<uint>(dfield_get_len(dfield1)),
static_cast<byte*>(dfield_get_data(dfield2)),
static_cast<uint>(dfield_get_len(dfield2)));
} else {
ret = (cmp_data_data_like_prefix(
static_cast<byte*>(dfield_get_data(dfield1)),
dfield_get_len(dfield1),
static_cast<byte*>(dfield_get_data(dfield2)),
dfield_get_len(dfield2)));
}
return(ret);
}
/*************************************************************//**
This function is used to compare two data fields for which we know the
data type.
@return 1, 0, -1, if data1 is greater, equal, less than data2, respectively */
UNIV_INTERN
int
cmp_data_data_slow(
/*===============*/
ulint mtype, /*!< in: main type */
ulint prtype, /*!< in: precise type */
const byte* data1, /*!< in: data field (== a pointer to a memory
buffer) */
ulint len1, /*!< in: data field length or UNIV_SQL_NULL */
const byte* data2, /*!< in: data field (== a pointer to a memory
buffer) */
ulint len2) /*!< in: data field length or UNIV_SQL_NULL */
{
ulint data1_byte;
ulint data2_byte;
ulint cur_bytes;
if (len1 == UNIV_SQL_NULL || len2 == UNIV_SQL_NULL) {
if (len1 == len2) {
return(0);
}
if (len1 == UNIV_SQL_NULL) {
/* We define the SQL null to be the smallest possible
value of a field in the alphabetical order */
return(-1);
}
return(1);
}
if (mtype >= DATA_FLOAT
|| (mtype == DATA_BLOB
&& 0 == (prtype & DATA_BINARY_TYPE)
&& dtype_get_charset_coll(prtype)
!= DATA_MYSQL_LATIN1_SWEDISH_CHARSET_COLL)) {
return(cmp_whole_field(mtype, prtype,
data1, (unsigned) len1,
data2, (unsigned) len2));
}
/* Compare then the fields */
cur_bytes = 0;
for (;;) {
if (len1 <= cur_bytes) {
if (len2 <= cur_bytes) {
return(0);
}
data1_byte = dtype_get_pad_char(mtype, prtype);
if (data1_byte == ULINT_UNDEFINED) {
return(-1);
}
} else {
data1_byte = *data1;
}
if (len2 <= cur_bytes) {
data2_byte = dtype_get_pad_char(mtype, prtype);
if (data2_byte == ULINT_UNDEFINED) {
return(1);
}
} else {
data2_byte = *data2;
}
if (data1_byte == data2_byte) {
/* If the bytes are equal, they will remain such even
after the collation transformation below */
goto next_byte;
}
if (mtype <= DATA_CHAR
|| (mtype == DATA_BLOB
&& 0 == (prtype & DATA_BINARY_TYPE))) {
data1_byte = cmp_collate(data1_byte);
data2_byte = cmp_collate(data2_byte);
}
if (data1_byte > data2_byte) {
return(1);
} else if (data1_byte < data2_byte) {
return(-1);
}
next_byte:
/* Next byte */
cur_bytes++;
data1++;
data2++;
}
return(0); /* Not reached */
}
/*****************************************************************
This function is used to compare two data fields for which we know the
data type to be VARCHAR */
int
cmp_data_data_slow_varchar(
/*=======================*/
/* out: 1, 0, -1, if lhs is greater, equal,
less than rhs, respectively */
const byte* lhs, /* in: data field (== a pointer to a memory
buffer) */
ulint lhs_len,/* in: data field length or UNIV_SQL_NULL */
const byte* rhs, /* in: data field (== a pointer to a memory
buffer) */
ulint rhs_len)/* in: data field length or UNIV_SQL_NULL */
{
ulint i;
ut_a(rhs_len != UNIV_SQL_NULL);
if (lhs_len == UNIV_SQL_NULL) {
/* We define the SQL null to be the smallest possible
value of a field in the alphabetical order */
return(-1);
}
/* Compare the values.*/
for (i = 0; i < lhs_len && i < rhs_len; ++i, ++rhs, ++lhs) {
ulint lhs_byte = *lhs;
ulint rhs_byte = *rhs;
if (lhs_byte != rhs_byte) {
/* If the bytes are equal, they will remain such even
after the collation transformation below */
lhs_byte = cmp_collate(lhs_byte);
rhs_byte = cmp_collate(rhs_byte);
if (lhs_byte > rhs_byte) {
return(1);
} else if (lhs_byte < rhs_byte) {
return(-1);
}
}
}
return((i == lhs_len && i == rhs_len) ? 0 :
static_cast<int>(rhs_len - lhs_len));
}
/*****************************************************************
This function is used to compare two data fields for which we know the
data type. The comparison is done for the LIKE operator.*/
int
cmp_data_data_slow_like_prefix(
/*===========================*/
/* out: 1, 0, -1, if lhs is greater, equal,
less than rhs, respectively */
const byte* lhs, /* in: data field (== a pointer to a memory
buffer) */
ulint len1, /* in: data field length or UNIV_SQL_NULL */
const byte* rhs, /* in: data field (== a pointer to a memory
buffer) */
ulint len2) /* in: data field length or UNIV_SQL_NULL */
{
ulint i;
ut_a(len2 != UNIV_SQL_NULL);
if (len1 == UNIV_SQL_NULL) {
/* We define the SQL null to be the smallest possible
value of a field in the alphabetical order */
return(-1);
}
/* Compare the values.*/
for (i = 0; i < len1 && i < len2; ++i, ++rhs, ++lhs) {
ulint lhs_byte = *lhs;
ulint rhs_byte = *rhs;
if (lhs_byte != rhs_byte) {
/* If the bytes are equal, they will remain such even
after the collation transformation below */
lhs_byte = cmp_collate(lhs_byte);
rhs_byte = cmp_collate(rhs_byte);
if (lhs_byte > rhs_byte) {
return(1);
} else if (lhs_byte < rhs_byte) {
return(-1);
}
}
}
return(i == len2 ? 0 : 1);
}
/*****************************************************************
This function is used to compare two data fields for which we know the
data type. The comparison is done for the LIKE operator.*/
int
cmp_data_data_slow_like_suffix(
/*===========================*/
/* out: 1, 0, -1, if data1 is greater, equal,
less than data2, respectively */
/* in: data field (== a pointer to a
memory buffer) */
const byte* data1 UNIV_UNUSED,
/* in: data field length or UNIV_SQL_NULL */
ulint len1 UNIV_UNUSED,
/* in: data field (== a pointer to a memory
buffer) */
const byte* data2 UNIV_UNUSED,
/* in: data field length or UNIV_SQL_NULL */
ulint len2 UNIV_UNUSED)
{
ut_error; // FIXME:
return(1);
}
/*****************************************************************
This function is used to compare two data fields for which we know the
data type. The comparison is done for the LIKE operator.*/
int
cmp_data_data_slow_like_substr(
/*===========================*/
/* out: 1, 0, -1, if data1 is greater, equal,
less than data2, respectively */
/* in: data field (== a pointer to a
memory buffer) */
const byte* data1 UNIV_UNUSED,
/* in: data field length or UNIV_SQL_NULL */
ulint len1 UNIV_UNUSED,
/* in: data field (== a pointer to a memory
buffer) */
const byte* data2 UNIV_UNUSED,
/* in: data field length or UNIV_SQL_NULL */
ulint len2 UNIV_UNUSED)
{
ut_error; // FIXME:
return(1);
}
/*************************************************************//**
This function is used to compare a data tuple to a physical record.
Only dtuple->n_fields_cmp first fields are taken into account for
the data tuple! If we denote by n = n_fields_cmp, then rec must
have either m >= n fields, or it must differ from dtuple in some of
the m fields rec has. If rec has an externally stored field we do not
compare it but return with value 0 if such a comparison should be
made.
@return 1, 0, -1, if dtuple is greater, equal, less than rec,
respectively, when only the common first fields are compared, or until
the first externally stored field in rec */
UNIV_INTERN
int
cmp_dtuple_rec_with_match_low(
/*==========================*/
const dtuple_t* dtuple, /*!< in: data tuple */
const rec_t* rec, /*!< in: physical record which differs from
dtuple in some of the common fields, or which
has an equal number or more fields than
dtuple */
const ulint* offsets,/*!< in: array returned by rec_get_offsets() */
ulint n_cmp, /*!< in: number of fields to compare */
ulint* matched_fields, /*!< in/out: number of already completely
matched fields; when function returns,
contains the value for current comparison */
ulint* matched_bytes) /*!< in/out: number of already matched
bytes within the first field not completely
matched; when function returns, contains the
value for current comparison */
{
const dfield_t* dtuple_field; /* current field in logical record */
ulint dtuple_f_len; /* the length of the current field
in the logical record */
const byte* dtuple_b_ptr; /* pointer to the current byte in
logical field data */
ulint dtuple_byte; /* value of current byte to be compared
in dtuple*/
ulint rec_f_len; /* length of current field in rec */
const byte* rec_b_ptr; /* pointer to the current byte in
rec field */
ulint rec_byte; /* value of current byte to be
compared in rec */
ulint cur_field; /* current field number */
ulint cur_bytes; /* number of already matched bytes
in current field */
int ret; /* return value */
ut_ad(dtuple != NULL);
ut_ad(rec != NULL);
ut_ad(matched_fields != NULL);
ut_ad(matched_bytes != NULL);
ut_ad(dtuple_check_typed(dtuple));
ut_ad(rec_offs_validate(rec, NULL, offsets));
cur_field = *matched_fields;
cur_bytes = *matched_bytes;
ut_ad(n_cmp > 0);
ut_ad(n_cmp <= dtuple_get_n_fields(dtuple));
ut_ad(cur_field <= n_cmp);
ut_ad(cur_field <= rec_offs_n_fields(offsets));
if (cur_bytes == 0 && cur_field == 0) {
ulint rec_info = rec_get_info_bits(rec,
rec_offs_comp(offsets));
ulint tup_info = dtuple_get_info_bits(dtuple);
if (UNIV_UNLIKELY(rec_info & REC_INFO_MIN_REC_FLAG)) {
ret = !(tup_info & REC_INFO_MIN_REC_FLAG);
goto order_resolved;
} else if (UNIV_UNLIKELY(tup_info & REC_INFO_MIN_REC_FLAG)) {
ret = -1;
goto order_resolved;
}
}
/* Match fields in a loop; stop if we run out of fields in dtuple
or find an externally stored field */
while (cur_field < n_cmp) {
ulint mtype;
ulint prtype;
dtuple_field = dtuple_get_nth_field(dtuple, cur_field);
{
const dtype_t* type
= dfield_get_type(dtuple_field);
mtype = type->mtype;
prtype = type->prtype;
}
dtuple_f_len = dfield_get_len(dtuple_field);
rec_b_ptr = rec_get_nth_field(rec, offsets,
cur_field, &rec_f_len);
/* If we have matched yet 0 bytes, it may be that one or
both the fields are SQL null, or the record or dtuple may be
the predefined minimum record, or the field is externally
stored */
if (UNIV_LIKELY(cur_bytes == 0)) {
if (rec_offs_nth_extern(offsets, cur_field)) {
/* We do not compare to an externally
stored field */
ret = 0;
goto order_resolved;
}
if (dtuple_f_len == UNIV_SQL_NULL) {
if (rec_f_len == UNIV_SQL_NULL) {
goto next_field;
}
ret = -1;
goto order_resolved;
} else if (rec_f_len == UNIV_SQL_NULL) {
/* We define the SQL null to be the
smallest possible value of a field
in the alphabetical order */
ret = 1;
goto order_resolved;
}
}
if (mtype >= DATA_FLOAT
|| (mtype == DATA_BLOB
&& 0 == (prtype & DATA_BINARY_TYPE)
&& dtype_get_charset_coll(prtype)
!= DATA_MYSQL_LATIN1_SWEDISH_CHARSET_COLL)) {
ret = cmp_whole_field(
mtype, prtype,
static_cast<const byte*>(
dfield_get_data(dtuple_field)),
(unsigned) dtuple_f_len,
rec_b_ptr, (unsigned) rec_f_len);
if (ret != 0) {
cur_bytes = 0;
goto order_resolved;
} else {
goto next_field;
}
}
/* Set the pointers at the current byte */
rec_b_ptr = rec_b_ptr + cur_bytes;
dtuple_b_ptr = (byte*) dfield_get_data(dtuple_field)
+ cur_bytes;
/* Compare then the fields */
for (;;) {
if (UNIV_UNLIKELY(rec_f_len <= cur_bytes)) {
if (dtuple_f_len <= cur_bytes) {
goto next_field;
}
rec_byte = dtype_get_pad_char(mtype, prtype);
if (rec_byte == ULINT_UNDEFINED) {
ret = 1;
goto order_resolved;
}
} else {
rec_byte = *rec_b_ptr;
}
if (UNIV_UNLIKELY(dtuple_f_len <= cur_bytes)) {
dtuple_byte = dtype_get_pad_char(mtype,
prtype);
if (dtuple_byte == ULINT_UNDEFINED) {
ret = -1;
goto order_resolved;
}
} else {
dtuple_byte = *dtuple_b_ptr;
}
if (dtuple_byte == rec_byte) {
/* If the bytes are equal, they will
remain such even after the collation
transformation below */
goto next_byte;
}
if (mtype <= DATA_CHAR
|| (mtype == DATA_BLOB
&& !(prtype & DATA_BINARY_TYPE))) {
rec_byte = cmp_collate(rec_byte);
dtuple_byte = cmp_collate(dtuple_byte);
}
ret = (int) (dtuple_byte - rec_byte);
if (UNIV_LIKELY(ret)) {
if (ret < 0) {
ret = -1;
goto order_resolved;
} else {
ret = 1;
goto order_resolved;
}
}
next_byte:
/* Next byte */
cur_bytes++;
rec_b_ptr++;
dtuple_b_ptr++;
}
next_field:
cur_field++;
cur_bytes = 0;
}
ut_ad(cur_bytes == 0);
ret = 0; /* If we ran out of fields, dtuple was equal to rec
up to the common fields */
order_resolved:
ut_ad((ret >= - 1) && (ret <= 1));
ut_ad(ret == cmp_debug_dtuple_rec_with_match(dtuple, rec, offsets,
n_cmp, matched_fields));
ut_ad(*matched_fields == cur_field); /* In the debug version, the
above cmp_debug_... sets
*matched_fields to a value */
*matched_fields = cur_field;
*matched_bytes = cur_bytes;
return(ret);
}
/**************************************************************//**
Compares a data tuple to a physical record.
@see cmp_dtuple_rec_with_match
@return 1, 0, -1, if dtuple is greater, equal, less than rec, respectively */
UNIV_INTERN
int
cmp_dtuple_rec(
/*===========*/
const dtuple_t* dtuple, /*!< in: data tuple */
const rec_t* rec, /*!< in: physical record */
const ulint* offsets)/*!< in: array returned by rec_get_offsets() */
{
ulint matched_fields = 0;
ulint matched_bytes = 0;
ut_ad(rec_offs_validate(rec, NULL, offsets));
return(cmp_dtuple_rec_with_match(dtuple, rec, offsets,
&matched_fields, &matched_bytes));
}
/**************************************************************//**
Checks if a dtuple is a prefix of a record. The last field in dtuple
is allowed to be a prefix of the corresponding field in the record.
@return TRUE if prefix */
UNIV_INTERN
ibool
cmp_dtuple_is_prefix_of_rec(
/*========================*/
const dtuple_t* dtuple, /*!< in: data tuple */
const rec_t* rec, /*!< in: physical record */
const ulint* offsets)/*!< in: array returned by rec_get_offsets() */
{
ulint n_fields;
ulint matched_fields = 0;
ulint matched_bytes = 0;
ut_ad(rec_offs_validate(rec, NULL, offsets));
n_fields = dtuple_get_n_fields(dtuple);
if (n_fields > rec_offs_n_fields(offsets)) {
return(FALSE);
}
cmp_dtuple_rec_with_match(dtuple, rec, offsets,
&matched_fields, &matched_bytes);
if (matched_fields == n_fields) {
return(TRUE);
}
if (matched_fields == n_fields - 1
&& matched_bytes == dfield_get_len(
dtuple_get_nth_field(dtuple, n_fields - 1))) {
return(TRUE);
}
return(FALSE);
}
/*************************************************************//**
Compare two physical record fields.
@retval 1 if rec1 field is greater than rec2
@retval -1 if rec1 field is less than rec2
@retval 0 if rec1 field equals to rec2 */
static __attribute__((nonnull, warn_unused_result))
int
cmp_rec_rec_simple_field(
/*=====================*/
const rec_t* rec1, /*!< in: physical record */
const rec_t* rec2, /*!< in: physical record */
const ulint* offsets1,/*!< in: rec_get_offsets(rec1, ...) */
const ulint* offsets2,/*!< in: rec_get_offsets(rec2, ...) */
const dict_index_t* index, /*!< in: data dictionary index */
ulint n) /*!< in: field to compare */
{
const byte* rec1_b_ptr;
const byte* rec2_b_ptr;
ulint rec1_f_len;
ulint rec2_f_len;
const dict_col_t* col = dict_index_get_nth_col(index, n);
ut_ad(!rec_offs_nth_extern(offsets1, n));
ut_ad(!rec_offs_nth_extern(offsets2, n));
rec1_b_ptr = rec_get_nth_field(rec1, offsets1, n, &rec1_f_len);
rec2_b_ptr = rec_get_nth_field(rec2, offsets2, n, &rec2_f_len);
if (rec1_f_len == UNIV_SQL_NULL || rec2_f_len == UNIV_SQL_NULL) {
if (rec1_f_len == rec2_f_len) {
return(0);
}
/* We define the SQL null to be the smallest possible
value of a field in the alphabetical order */
return(rec1_f_len == UNIV_SQL_NULL ? -1 : 1);
}
if (col->mtype >= DATA_FLOAT
|| (col->mtype == DATA_BLOB
&& !(col->prtype & DATA_BINARY_TYPE)
&& dtype_get_charset_coll(col->prtype)
!= DATA_MYSQL_LATIN1_SWEDISH_CHARSET_COLL)) {
return(cmp_whole_field(col->mtype, col->prtype,
rec1_b_ptr, (unsigned) rec1_f_len,
rec2_b_ptr, (unsigned) rec2_f_len));
}
/* Compare the fields */
for (ulint cur_bytes = 0;; cur_bytes++, rec1_b_ptr++, rec2_b_ptr++) {
ulint rec1_byte;
ulint rec2_byte;
if (rec2_f_len <= cur_bytes) {
if (rec1_f_len <= cur_bytes) {
return(0);
}
rec2_byte = dtype_get_pad_char(
col->mtype, col->prtype);
if (rec2_byte == ULINT_UNDEFINED) {
return(1);
}
} else {
rec2_byte = *rec2_b_ptr;
}
if (rec1_f_len <= cur_bytes) {
rec1_byte = dtype_get_pad_char(
col->mtype, col->prtype);
if (rec1_byte == ULINT_UNDEFINED) {
return(-1);
}
} else {
rec1_byte = *rec1_b_ptr;
}
if (rec1_byte == rec2_byte) {
/* If the bytes are equal, they will remain such
even after the collation transformation below */
continue;
}
if (col->mtype <= DATA_CHAR
|| (col->mtype == DATA_BLOB
&& !(col->prtype & DATA_BINARY_TYPE))) {
rec1_byte = cmp_collate(rec1_byte);
rec2_byte = cmp_collate(rec2_byte);
}
if (rec1_byte < rec2_byte) {
return(-1);
} else if (rec1_byte > rec2_byte) {
return(1);
}
}
}
/*************************************************************//**
Compare two physical records that contain the same number of columns,
none of which are stored externally.
@retval 1 if rec1 (including non-ordering columns) is greater than rec2
@retval -1 if rec1 (including non-ordering columns) is less than rec2
@retval 0 if rec1 is a duplicate of rec2 */
UNIV_INTERN
int
cmp_rec_rec_simple(
/*===============*/
const rec_t* rec1, /*!< in: physical record */
const rec_t* rec2, /*!< in: physical record */
const ulint* offsets1,/*!< in: rec_get_offsets(rec1, ...) */
const ulint* offsets2,/*!< in: rec_get_offsets(rec2, ...) */
const dict_index_t* index, /*!< in: data dictionary index */
struct TABLE* table) /*!< in: MySQL table, for reporting
duplicate key value if applicable,
or NULL */
{
ulint n;
ulint n_uniq = dict_index_get_n_unique(index);
bool null_eq = false;
ut_ad(rec_offs_n_fields(offsets1) >= n_uniq);
ut_ad(rec_offs_n_fields(offsets2) == rec_offs_n_fields(offsets2));
ut_ad(rec_offs_comp(offsets1) == rec_offs_comp(offsets2));
for (n = 0; n < n_uniq; n++) {
int cmp = cmp_rec_rec_simple_field(
rec1, rec2, offsets1, offsets2, index, n);
if (cmp) {
return(cmp);
}
/* If the fields are internally equal, they must both
be NULL or non-NULL. */
ut_ad(rec_offs_nth_sql_null(offsets1, n)
== rec_offs_nth_sql_null(offsets2, n));
if (rec_offs_nth_sql_null(offsets1, n)) {
ut_ad(!(dict_index_get_nth_col(index, n)->prtype
& DATA_NOT_NULL));
null_eq = true;
}
}
/* If we ran out of fields, the ordering columns of rec1 were
equal to rec2. Issue a duplicate key error if needed. */
if (!null_eq && table && dict_index_is_unique(index)) {
/* Report erroneous row using new version of table. */
innobase_rec_to_mysql(table, rec1, index, offsets1);
return(0);
}
/* Else, keep comparing so that we have the full internal
order. */
for (; n < dict_index_get_n_fields(index); n++) {
int cmp = cmp_rec_rec_simple_field(
rec1, rec2, offsets1, offsets2, index, n);
if (cmp) {
return(cmp);
}
/* If the fields are internally equal, they must both
be NULL or non-NULL. */
ut_ad(rec_offs_nth_sql_null(offsets1, n)
== rec_offs_nth_sql_null(offsets2, n));
}
/* This should never be reached. Internally, an index must
never contain duplicate entries. */
ut_ad(0);
return(0);
}
/*************************************************************//**
This function is used to compare two physical records. Only the common
first fields are compared, and if an externally stored field is
encountered, then 0 is returned.
@return 1, 0, -1 if rec1 is greater, equal, less, respectively */
UNIV_INTERN
int
cmp_rec_rec_with_match(
/*===================*/
const rec_t* rec1, /*!< in: physical record */
const rec_t* rec2, /*!< in: physical record */
const ulint* offsets1,/*!< in: rec_get_offsets(rec1, index) */
const ulint* offsets2,/*!< in: rec_get_offsets(rec2, index) */
dict_index_t* index, /*!< in: data dictionary index */
ibool nulls_unequal,
/* in: TRUE if this is for index statistics
cardinality estimation, and innodb_stats_method
is "nulls_unequal" or "nulls_ignored" */
ulint* matched_fields, /*!< in/out: number of already completely
matched fields; when the function returns,
contains the value the for current
comparison */
ulint* matched_bytes) /*!< in/out: number of already matched
bytes within the first field not completely
matched; when the function returns, contains
the value for the current comparison */
{
ulint rec1_n_fields; /* the number of fields in rec */
ulint rec1_f_len; /* length of current field in rec */
const byte* rec1_b_ptr; /* pointer to the current byte
in rec field */
ulint rec1_byte; /* value of current byte to be
compared in rec */
ulint rec2_n_fields; /* the number of fields in rec */
ulint rec2_f_len; /* length of current field in rec */
const byte* rec2_b_ptr; /* pointer to the current byte
in rec field */
ulint rec2_byte; /* value of current byte to be
compared in rec */
ulint cur_field; /* current field number */
ulint cur_bytes; /* number of already matched
bytes in current field */
int ret = 0; /* return value */
ulint comp;
ut_ad(rec1 != NULL);
ut_ad(rec2 != NULL);
ut_ad(index != NULL);
ut_ad(rec_offs_validate(rec1, index, offsets1));
ut_ad(rec_offs_validate(rec2, index, offsets2));
ut_ad(rec_offs_comp(offsets1) == rec_offs_comp(offsets2));
comp = rec_offs_comp(offsets1);
rec1_n_fields = rec_offs_n_fields(offsets1);
rec2_n_fields = rec_offs_n_fields(offsets2);
cur_field = *matched_fields;
cur_bytes = *matched_bytes;
/* Match fields in a loop */
while ((cur_field < rec1_n_fields) && (cur_field < rec2_n_fields)) {
ulint mtype;
ulint prtype;
if (dict_index_is_univ(index)) {
/* This is for the insert buffer B-tree. */
mtype = DATA_BINARY;
prtype = 0;
} else {
const dict_col_t* col
= dict_index_get_nth_col(index, cur_field);
mtype = col->mtype;
prtype = col->prtype;
}
rec1_b_ptr = rec_get_nth_field(rec1, offsets1,
cur_field, &rec1_f_len);
rec2_b_ptr = rec_get_nth_field(rec2, offsets2,
cur_field, &rec2_f_len);
if (cur_bytes == 0) {
if (cur_field == 0) {
/* Test if rec is the predefined minimum
record */
if (UNIV_UNLIKELY(rec_get_info_bits(rec1, comp)
& REC_INFO_MIN_REC_FLAG)) {
if (!(rec_get_info_bits(rec2, comp)
& REC_INFO_MIN_REC_FLAG)) {
ret = -1;
}
goto order_resolved;
} else if (UNIV_UNLIKELY
(rec_get_info_bits(rec2, comp)
& REC_INFO_MIN_REC_FLAG)) {
ret = 1;
goto order_resolved;
}
}
if (rec_offs_nth_extern(offsets1, cur_field)
|| rec_offs_nth_extern(offsets2, cur_field)) {
/* We do not compare to an externally
stored field */
goto order_resolved;
}
if (rec1_f_len == UNIV_SQL_NULL
|| rec2_f_len == UNIV_SQL_NULL) {
if (rec1_f_len == rec2_f_len) {
/* This is limited to stats collection,
cannot use it for regular search */
if (nulls_unequal) {
ret = -1;
} else {
goto next_field;
}
} else if (rec2_f_len == UNIV_SQL_NULL) {
/* We define the SQL null to be the
smallest possible value of a field
in the alphabetical order */
ret = 1;
} else {
ret = -1;
}
goto order_resolved;
}
}
if (mtype >= DATA_FLOAT
|| (mtype == DATA_BLOB
&& 0 == (prtype & DATA_BINARY_TYPE)
&& dtype_get_charset_coll(prtype)
!= DATA_MYSQL_LATIN1_SWEDISH_CHARSET_COLL)) {
ret = cmp_whole_field(mtype, prtype,
rec1_b_ptr,
(unsigned) rec1_f_len,
rec2_b_ptr,
(unsigned) rec2_f_len);
if (ret != 0) {
cur_bytes = 0;
goto order_resolved;
} else {
goto next_field;
}
}
/* Set the pointers at the current byte */
rec1_b_ptr = rec1_b_ptr + cur_bytes;
rec2_b_ptr = rec2_b_ptr + cur_bytes;
/* Compare then the fields */
for (;;) {
if (rec2_f_len <= cur_bytes) {
if (rec1_f_len <= cur_bytes) {
goto next_field;
}
rec2_byte = dtype_get_pad_char(mtype, prtype);
if (rec2_byte == ULINT_UNDEFINED) {
ret = 1;
goto order_resolved;
}
} else {
rec2_byte = *rec2_b_ptr;
}
if (rec1_f_len <= cur_bytes) {
rec1_byte = dtype_get_pad_char(mtype, prtype);
if (rec1_byte == ULINT_UNDEFINED) {
ret = -1;
goto order_resolved;
}
} else {
rec1_byte = *rec1_b_ptr;
}
if (rec1_byte == rec2_byte) {
/* If the bytes are equal, they will remain
such even after the collation transformation
below */
goto next_byte;
}
if (mtype <= DATA_CHAR
|| (mtype == DATA_BLOB
&& !(prtype & DATA_BINARY_TYPE))) {
rec1_byte = cmp_collate(rec1_byte);
rec2_byte = cmp_collate(rec2_byte);
}
if (rec1_byte < rec2_byte) {
ret = -1;
goto order_resolved;
} else if (rec1_byte > rec2_byte) {
ret = 1;
goto order_resolved;
}
next_byte:
/* Next byte */
cur_bytes++;
rec1_b_ptr++;
rec2_b_ptr++;
}
next_field:
cur_field++;
cur_bytes = 0;
}
ut_ad(cur_bytes == 0);
/* If we ran out of fields, rec1 was equal to rec2 up
to the common fields */
ut_ad(ret == 0);
order_resolved:
ut_ad((ret >= - 1) && (ret <= 1));
*matched_fields = cur_field;
*matched_bytes = cur_bytes;
return(ret);
}
#ifdef UNIV_DEBUG
/*************************************************************//**
Used in debug checking of cmp_dtuple_... .
This function is used to compare a data tuple to a physical record. If
dtuple has n fields then rec must have either m >= n fields, or it must
differ from dtuple in some of the m fields rec has. If encounters an
externally stored field, returns 0.
@return 1, 0, -1, if dtuple is greater, equal, less than rec,
respectively, when only the common first fields are compared */
static
int
cmp_debug_dtuple_rec_with_match(
/*============================*/
const dtuple_t* dtuple, /*!< in: data tuple */
const rec_t* rec, /*!< in: physical record which differs from
dtuple in some of the common fields, or which
has an equal number or more fields than
dtuple */
const ulint* offsets,/*!< in: array returned by rec_get_offsets() */
ulint n_cmp, /*!< in: number of fields to compare */
ulint* matched_fields) /*!< in/out: number of already
completely matched fields; when function
returns, contains the value for current
comparison */
{
const dfield_t* dtuple_field; /* current field in logical record */
ulint dtuple_f_len; /* the length of the current field
in the logical record */
const byte* dtuple_f_data; /* pointer to the current logical
field data */
ulint rec_f_len; /* length of current field in rec */
const byte* rec_f_data; /* pointer to the current rec field */
int ret; /* return value */
ulint cur_field; /* current field number */
ut_ad(dtuple != NULL);
ut_ad(rec != NULL);
ut_ad(matched_fields != NULL);
ut_ad(dtuple_check_typed(dtuple));
ut_ad(rec_offs_validate(rec, NULL, offsets));
ut_ad(n_cmp > 0);
ut_ad(n_cmp <= dtuple_get_n_fields(dtuple));
ut_ad(*matched_fields <= n_cmp);
ut_ad(*matched_fields <= rec_offs_n_fields(offsets));
cur_field = *matched_fields;
if (cur_field == 0) {
if (UNIV_UNLIKELY
(rec_get_info_bits(rec, rec_offs_comp(offsets))
& REC_INFO_MIN_REC_FLAG)) {
ret = !(dtuple_get_info_bits(dtuple)
& REC_INFO_MIN_REC_FLAG);
goto order_resolved;
}
if (UNIV_UNLIKELY
(dtuple_get_info_bits(dtuple) & REC_INFO_MIN_REC_FLAG)) {
ret = -1;
goto order_resolved;
}
}
/* Match fields in a loop; stop if we run out of fields in dtuple */
while (cur_field < n_cmp) {
ulint mtype;
ulint prtype;
dtuple_field = dtuple_get_nth_field(dtuple, cur_field);
{
const dtype_t* type
= dfield_get_type(dtuple_field);
mtype = type->mtype;
prtype = type->prtype;
}
dtuple_f_data = static_cast<const byte*>(
dfield_get_data(dtuple_field));
dtuple_f_len = dfield_get_len(dtuple_field);
rec_f_data = rec_get_nth_field(rec, offsets,
cur_field, &rec_f_len);
if (rec_offs_nth_extern(offsets, cur_field)) {
/* We do not compare to an externally stored field */
ret = 0;
goto order_resolved;
}
ret = cmp_data_data(mtype, prtype, dtuple_f_data, dtuple_f_len,
rec_f_data, rec_f_len);
if (ret != 0) {
goto order_resolved;
}
cur_field++;
}
ret = 0; /* If we ran out of fields, dtuple was equal to rec
up to the common fields */
order_resolved:
ut_ad((ret >= - 1) && (ret <= 1));
*matched_fields = cur_field;
return(ret);
}
#endif /* UNIV_DEBUG */
| gpl-2.0 |
Martchus/qtutilities | settingsdialog/qtsettings.cpp | 15943 | #include "./qtsettings.h"
#include "./optioncategory.h"
#include "./optioncategoryfiltermodel.h"
#include "./optioncategorymodel.h"
#include "./optionpage.h"
#include "../paletteeditor/paletteeditor.h"
#include "../widgets/clearlineedit.h"
#include "../resources/resources.h"
#include "ui_qtappearanceoptionpage.h"
#include "ui_qtenvoptionpage.h"
#include "ui_qtlanguageoptionpage.h"
#include <QDir>
#include <QFileDialog>
#include <QFontDialog>
#include <QIcon>
#include <QSettings>
#include <QStringBuilder>
#include <QStyleFactory>
#include <iostream>
#include <memory>
using namespace std;
namespace QtUtilities {
struct QtSettingsData {
QtSettingsData();
QFont font;
QPalette palette;
QString widgetStyle;
QString styleSheetPath;
QString iconTheme;
QLocale defaultLocale;
QString localeName;
QString additionalPluginDirectory;
QString additionalIconThemeSearchPath;
bool customFont;
bool customPalette;
bool customWidgetStyle;
bool customStyleSheet;
bool customIconTheme;
bool customLocale;
};
inline QtSettingsData::QtSettingsData()
: iconTheme(QIcon::themeName())
, localeName(defaultLocale.name())
, customFont(false)
, customPalette(false)
, customWidgetStyle(false)
, customStyleSheet(false)
, customIconTheme(false)
, customLocale(false)
{
}
/*!
* \brief Creates a new settings object.
* \remarks Settings are not restored automatically. Instead, some values (font,
* widget style, ...) are initialized
* from the current Qt configuration. These values are considered as
* system-default.
*/
QtSettings::QtSettings()
: m_d(make_unique<QtSettingsData>())
{
}
/*!
* \brief Destroys the settings object.
* \remarks Unlike QSettings not explicitly saved settings are not saved
* automatically.
*/
QtSettings::~QtSettings()
{
}
/*!
* \brief Returns whether a custom font is set.
*/
bool QtSettings::hasCustomFont() const
{
return m_d->customFont;
}
/*!
* \brief Restores the settings from the specified QSettings object.
* \remarks The restored values are not applied automatically (except
* translation path).
* \sa apply(), save()
*/
void QtSettings::restore(QSettings &settings)
{
settings.beginGroup(QStringLiteral("qt"));
m_d->font.fromString(settings.value(QStringLiteral("font")).toString());
m_d->customFont = settings.value(QStringLiteral("customfont"), false).toBool();
m_d->palette = settings.value(QStringLiteral("palette")).value<QPalette>();
m_d->customPalette = settings.value(QStringLiteral("custompalette"), false).toBool();
m_d->widgetStyle = settings.value(QStringLiteral("widgetstyle"), m_d->widgetStyle).toString();
m_d->customWidgetStyle = settings.value(QStringLiteral("customwidgetstyle"), false).toBool();
m_d->styleSheetPath = settings.value(QStringLiteral("stylesheetpath"), m_d->styleSheetPath).toString();
m_d->customStyleSheet = settings.value(QStringLiteral("customstylesheet"), false).toBool();
m_d->iconTheme = settings.value(QStringLiteral("icontheme"), m_d->iconTheme).toString();
m_d->customIconTheme = settings.value(QStringLiteral("customicontheme"), false).toBool();
m_d->localeName = settings.value(QStringLiteral("locale"), m_d->localeName).toString();
m_d->customLocale = settings.value(QStringLiteral("customlocale"), false).toBool();
m_d->additionalPluginDirectory = settings.value(QStringLiteral("plugindir")).toString();
m_d->additionalIconThemeSearchPath = settings.value(QStringLiteral("iconthemepath")).toString();
TranslationFiles::additionalTranslationFilePath() = settings.value(QStringLiteral("trpath")).toString();
settings.endGroup();
}
/*!
* \brief Saves the settings to the specified QSettings object.
*/
void QtSettings::save(QSettings &settings) const
{
settings.beginGroup(QStringLiteral("qt"));
settings.setValue(QStringLiteral("font"), QVariant(m_d->font.toString()));
settings.setValue(QStringLiteral("customfont"), m_d->customFont);
settings.setValue(QStringLiteral("palette"), QVariant(m_d->palette));
settings.setValue(QStringLiteral("custompalette"), m_d->customPalette);
settings.setValue(QStringLiteral("widgetstyle"), m_d->widgetStyle);
settings.setValue(QStringLiteral("customwidgetstyle"), m_d->customWidgetStyle);
settings.setValue(QStringLiteral("stylesheetpath"), m_d->styleSheetPath);
settings.setValue(QStringLiteral("customstylesheet"), m_d->customStyleSheet);
settings.setValue(QStringLiteral("icontheme"), m_d->iconTheme);
settings.setValue(QStringLiteral("customicontheme"), m_d->customIconTheme);
settings.setValue(QStringLiteral("locale"), m_d->localeName);
settings.setValue(QStringLiteral("customlocale"), m_d->customLocale);
settings.setValue(QStringLiteral("plugindir"), m_d->additionalPluginDirectory);
settings.setValue(QStringLiteral("iconthemepath"), m_d->additionalIconThemeSearchPath);
settings.setValue(QStringLiteral("trpath"), QVariant(TranslationFiles::additionalTranslationFilePath()));
settings.endGroup();
}
/*!
* \brief Applies the current configuration.
* \remarks
* - Some settings take only affect after restarting the application.
* - QApplication/QGuiApplication must be instantiated before calling this
* method.
* - Hence it makes most sense to call this directly after instantiating
* QApplication/QGuiApplication.
*/
void QtSettings::apply()
{
// read style sheet
QString styleSheet;
if (m_d->customStyleSheet && !m_d->styleSheetPath.isEmpty()) {
QFile file(m_d->styleSheetPath);
if (!file.open(QFile::ReadOnly)) {
cerr << "Unable to open the specified stylesheet \"" << m_d->styleSheetPath.toLocal8Bit().data() << "\"." << endl;
}
styleSheet.append(file.readAll());
if (file.error() != QFile::NoError) {
cerr << "Unable to read the specified stylesheet \"" << m_d->styleSheetPath.toLocal8Bit().data() << "\"." << endl;
}
}
// apply appearance
if (m_d->customFont) {
QGuiApplication::setFont(m_d->font);
}
if (m_d->customWidgetStyle) {
QApplication::setStyle(m_d->widgetStyle);
}
if (!styleSheet.isEmpty()) {
if (auto *qapp = qobject_cast<QApplication *>(QApplication::instance())) {
qapp->setStyleSheet(styleSheet);
} else {
cerr << "Unable to apply the specified stylesheet \"" << m_d->styleSheetPath.toLocal8Bit().data()
<< "\" because no QApplication has been instantiated." << endl;
}
}
if (m_d->customPalette) {
QGuiApplication::setPalette(m_d->palette);
}
if (m_d->customIconTheme) {
QIcon::setThemeName(m_d->iconTheme);
}
// apply locale
QLocale::setDefault(m_d->customLocale ? QLocale(m_d->localeName) : m_d->defaultLocale);
// apply environment
if (m_d->additionalPluginDirectory.isEmpty()) {
QCoreApplication::addLibraryPath(m_d->additionalPluginDirectory);
}
if (!m_d->additionalIconThemeSearchPath.isEmpty()) {
QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() << m_d->additionalIconThemeSearchPath);
}
}
/*!
* \brief Returns a new OptionCatecory containing all Qt related option pages.
* \remarks
* - The QtSettings instance does not keep the ownership over the returned
* category.
* - The pages of the returned category require the QtSetings instance which
* hence
* must be present as long as all pages are destroyed.
*/
OptionCategory *QtSettings::category()
{
auto *category = new OptionCategory;
category->setDisplayName(QCoreApplication::translate("QtGui::QtOptionCategory", "Qt"));
category->setIcon(QIcon::fromTheme(QStringLiteral("qtcreator"), QIcon(QStringLiteral(":/qtutilities/icons/hicolor/48x48/apps/qtcreator.svg"))));
category->assignPages({ new QtAppearanceOptionPage(*m_d), new QtLanguageOptionPage(*m_d), new QtEnvOptionPage(*m_d) });
return category;
}
QtAppearanceOptionPage::QtAppearanceOptionPage(QtSettingsData &settings, QWidget *parentWidget)
: QtAppearanceOptionPageBase(parentWidget)
, m_settings(settings)
, m_fontDialog(nullptr)
{
}
QtAppearanceOptionPage::~QtAppearanceOptionPage()
{
}
bool QtAppearanceOptionPage::apply()
{
m_settings.font = ui()->fontComboBox->font();
m_settings.customFont = !ui()->fontCheckBox->isChecked();
m_settings.widgetStyle = ui()->widgetStyleComboBox->currentText();
m_settings.customWidgetStyle = !ui()->widgetStyleCheckBox->isChecked();
m_settings.styleSheetPath = ui()->styleSheetPathSelection->lineEdit()->text();
m_settings.customStyleSheet = !ui()->styleSheetCheckBox->isChecked();
m_settings.palette = ui()->paletteToolButton->palette();
m_settings.customPalette = !ui()->paletteCheckBox->isChecked();
m_settings.iconTheme
= ui()->iconThemeComboBox->currentIndex() != -1 ? ui()->iconThemeComboBox->currentData().toString() : ui()->iconThemeComboBox->currentText();
m_settings.customIconTheme = !ui()->iconThemeCheckBox->isChecked();
return true;
}
void QtAppearanceOptionPage::reset()
{
ui()->fontComboBox->setCurrentFont(m_settings.font);
ui()->fontCheckBox->setChecked(!m_settings.customFont);
ui()->widgetStyleComboBox->setCurrentText(
m_settings.widgetStyle.isEmpty() ? (QApplication::style() ? QApplication::style()->objectName() : QString()) : m_settings.widgetStyle);
ui()->widgetStyleCheckBox->setChecked(!m_settings.customWidgetStyle);
ui()->styleSheetPathSelection->lineEdit()->setText(m_settings.styleSheetPath);
ui()->styleSheetCheckBox->setChecked(!m_settings.customStyleSheet);
ui()->paletteToolButton->setPalette(m_settings.palette);
ui()->paletteCheckBox->setChecked(!m_settings.customPalette);
int iconThemeIndex = ui()->iconThemeComboBox->findData(m_settings.iconTheme);
if (iconThemeIndex != -1) {
ui()->iconThemeComboBox->setCurrentIndex(iconThemeIndex);
} else {
ui()->iconThemeComboBox->setCurrentText(m_settings.iconTheme);
}
ui()->iconThemeCheckBox->setChecked(!m_settings.customIconTheme);
}
QWidget *QtAppearanceOptionPage::setupWidget()
{
// call base implementation first, so ui() is available
auto *widget = QtAppearanceOptionPageBase::setupWidget();
// setup widget style selection
ui()->widgetStyleComboBox->addItems(QStyleFactory::keys());
// setup style sheet selection
ui()->styleSheetPathSelection->provideCustomFileMode(QFileDialog::ExistingFile);
// setup font selection
QObject::connect(ui()->fontPushButton, &QPushButton::clicked, [this] {
if (!m_fontDialog) {
m_fontDialog = new QFontDialog(this->widget());
m_fontDialog->setCurrentFont(ui()->fontComboBox->font());
QObject::connect(m_fontDialog, &QFontDialog::fontSelected, ui()->fontComboBox, &QFontComboBox::setCurrentFont);
QObject::connect(ui()->fontComboBox, &QFontComboBox::currentFontChanged, m_fontDialog, &QFontDialog::setCurrentFont);
}
m_fontDialog->show();
});
// setup palette selection
QObject::connect(ui()->paletteToolButton, &QToolButton::clicked,
[this] { ui()->paletteToolButton->setPalette(PaletteEditor::getPalette(this->widget(), ui()->paletteToolButton->palette())); });
// setup icon theme selection
const QStringList searchPaths = QIcon::themeSearchPaths() << QStringLiteral("/usr/share/icons/");
for (const QString &searchPath : searchPaths) {
const auto dir = QDir(searchPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (const QString &iconTheme : dir) {
const int existingItemIndex = ui()->iconThemeComboBox->findData(iconTheme);
QFile indexFile(searchPath % QChar('/') % iconTheme % QStringLiteral("/index.theme"));
QByteArray index;
if (indexFile.open(QFile::ReadOnly) && !(index = indexFile.readAll()).isEmpty()) {
const auto iconThemeSection = index.indexOf("[Icon Theme]");
const auto nameStart = index.indexOf("Name=", iconThemeSection != -1 ? iconThemeSection : 0);
if (nameStart != -1) {
auto nameLength = index.indexOf("\n", nameStart) - nameStart - 5;
if (nameLength > 0) {
QString displayName = index.mid(nameStart + 5, nameLength);
if (displayName != iconTheme) {
displayName += QChar(' ') % QChar('(') % iconTheme % QChar(')');
}
if (existingItemIndex != -1) {
ui()->iconThemeComboBox->setItemText(existingItemIndex, displayName);
} else {
ui()->iconThemeComboBox->addItem(displayName, iconTheme);
}
continue;
}
}
}
if (existingItemIndex == -1) {
ui()->iconThemeComboBox->addItem(iconTheme, iconTheme);
}
}
}
return widget;
}
QtLanguageOptionPage::QtLanguageOptionPage(QtSettingsData &settings, QWidget *parentWidget)
: QtLanguageOptionPageBase(parentWidget)
, m_settings(settings)
{
}
QtLanguageOptionPage::~QtLanguageOptionPage()
{
}
bool QtLanguageOptionPage::apply()
{
m_settings.localeName = ui()->localeComboBox->currentText();
m_settings.customLocale = !ui()->localeCheckBox->isChecked();
return true;
}
void QtLanguageOptionPage::reset()
{
ui()->localeComboBox->setCurrentText(m_settings.localeName);
ui()->localeCheckBox->setChecked(!m_settings.customLocale);
}
QWidget *QtLanguageOptionPage::setupWidget()
{
// call base implementation first, so ui() is available
auto *widget = QtLanguageOptionPageBase::setupWidget();
// add all available locales to combo box
auto *localeComboBox = ui()->localeComboBox;
const auto locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
for (const QLocale &locale : locales) {
localeComboBox->addItem(locale.name());
}
auto *languageLabel = ui()->languageLabel;
QObject::connect(ui()->localeComboBox, &QComboBox::currentTextChanged, [languageLabel, localeComboBox] {
const QLocale selectedLocale(localeComboBox->currentText());
const QLocale currentLocale;
languageLabel->setText(QCoreApplication::translate("QtGui::QtLanguageOptionPage", "recognized by Qt as") % QStringLiteral(" <i>")
% currentLocale.languageToString(selectedLocale.language()) % QChar(',') % QChar(' ')
% currentLocale.countryToString(selectedLocale.country()) % QStringLiteral("</i>"));
});
return widget;
}
QtEnvOptionPage::QtEnvOptionPage(QtSettingsData &settings, QWidget *parentWidget)
: QtEnvOptionPageBase(parentWidget)
, m_settings(settings)
{
}
QtEnvOptionPage::~QtEnvOptionPage()
{
}
bool QtEnvOptionPage::apply()
{
m_settings.additionalPluginDirectory = ui()->pluginPathSelection->lineEdit()->text();
m_settings.additionalIconThemeSearchPath = ui()->iconThemeSearchPathSelection->lineEdit()->text();
TranslationFiles::additionalTranslationFilePath() = ui()->translationPathSelection->lineEdit()->text();
return true;
}
void QtEnvOptionPage::reset()
{
ui()->pluginPathSelection->lineEdit()->setText(m_settings.additionalPluginDirectory);
ui()->iconThemeSearchPathSelection->lineEdit()->setText(m_settings.additionalIconThemeSearchPath);
ui()->translationPathSelection->lineEdit()->setText(TranslationFiles::additionalTranslationFilePath());
}
} // namespace QtUtilities
INSTANTIATE_UI_FILE_BASED_OPTION_PAGE(QtAppearanceOptionPage)
INSTANTIATE_UI_FILE_BASED_OPTION_PAGE(QtLanguageOptionPage)
INSTANTIATE_UI_FILE_BASED_OPTION_PAGE(QtEnvOptionPage)
| gpl-2.0 |
JeremiasE/KFormula | krita/sdk/templates/filefilter/APPNAMELC_import.cc | 2124 | #include "%{APPNAMELC}_import.h"
#include <kgenericfactory.h>
#include <KoFilterChain.h>
#include <kis_doc2.h>
#include <kis_image.h>
#include "%{APPNAMELC}_converter.h"
typedef KGenericFactory<%{APPNAME}Import> ImportFactory;
K_EXPORT_COMPONENT_FACTORY(libkrita%{APPNAMELC}import, ImportFactory("kofficefilters"))
%{APPNAME}Import::%{APPNAME}Import(QObject *parent, const QStringList&) : KoFilter(parent)
{
}
%{APPNAME}Import::~%{APPNAME}Import()
{
}
KoFilter::ConversionStatus %{APPNAME}Import::convert(const QByteArray&, const QByteArray& to)
{
dbgFile <<"Importing using %{APPNAMEUC}Import!";
if (to != "application/x-krita")
return KoFilter::BadMimeType;
KisDoc2 * doc = dynamic_cast<KisDoc2*>(m_chain->outputDocument());
if (!doc)
return KoFilter::CreationError;
QString filename = m_chain -> inputFile();
doc->prepareForImport();
if (!filename.isEmpty()) {
KUrl url;
url.setPath(filename);
if (url.isEmpty())
return KoFilter::FileNotFound;
%{APPNAME}Converter ib(doc, doc -> undoAdapter());
switch (ib.buildImage(url)) {
case KisImageBuilder_RESULT_UNSUPPORTED:
return KoFilter::NotImplemented;
break;
case KisImageBuilder_RESULT_INVALID_ARG:
return KoFilter::BadMimeType;
break;
case KisImageBuilder_RESULT_NO_URI:
case KisImageBuilder_RESULT_NOT_LOCAL:
return KoFilter::FileNotFound;
break;
case KisImageBuilder_RESULT_BAD_FETCH:
case KisImageBuilder_RESULT_EMPTY:
return KoFilter::ParsingError;
break;
case KisImageBuilder_RESULT_FAILURE:
return KoFilter::InternalError;
break;
case KisImageBuilder_RESULT_OK:
doc -> setCurrentImage( ib.image());
return KoFilter::OK;
default:
break;
}
}
return KoFilter::StorageCreationError;
}
#include <%{APPNAMELC}_import.moc>
| gpl-2.0 |
ec429/zak-lang | codegen.py | 21162 | #!/usr/bin/python
import sys, pprint, string
import ast_build as AST, tacifier, allocator
TAC = tacifier.TACifier
REG = allocator.Register
LIT = allocator.Literal
RTL = allocator.Allocator
Flag = allocator.Flag
class GenError(Exception): pass
class Generator(object):
def __init__(self, rtl, name, opts, w_opts):
self.rtl = rtl
self.name = name
self.text = []
self.data = []
self.bss = []
self.check_stack = opts.get('check-stack', False)
self.has_error = False
self.werror = w_opts.get('error', False)
self.wunused_but_set = w_opts.get('unused-but-set', True)
def staticname(self, name):
if isinstance(name, TAC.Gensym):
return '__gensym_%d'%(name.n,)
return name
def print_stats(self):
print "Lines: %d bss, %d data, %d text"%(len(self.bss), len(self.data), len(self.text))
def warn(self, *args):
if self.werror:
self.has_error = True
print >>sys.stderr, ' '.join(map(str, args))
def err(self, *args):
self.has_error = True
print >>sys.stderr, ' '.join(map(str, args))
## Generate Z80 assembly code from the stack & RTL
class FunctionGenerator(Generator):
def extend_stack_frame(self):
if self.rtl.sp > 128:
raise GenError("Stack too big (%d bytes, max 128)"%(self.rtl.sp,))
if self.check_stack:
# Check caller stack size
# TODO if we take a regparm in A, we need to PUSH AF and POP it later
self.text.append("\tLD A,(IY-1)")
self.text.append("\tCP %d"%(self.rtl.caller_stack_size,))
self.text.append("\tCALL NZ,panic")
if self.rtl.sp > self.rtl.caller_stack_size:
self.text.append("\tLD (IY-1),%d"%(self.rtl.sp,))
# TODO optional stack-frame zeroing (in case of uninitialised variables)?
elif self.rtl.sp < self.rtl.caller_stack_size: # what the heck?
raise GenError("Stack shrunk (not allowed)")
def generate_op(self, op):
if isinstance(op, RTL.RTLReturn):
self.text.append("\tRET")
elif isinstance(op, RTL.RTLFill):
assert isinstance(op.reg, REG), op
if self.rtl.is_on_stack(op.name):
offset, typ, size, filled, spilled = self.rtl.stack[op.name]
if offset is None: # We tried to fill a local that isn't memory-backed. That implies (a) it is never spilled, (b) it isn't a (stack) parameter; hence it's uninitialised
assert not spilled, self.rtl.stack[op.name]
raise GenError("Fill reg %s with non-backed %s '%s' (used uninitialised variable?)"%(op.reg, typ, op.name))
if size != op.reg.size:
raise GenError("Fill reg %s (%d) with %s (%d)"%(op.reg, op.reg.size, op.name, size))
if size == 1:
self.text.append("\tLD %s,(IY+%d)"%(op.reg, offset))
elif size == 2:
self.text.append("\tLD %s,(IY+%d)"%(op.reg.lo, offset))
self.text.append("\tLD %s,(IY+%d)"%(op.reg.hi, offset+1))
else: # can't happen
raise GenError(size)
elif isinstance(op.name, LIT):
# if it's a word register, it auto-promotes the literal
assert op.reg.size >= op.name.size
self.text.append("\tLD %s,%d"%(op.reg, op.name.value))
else:
if op.reg.name == 'A':
name = self.staticname(op.name)
self.text.append("\tLD A,(%s)"%(op.name,))
elif op.reg.name == 'HL':
name = self.staticname(op.name)
self.text.append("\tLD HL,(%s)"%(op.name,))
else:
raise GenError("Fill", op.reg, "with static", op.name)
elif isinstance(op, RTL.RTLSpill):
assert isinstance(op.reg, REG), op
if self.rtl.is_on_stack(op.name):
offset, typ, size, filled, spilled = self.rtl.stack[op.name]
if offset is None:
if filled: # can't happen
raise GenError("Spill reg %s to non-backed %s"%(op.reg, op.name))
# nothing to do, it's not backed
else:
if size != op.reg.size:
raise GenError("Spill reg %s (%d) to %s (%d)"%(op.reg, op.reg.size, op.name, size))
if size == 1:
self.text.append("\tLD (IY+%d),%s"%(offset, op.reg))
elif size == 2:
self.text.append("\tLD (IY+%d),%s"%(offset, op.reg.lo))
self.text.append("\tLD (IY+%d),%s"%(offset+1, op.reg.hi))
else: # can't happen
raise GenError(size)
else:
if op.reg.name == 'A':
raise NotImplementedError("Spill A to static %s"%(op.name,))
else:
self.text.append("\tPUSH AF")
self.text.append("\tLD A,%s"%(op.reg,))
self.text.append("\tLD (%s),A"%(op.name,))
self.text.append("\tPOP AF")
elif isinstance(op, RTL.RTLDeref):
assert isinstance(op.dst, REG), op
assert isinstance(op.src, REG), op
assert op.src.size == 2, op
if op.dst.size == 1:
self.text.append("\tLD %s,(%s)"%(op.dst, op.src))
elif op.dst.size == 2:
# the INC/DEC don't clobber flags, as they're 16-bit
self.text.append("\tLD %s,(%s)"%(op.dst.lo, op.src))
self.text.append("\tINC %s"%(op.src,))
self.text.append("\tLD %s,(%s)"%(op.dst.hi, op.src))
self.text.append("\tDEC %s"%(op.src,))
else:
raise NotImplementedError(op.dst.size)
elif isinstance(op, RTL.RTLWrite):
assert isinstance(op.dst, REG), op
assert isinstance(op.src, REG), op
assert op.dst.size == 2, op
if op.src.size == 1:
self.text.append("\tLD (%s),%s"%(op.dst, op.src))
else:
raise NotImplementedError(op.src.size)
elif isinstance(op, RTL.RTLIndirectRead):
assert isinstance(op.dst, REG), op
if isinstance(op.src, REG):
assert op.src.size == 2, op
if op.dst.size == 1:
self.text.append("\tLD %s,(%s%+d)"%(op.dst, op.src, op.offset))
elif op.dst.size == 2:
self.text.append("\tLD %s,(%s%+d)"%(op.dst.lo, op.src, op.offset))
self.text.append("\tLD %s,(%s%+d)"%(op.dst.hi, op.src, op.offset + 1))
else:
raise GenError(op.dst.size)
else:
# it's a name. Get its address from stack or static
if self.rtl.is_on_stack(op.src):
offset, typ, size, filled, spilled = self.rtl.stack[op.src]
if offset is None: # We tried to fill a local that isn't memory-backed
assert not spilled, self.rtl.stack[op.src]
raise GenError("Indirect read from non-backed %s '%s' (used uninitialised variable?)"%(typ, op.src))
if op.dst.size == 1:
self.text.append("\tLD %s,(IY%+d)"%(op.dst, offset + op.offset))
elif op.dst.size == 2:
self.text.append("\tLD %s,(IY%+d)"%(op.dst.lo, offset + op.offset))
self.text.append("\tLD %s,(IY%+d)"%(op.dst.hi, offset + op.offset + 1))
else:
raise GenError(op.dst.size)
else:
raise GenError(op.src)
elif isinstance(op, RTL.RTLIndirectWrite):
if isinstance(op.dst, REG):
assert op.dst.size == 2, op
if isinstance(op.src, REG):
if op.src.size == 1:
self.text.append("\tLD (%s%+d),%s"%(op.dst, op.offset, op.src))
elif op.src.size == 2:
self.text.append("\tLD (%s%+d),%s"%(op.dst, op.offset, op.src.lo))
self.text.append("\tLD (%s%+d),%s"%(op.dst, op.offset + 1, op.src.hi))
else:
raise GenError(op.src.size)
elif isinstance(op.src, LIT):
self.text.append("\tLD (%s%+d),%d"%(op.dst, op.offset, op.src.value))
else:
raise GenError(op)
else:
# name
if self.rtl.is_on_stack(op.dst):
offset, typ, size, filled, spilled = self.rtl.stack[op.dst]
if offset is None: # this probably shouldn't happen
assert not filled, self.rtl.stack[op.dst]
raise GenError("Indirect write to non-backed %s '%s'"%(typ, op.dst))
if op.src.size == 1:
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset, op.src))
elif op.src.size == 2:
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset, op.src.lo))
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset + 1, op.src.hi))
else:
raise GenError(op.dst.size)
else:
raise GenError(op.src)
elif isinstance(op, RTL.RTLIndirectInit):
if self.rtl.is_on_stack(op.dst):
offset, typ, size, filled, spilled = self.rtl.stack[op.dst]
if offset is None: # it's never filled, so it's never used
assert not filled, self.rtl.stack[op.dst]
if self.wunused_but_set:
self.warn("Init to non-backed", op.dst, "- unused but set variable?")
# skip the initialisation, then, we don't need it
elif op.src.size == 1:
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset, op.src))
elif op.src.size == 2:
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset, op.src.lo))
self.text.append("\tLD (IY%+d),%s"%(offset + op.offset + 1, op.src.hi))
else:
raise GenError(op.src.size)
else:
raise NotImplementedError(op)
elif isinstance(op, RTL.RTLMove):
assert isinstance(op.dst, REG), op
if isinstance(op.src, REG):
assert op.dst.size >= op.src.size, op
if op.dst.size == 1:
self.text.append("\tLD %s,%s"%(op.dst, op.src))
elif op.dst.size == 2:
if op.src.size == 1:
self.text.append("\tLD %s,0"%(op.dst.hi,))
self.text.append("\tLD %s,%s"%(op.dst.lo, op.src))
elif op.dst.name in ['HL', 'IX', 'IY'] and\
op.src.name in ['HL', 'IX', 'IY']:
self.text.append("\tPUSH %s"%(op.src,))
self.text.append("\tPOP %s"%(op.dst,))
else:
self.text.append("\tLD %s,%s"%(op.dst.hi, op.src.hi))
self.text.append("\tLD %s,%s"%(op.dst.lo, op.src.lo))
else:
raise GenError(op.dst.size)
elif isinstance(op.src, (TAC.Gensym, str)):
# we assume it's a global symbol, and thus its name exists
self.text.append("\tLD %s,%s"%(op.dst, self.staticname(op.src)))
elif isinstance(op.src, LIT):
assert op.dst.size <= op.src.size, op
self.text.append("\tLD %s,%d"%(op.dst, op.src.value))
else:
raise NotImplementedError(op.src)
elif isinstance(op, RTL.RTLExchange):
assert isinstance(op.dst, REG), op
assert isinstance(op.src, REG), op
self.text.append("\tEX %s,%s"%(op.dst, op.src))
elif isinstance(op, RTL.RTLAdd):
assert isinstance(op.dst, REG), op
if isinstance(op.src, REG):
if op.dst.name == 'A': # 8-bit add
if op.src.size != 1: # should never happen
raise GenError("Add A with %s (%d)"%(op.src, op.src.size))
self.text.append("\tADD %s,%s"%(op.dst,op.src))
elif op.dst.name in ['HL', 'IX', 'IY']: # 16-bit add
if op.src.size != 2: # should never happen
raise GenError("Add %s with %s (%d)"%(op.dst, op.src, op.src.size))
self.text.append("\tADD %s,%s"%(op.dst, op.src))
else:
raise NotImplementedError(op)
elif isinstance(op.src, LIT):
assert op.dst.size == op.src.size, op
if op.src.value == 1:
self.text.append("\tINC %s"%(op.dst,))
else:
raise NotImplementedError(op)
else:
raise NotImplementedError(op)
elif isinstance(op, RTL.RTLCp):
assert isinstance(op.dst, REG), op
if op.dst.name == 'A': # 8-bit compare
if op.src.size != 1: # should never happen
raise GenError("Cp A with %s (%d)"%(op.src, op.src.size))
assert isinstance(op.src, (REG,LIT)), op
self.text.append("\tCP %s"%(op.src,))
else:
raise NotImplementedError(op)
elif isinstance(op, RTL.RTLAnd):
assert isinstance(op.dst, REG), op
if isinstance(op.src, REG):
if op.dst.name == 'A': # 8-bit and
if op.src.size != 1: # should never happen
raise GenError("And A with %s (%d)"%(op.src, op.src.size))
self.text.append("\tAND %s"%(op.src,))
else:
raise NotImplementedError(op)
elif isinstance(op, RTL.RTLPush):
assert isinstance(op.src, REG), op
self.text.append("\tPUSH %s"%(op.src,))
elif isinstance(op, RTL.RTLPop):
assert isinstance(op.dst, REG), op
self.text.append("\tPOP %s"%(op.dst,))
elif isinstance(op, RTL.RTLLabel):
assert isinstance(op.name, str), op
self.text.append("%s:"%(op.name,))
elif isinstance(op, RTL.RTLCall):
assert isinstance(op.addr, str), op
self.text.append("\tCALL %s"%(op.addr,))
elif isinstance(op, RTL.RTLJump): # TODO notice when we need to use long JP (but how?)
assert isinstance(op.label, str), op
self.text.append("\tJR %s"%(op.label))
elif isinstance(op, RTL.RTLCJump): # TODO notice when we need to use long JP (but how?)
assert isinstance(op.label, str), op
assert isinstance(op.flag, Flag)
self.text.append("\tJR %s,%s"%(op.flag.gen, op.label))
else:
raise NotImplementedError(op)
def generate(self):
for name, (size, typ) in self.rtl.static.items():
if name in self.rtl.tac.strings:
self.data.append("%s: .asciz \"%s\""%(self.staticname(name), self.escape_string(self.rtl.tac.strings[name])))
else:
self.err(self.rtl.tac.strings)
raise NotImplementedError(name, size, typ)
self.text.append("")
if self.rtl.sc.auto:
self.text.append(".globl %s ; %s"%(self.name, self.rtl.decl))
elif self.rtl.sc.static:
self.text.append("; (static) %s"%(self.rtl.decl,))
else:
raise GenError("Unexplained storage class", self.rtl.sc)
self.text.append("; Stack:")
stack = dict((offset, name) for (name,(offset, typ, size, filled, spilled)) in self.rtl.stack.items())
for offset, name in stack.items():
if offset is not None:
self.text.append("; %d: %s"%(offset, name))
self.text.append("%s:"%(self.name,))
self.extend_stack_frame()
for op in self.rtl.code:
try:
self.generate_op(op)
except Exception as e:
self.err("In func:", self.name, "as", self.rtl.decl)
self.err("In op:", op)
raise
def escape_string(self, s):
out = []
for c in s:
if c == '"':
out.append('\\"')
elif c in string.printable:
out.append(c)
else:
out.append('\\%03o'%(ord(c),))
return ''.join(out)
## Generate assembler directives for the global variables
class GlobalGenerator(Generator):
def generate(self):
things = {}
for name, (_, typ, size, filled, spilled) in self.rtl.stack.items():
if not filled and spilled: # can't happen
raise GenError("Global is not memory-backed", name)
if name not in self.rtl.inits: # can't happen
raise GenError("Undeclared global", name)
things[name] = (size, typ)
things.update(self.rtl.static)
for name, (size, typ) in things.items():
init = self.rtl.inits[name]
name = self.staticname(name)
if init is None:
self.bss.append(".globl %s ; %s"%(name,typ))
self.bss.append("%s: .skip %d"%(name, size))
else:
self.data.append(".globl %s ; %s"%(name,typ))
self.data.append("%s:"%(name,))
if isinstance(init, LIT):
if not typ.compat(init.typ):
raise GenError("Literal", init, "doesn't match type", typ, "of", name)
if size == 1:
self.data.append("\t.byte %d"%(init.value,))
elif size == 2:
self.data.append("\t.word %d"%(init.value,))
else:
raise GenError("Bad size", size, "for name", name, "with literal initialiser", init)
elif isinstance(init, TAC.TACAddress):
self.data.append("\t.word %s"%(self.staticname(init.src),))
elif isinstance(init, str):
# Don't trust .asciz, it can't cope with special chars like \n
self.data.append("\t; %r"%(init,))
self.data.append('\t.byte %s'%(', '.join(('%d'%(ord(ch),) for ch in init))))
self.data.append('\t.byte 0')
else:
raise NotImplementedError(init)
## Entry point
def generate(allocations, gen_opts, w_opts):
generated = {}
for name, rtl in allocations.items():
if name is None:
gen = GlobalGenerator(rtl, name, gen_opts, w_opts)
gen.generate()
generated[name] = gen
else:
gen = FunctionGenerator(rtl, name, gen_opts, w_opts)
gen.generate()
generated[name] = gen
if gen.has_error:
raise GenError("Error emitted while processing %s (see above)" % (name or 'globals',))
return generated
def combine(generated):
bss = []
data = []
text = []
for gen in generated.values():
bss.extend(gen.bss)
data.extend(gen.data)
text.extend(gen.text)
return bss, data, text
## Test code
if __name__ == "__main__":
import parser
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f:
source = f.read()
else:
source = sys.stdin.read()
parse_tree = parser.parse(source)
ast = AST.AST_builder(parse_tree)
tac = tacifier.tacify(ast)
assert tac.in_func is None, tac.in_func
assert len(tac.scopes) == 1
allocations = allocator.alloc(tac, {}, debug=True)
print
generated = {}
for name, rtl in allocations.items():
if name is None:
print "Generating global variables"
gen = GlobalGenerator(rtl, name, {}, {})
gen.generate()
gen.print_stats()
generated[name] = gen
else:
print "Generating code for", name
gen = FunctionGenerator(rtl, name, {}, {})
gen.generate()
gen.print_stats()
generated[name] = gen
bss = []
data = []
text = []
for gen in generated.values():
bss.extend(gen.bss)
data.extend(gen.data)
text.extend(gen.text)
print "==ASSEMBLY OUTPUT BEGINS HERE=="
if bss:
print
print ".bss"
for line in bss:
print line
if data:
print
print ".data"
for line in data:
print line
if text:
print
print ".text"
for line in text:
print line
| gpl-2.0 |
tommythorn/yari | shared/cacao-related/phoneme_feature/cldc/src/vm/share/runtime/WTKProfiler.hpp | 2725 | /*
*
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
#if ENABLE_WTK_PROFILER
/** \class WTKProfiler
This profiler collects exact execution time information.
*/
class WTKProfiler : public AllStatic {
private:
static jlong _totalCycles;
static jlong _vmStartTime;
static jint _dumpedProfiles;
public:
// Not good to be public, but should be visible to optimize a little
static jlong _lastCycles;
// Initialize resources needed by the profiler
static void initialize();
// Activate the profiler
static void engage();
// Deactivate the profiler -- it may be activated again
static void disengage();
// Free all resources needed by the profiler
// (in MVM case, only ones specific for id)
static void dispose(int id);
// Called when current metod changes
// information about current method can be read from thread stack
static void record_method_transition(Thread*);
// Called when current thread changes
static void record_thread_transition();
// Called when exception is being thrown
static void record_exception(Thread*, Frame* new_current_frame);
// Prints the collected profiling information
static void print(Stream* out, int id);
// suspend/resume profiler while waiting for external events
static void suspend();
static void resume();
/// allocate thread-specific profiler data
static ReturnOop allocate_thread_data(JVM_SINGLE_ARG_TRAPS);
// saves profiler data on disk and returns unique integer
// for stored profile, also removes profiler's internal
// structure related to particulatar task_id (in MVM case)
// in SVM case the only reasonable value for task_id is -1
static int dump_and_clear_profile_data(int task_id);
};
#endif
| gpl-2.0 |
dolphin19303/PhotoBox | DPPhotoSDK/src/winterwell/jtwitter/InternalUtils.java | 18307 | package winterwell.jtwitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import winterwell.jgeoplanet.GeoCodeQuery;
import winterwell.jgeoplanet.IGeoCode;
import winterwell.jgeoplanet.IPlace;
import winterwell.jgeoplanet.Location;
import winterwell.json.JSONException;
import winterwell.json.JSONObject;
import winterwell.jtwitter.Twitter.ITweet;
/**
* Utility methods used in Twitter. This class is public in case anyone else
* wants to use these methods. WARNING: they don't really form part of the
* JTwitter API, and may be changed or reorganised in future versions.
* <p>
* NB: Some of these are copies (sometimes simplified) of methods in
* winterwell.utils.Utils
*
* @author daniel
* @testedby {@link InternalUtilsTest}
*/
public class InternalUtils {
/**
* Utility method for {@link IGeoCode}rs
* @param query
* @param places Can be null.
* @return places which match the query requirements. Can be empty, never null.
*/
public static Map<IPlace,Double> filterByReq(GeoCodeQuery query, Map<IPlace,Double> places) {
if (places==null) return Collections.EMPTY_MAP;
if ( ! (query.reqGeometry || query.reqLocn)) { // TODO || query.reqOnlyCity)) { // NB: Every place should have a country
return places;
}
Map<IPlace,Double> out = new HashMap(places.size());
for(IPlace p : places.keySet()) {
if (query.reqGeometry && p.getBoundingBox()==null) continue;
if (query.reqLocn && p.getCentroid()==null) continue;
// TODO if (query.reqOnlyCity && p.getBoundingBox()==null) continue;
out.put(p, places.get(p));
}
return out;
}
/**
* Utility method for {@link IGeoCode}rs
* @param query
* @param places
* @param prefType e.g. city
* @param baseConfidence
* @return
*/
public static Map<IPlace,Double> prefer(GeoCodeQuery query, List<? extends IPlace> places, String prefType, double baseConfidence)
{
assert places.size() != 0;
assert baseConfidence >= 0 && baseConfidence <= 1;
// prefer cities (or whatever)
List<IPlace> cities = new ArrayList();
for (IPlace place : places) {
if (prefType.equals(place.getType())) {
cities.add(place);
}
}
HashMap map = new HashMap();
List select = cities.size()!=0? cities : places;
double c = baseConfidence / places.size();
for (Object place : select) {
map.put(place, c);
}
Map<IPlace, Double> map2 = filterByReq(query, map);
return map2;
}
/**
* @param text
* @return text with any urls (using Twitter's Regex.VALID_URL) replaced with ""
*/
public static String stripUrls(String text) {
return Regex.VALID_URL.matcher(text).replaceAll("");
}
public static final Pattern TAG_REGEX = Pattern.compile("<!?/?[\\[\\-a-zA-Z][^>]*>", Pattern.DOTALL);
static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
/**
* The date format used by Marko from Marakana. This is needed for *some*
* installs of Status.Net, though not for Identi.ca.
*/
static final DateFormat dfMarko = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss ZZZZZ yyyy");
/**
* Matches latitude, longitude, including with the UberTwitter UT: prefix
* Group 2 = latitude, Group 3 = longitude.
* <p>
* Weird: I saw this as an address - "ÜT: 25.324488,55.376224t" Is it just a
* one-off typo? Should we match N/S/E/W markers?
*/
// ?? unify this with Location#parse()?
public static final Pattern latLongLocn = Pattern
.compile("(\\S+:)?\\s*(-?[\\d\\.]+)\\s*,\\s*(-?[\\d\\.]+)");
static final Comparator<Status> NEWEST_FIRST = new Comparator<Status>() {
@Override
public int compare(Status o1, Status o2) {
return -o1.id.compareTo(o2.id);
}
};
public static final Pattern REGEX_JUST_DIGITS = Pattern.compile("\\d+");
/**
* Group 1 = the recipient
*/
// TODO test -- is the \\s? at the end of this regex right??
public static final Pattern DM = Pattern.compile("^dm? (\\w+)\\s?", Pattern.CASE_INSENSITIVE);
static ConcurrentHashMap<String, Long> usage;
/**
* Create a map from a list of key, value pairs. An easy way to make small
* maps, basically the equivalent of {@link Arrays#asList(Object...)}. If
* the value is null, the key will not be included.
*/
@SuppressWarnings("unchecked")
public static Map asMap(Object... keyValuePairs) {
assert keyValuePairs.length % 2 == 0;
Map m = new HashMap(keyValuePairs.length / 2);
for (int i = 0; i < keyValuePairs.length; i += 2) {
Object v = keyValuePairs[i + 1];
if (v == null) {
continue;
}
m.put(keyValuePairs[i], v);
}
return m;
}
public static void close(OutputStream output) {
if (output == null)
return;
// Flush (annoying that this is not part of Closeable)
try {
output.flush();
} catch (Exception e) {
// Ignore
} finally {
// Close
try {
output.close();
} catch (IOException e) {
// Ignore
}
}
}
public static void close(InputStream input) {
if (input == null)
return;
// Close
try {
input.close();
} catch (IOException e) {
// Ignore
}
}
/**
* Count API usage for api usage stats.
*
* @param url
*/
static void count(String url) {
if (usage == null)
return;
// ignore parameters
int i = url.indexOf("?");
if (i != -1) {
url = url.substring(0, i);
}
// for clarity
i = url.indexOf("/1/");
if (i != -1) {
url = url.substring(i + 3);
}
// some calls - eg statuses/show - include the tweet id
url = url.replaceAll("\\d+", "");
// non-blocking (we could just ignore the race condition I suppose)
for (int j = 0; j < 100; j++) { // give up if you lose >100 races
Long v = usage.get(url);
boolean done;
if (v == null) {
Long old = usage.putIfAbsent(url, 1L);
done = old == null;
} else {
long nv = v + 1;
done = usage.replace(url, v, nv);
}
if (done) {
break;
}
}
}
static String encode(Object x) {
String encd;
try {
encd = URLEncoder.encode(String.valueOf(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
// This shouldn't happen as UTF-8 is standard
encd = URLEncoder.encode(String.valueOf(x));
}
// v1.1 doesn't like *
encd = encd.replace("*", "%2A");
return encd.replace("+", "%20");
}
/**
* @return a map of API endpoint to count-of-calls. null if switched off
* (which is the default).
*
* @see #setTrackAPIUsage(boolean)
*/
static public ConcurrentHashMap<String, Long> getAPIUsageStats() {
return usage;
}
/**
* Convenience method for making Dates. Because Date is a tricksy bugger of
* a class.
*
* @param year
* @param month
* @param day
* @return date object
*/
public static Date getDate(int year, String month, int day) {
try {
Field field = GregorianCalendar.class.getField(month.toUpperCase());
int m = field.getInt(null);
Calendar date = new GregorianCalendar(year, m, day);
return date.getTime();
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage());
}
}
/**
* A very tolerant boolean reader
* @param obj
* @param key
* @return
* @throws JSONException
*/
static Boolean getOptBoolean(JSONObject obj, String key)
throws JSONException {
Object o = obj.opt(key);
if (o == null || o.equals(JSONObject.NULL))
return null;
if (o instanceof Boolean) {
return (Boolean) o;
}
if (o instanceof String) {
String os = (String) o;
if (os.equalsIgnoreCase("true")) return true;
if (os.equalsIgnoreCase("false")) return false;
}
// Wordpress returns some random shite :(
if (o instanceof Integer) {
int oi = (Integer)o;
if (oi==1) return true;
if (oi==0 || oi==-1) return false;
}
System.err.println("JSON parse fail: "+o + " (" + key + ") is not boolean");
return null;
}
/**
* Join a slice of the list
*
* @param screenNamesOrIds
* @param first
* Inclusive
* @param last
* Exclusive. Can be > list.size (will be truncated).
* @return
*/
static String join(List screenNamesOrIds, int first, int last) {
StringBuilder names = new StringBuilder();
for (int si = first, n = Math.min(last, screenNamesOrIds.size()); si < n; si++) {
names.append(screenNamesOrIds.get(si));
names.append(",");
}
// pop the final ","
if (names.length() != 0) {
names.delete(names.length() - 1, names.length());
}
return names.toString();
}
/**
* Join the list
*
* @param screenNames
* @return
*/
public static String join(String[] screenNames) {
StringBuilder names = new StringBuilder();
for (int si = 0, n = screenNames.length; si < n; si++) {
names.append(screenNames[si]);
names.append(",");
}
// pop the final ","
if (names.length() != 0) {
names.delete(names.length() - 1, names.length());
}
return names.toString();
}
/**
* Helper method to deal with JSON-in-Java weirdness
*
* @return Can be null
* */
protected static String jsonGet(String key, JSONObject jsonObj) {
assert key != null : jsonObj;
assert jsonObj != null;
Object val = jsonObj.opt(key);
if (val == null)
return null;
if (JSONObject.NULL.equals(val))
return null;
String s = val.toString();
return s;
}
static Date parseDate(String c) {
if (InternalUtils.REGEX_JUST_DIGITS.matcher(c).matches())
return new Date(Long.valueOf(c));
try {
Date _createdAt = new Date(c);
return _createdAt;
} catch (Exception e) { // Bug reported by Marakana with *some*
// Status.Net sites
try {
Date _createdAt = InternalUtils.dfMarko.parse(c);
return _createdAt;
} catch (ParseException e1) {
throw new TwitterException.Parsing(c, e1);
}
}
}
/**
* Note: this is a global JVM wide setting, intended for debugging.
* @param on
* true to activate {@link #getAPIUsageStats()}. false to switch
* stats off. false by default
*/
static public void setTrackAPIUsage(boolean on) {
if (!on) {
usage = null;
return;
}
if (usage != null)
return;
usage = new ConcurrentHashMap<String, Long>();
}
/**
* We assume that UTF8 is supported everywhere!
*/
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Use a buffered reader (preferably UTF-8) to extract the contents of the
* given stream. Then close it.
*/
protected static String read(InputStream inputStream) {
try {
Reader reader = new InputStreamReader(inputStream, UTF_8);
reader = new BufferedReader(reader);
StringBuilder output = new StringBuilder();
while (true) {
int c = reader.read();
if (c == -1) {
break;
}
output.append((char) c);
}
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
close(inputStream);
}
}
/**
* Twitter html encodes some entities: ", ', <, >, &
*
* @param text
* Can be null (which returns null)
* @return normal-ish text
*/
static String unencode(String text) {
if (text == null)
return null;
// TODO use Jakarta to handle all html entities?
text = text.replace(""", "\"");
text = text.replace("'", "'");
text = text.replace(" ", " ");
text = text.replace("&", "&");
text = text.replace(">", ">");
text = text.replace("<", "<");
// zero-byte chars are a rare but annoying occurrence
if (text.indexOf(0) != -1) {
text = text.replace((char) 0, ' ').trim();
}
// if (Pattern.compile("&\\w+;").matcher(text).find()) {
// System.out.print(text);
// }
return text;
}
/**
* Convert to a URI, or return null if this is badly formatted
*/
static URI URI(String uri) {
try {
return new URI(uri);
} catch (URISyntaxException e) {
return null; // Bad syntax
}
}
static User user(String json) {
try {
JSONObject obj = new JSONObject(json);
User u = new User(obj, null);
return u;
} catch (JSONException e) {
throw new TwitterException(e);
}
}
/**
* Remove xml and html tags, e.g. to safeguard against javascript
* injection attacks, or to get plain text for NLP.
* @param xml can be null, in which case null will be returned
* @return the text contents - ie input with all tags removed
*/
public static String stripTags(String xml) {
if (xml==null) return null;
// short cut if there are no tags
if (xml.indexOf('<')==-1) return xml;
// first all the scripts (cos we must remove the tag contents too)
Matcher m4 = pScriptOrStyle.matcher(xml);
xml = m4.replaceAll("");
// comments
Matcher m2 = pComment.matcher(xml);
String txt = m2.replaceAll("");
// now the tags
Matcher m = TAG_REGEX.matcher(txt);
String txt2 = m.replaceAll("");
Matcher m3 = pDocType.matcher(txt2);
String txt3 = m3.replaceAll("");
return txt3;
}
/**
* Matches an xml comment - including some bad versions
*/
public static final Pattern pComment = Pattern.compile("<!-*.*?-+>", Pattern.DOTALL);
/**
* Used in strip tags to get rid of scripts and css style blocks altogether.
*/
public static final Pattern pScriptOrStyle = Pattern.compile("<(script|style)[^<>]*>.+?</(script|style)>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/**
* Matches a doctype element.
*/
public static final Pattern pDocType = Pattern.compile("<!DOCTYPE.*?>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
public static void sleep(long msecs) {
try {
Thread.sleep(msecs);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Several methods require authorisation in API v1.1, but not in v1.0
* @param jtwit
* @return true if jtwit can authorise, or if the API v is 1.1
*/
static boolean authoriseIn11(Twitter jtwit) {
return jtwit.getHttpClient().canAuthenticate()
|| jtwit.TWITTER_URL.endsWith("1.1");
}
/**
*
* @param maxId
* @param stati
* @return mimimum - 1
*/
public static BigInteger getMinId(BigInteger maxId, List<? extends ITweet> stati) {
BigInteger min = maxId;
for (ITweet s : stati) {
if (min==null || min.compareTo(s.getId()) > 0) {
min = s.getId();
}
}
// Next page must start strictly before this one
if (min!=null) min = min.subtract(BigInteger.ONE);
return min;
}
/**
* Best of them, or null if places is empty
* @param places
* @return
*/
public static <X> X getBest(Map<X, Double> places) {
double high = Double.NEGATIVE_INFINITY;
X best = null;
for(Map.Entry<X,Double> e : places.entrySet()) {
if (e.getValue() > high) {
best = e.getKey();
}
}
return best;
}
/**
* Does place match the query?
* @param query
* @param place
* @return true/false/null. Often null for unsure!
*/
public static Boolean geoMatch(GeoCodeQuery query, IPlace place) {
if (place==null) return null;
boolean unsure = false;
// Country
if (query.country!=null) {
String cc = place.getCountryCode();
if (cc==null) {
// TODO get country for place
unsure=true;
} else if ( ! query.country.equals(cc)) {
return false;
}
}
// city
if (query.city!=null) {
// TODO
}
// Bounding box
if (query.bbox != null) {
Location locn = place.getCentroid();
if (locn!=null && ! query.bbox.contains(locn)) {
return false;
}
// Hm: no long/lat for place -- what shall we say??
// Let's be lenient
unsure = true;
}
// requirements
Map<IPlace, Double> filtered = filterByReq(query, Collections.singletonMap(place, 1.0));
if (filtered.isEmpty()) return false;
// Does it contain the query string?
if (unsure) {
if (query.desc!=null && ! query.desc.isEmpty() && place.getName() != null && ! place.getName().isEmpty()) {
String qdesc = InternalUtils.toCanonical(query.desc);
String qname = InternalUtils.toCanonical(place.getName());
Pattern namep = Pattern.compile("\\b"+Pattern.quote(qname)+"\\b");
if (namep.matcher(qdesc).find()) {
// Fairly strong benefit of the doubt here
return true;
}
}
}
return unsure? null : true;
}
private static String toCanonical(String string) {
if (string == null)
return "";
StringBuilder sb = new StringBuilder();
boolean spaced = false;
for (int i = 0, n = string.length(); i < n; i++) {
char c = string.charAt(i);
// lowercase letters
if (Character.isLetterOrDigit(c)) {
spaced = false;
// Note: javadoc recommends String.toLowerCase() as being better
// -- I wonder if it actually is, or if this is aspirational
// internationalisation?
c = Character.toLowerCase(c);
sb.append(c);
continue;
}
// all else as spaces
// compact whitespace
// if (Character.isWhitespace(c)) {
if (spaced || sb.length() == 0) {
continue;
}
sb.append(' ');
spaced = true;
// }
// ignore punctuation!
}
string = sb.toString().trim();
// NB: StrUtils would ditch the accents, if we can
return string;
}
private static Method logFn;
private static boolean logInit;
/**
* Use the Winterwell logger. Reflection-based to avoid a dependency.
* @param tag
* @param msg
*/
public static void log(String tag, String msg) {
logInit();
if (logFn!=null) {
try {
logFn.invoke(null, tag, msg);
} catch (Exception ex) {
// oh well
}
}
}
private static void logInit() {
if (logInit) return;
try {
Class<?> Log = Class.forName("winterwell.utils.reporting.Log");
logFn = Log.getMethod("w", String.class, Object.class);
} catch(Throwable ex) {
// ignore
} finally {
logInit = true;
}
}
}
| gpl-2.0 |
EnigmaTeam/EnigmaBot | plugins/anime.lua | 359 | function run(msg, matches)
local url = http.request('https://konachan.com/post.json?limit=300')
local js = json:decode(url)
local random = math.random (100)
local sticker = js[random].jpeg_url
local file = download_to_file(sticker,'sticker.png')
send_photo(get_receiver(msg), file, ok_cb, false)
end
return {
patterns = {
"^[!#/]([Aa]nimeee)$"
},
run = run
} | gpl-2.0 |
thiagoamm-agr/sods | admin/tipos_solicitacao/index.php | 26466 | <?php
// Cadastro de Tipos de Solicitação.
// Model
@include $_SERVER['DOCUMENT_ROOT'] . '/sods/app/models/TipoSolicitacao.php';
// Controller
@include $_SERVER['DOCUMENT_ROOT'] . '/sods/app/controllers/TiposSolicitacoesController.php';
$controller = new TiposSolicitacoesController();
// Identificação e atendimento das ações do usuário pelo controller.
if (isset($_POST['action'])) {
// Recuperando os parâmetros da requisição.
$action = $_POST['action'];
if (isset($_POST['json'])) {
$json = $_POST['json'];
if (!empty($json)) {
$tipoSolicitacao = new TipoSolicitacao();
$tipoSolicitacao->loadJSON($json);
}
}
// Identificando a ação desempenhada pelo usuário.
switch ($action) {
case 'add':
$fail = $controller->add($tipoSolicitacao);
if($fail){
echo 'NOUPDATE';
}
exit();
break;
case 'edit':
$fail = $controller->edit($tipoSolicitacao);
if($fail){
echo 'NOUPDATE';
}
exit();
break;
case 'delete':
$fail = $controller->delete($tipoSolicitacao);
if ($fail) {
echo 'ERRO';
}
exit();
break;
case 'list':
$filter = isset($_POST['filter']) ? $_POST['filter'] : '';
$value = isset($_POST['value']) ? $_POST['value'] : '';
$page = isset($_POST['p']) ? $_POST['p'] : 1;
echo $controller->getGrid($page, $filter, $value);
exit();
break;
}
}
?>
<?php
// Topo
@include $_SERVER['DOCUMENT_ROOT'] . '/sods/includes/topo.php';
?>
<!-- Javascript -->
<script type="text/javascript" src="/sods/static/js/models/TipoSolicitacao.js"></script>
<script type="text/javascript" src="/sods/static/js/validators/TipoSolicitacaoFormValidator.js"></script>
<script type="text/javascript" src="/sods/static/js/validators/PesquisaFormValidator.js"></script>
<script type="text/javascript">
var tipoSolicitacao = null;
var action = null;
var form = null;
var formValidator = null;
var resposta = null;
var page = 1;
var current_page = null;
var filter = null;
var value = null;
function add() {
action = "add";
tipoSolicitacao = new TipoSolicitacao();
tipoSolicitacao.id = null;
form = $('#form-add');
formValidator = new TipoSolicitacaoFormValidator(form);
current_page = 1;
filter = null;
value = null;
}
function edit(tipoSolicitacao_json, page) {
try {
if (tipoSolicitacao_json != null) {
action = 'edit';
form = $('#form-edit');
tipoSolicitacao = new TipoSolicitacao();
formValidator = new TipoSolicitacaoFormValidator(form);
tipoSolicitacao.id = tipoSolicitacao_json.id;
$('#nome', form).val(tipoSolicitacao_json.nome);
if (tipoSolicitacao_json.status == 'A') {
$('#status', form).prop('checked', true);
$('#status', form).val('A');
} else {
$('#status', form).prop('checked', false);
$('#status', form).val('I');
}
current_page = page;
} else {
throw 'Não é possível editar um tipo de lotação inexistente!';
}
} catch(e) {
alert(e);
}
}
function del(tipoSolicitacao_json, page, total_records) {
try {
if (tipoSolicitacao_json != null) {
action = 'delete';
tipoSolicitacao = new TipoSolicitacao();
tipoSolicitacao.id = tipoSolicitacao_json.id;
tipoSolicitacao.nome = tipoSolicitacao_json.nome;
tipoSolicitacao.status = tipoSolicitacao_json.status;
form = $('#form-del');
formValidator = new TipoSolicitacaoFormValidator(form);
total_records = total_records - 1;
if (total_records == 0) {
filter = null;
value = null;
current_page = 1;
}
var manipulated_page = Math.ceil(total_records / 10);
if (manipulated_page < page) {
current_page = manipulated_page;
} else {
current_page = page;
}
}
} catch(e) {
alert(e);
}
}
function createAJAXPagination() {
$('.pagination-css').on({
click: function(e) {
var page = $(this).attr('id');
page = page.replace('pg_', '');
page = page.replace('pn_', '');
page = page.replace('pl_', '');
page = page.replace('pp_', '');
page = page.replace('p_', '');
list(page);
e.preventDefault();
return false;
}
});
}
function list(page) {
if ($(form).attr('id') == 'form-search') {
formValidator.validate();
}
$.ajax({
type: 'post',
url: '/sods/admin/tipos_solicitacao/',
dataType: 'text',
cache: false,
timeout: 70000,
async: true,
data: {
'action': 'list',
'p': page,
'filter': filter,
'value': value
},
success: function(data, status, xhr) {
if (data == 'ERRO') {
$('#modal-danger').modal('show');
window.setTimeout(function() {
$('#modal-danger').modal('hide');
}, 3000);
} else {
// Carrega o HTML da Grid.
$('#grid').html(data);
// Paginação AJAX na Grid.
createAJAXPagination();
// Ordenação dos resultados da Grid.
$("table thead .nonSortable").data("sorter", false);
$("#tablesorter").tablesorter({
emptyTo: 'none',
theme : 'default',
headerTemplate : '{content}{icon}',
widgetOptions : {
columns : [ "primary", "secondary", "tertiary" ]
}
});
// Tooltip.
$('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
createAJAXPagination();
}
// Mostra a saída no console do Firebug.
console.log(data);
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function(xhr, status) {
console.log('A requisição foi completada.');
if ($(form).attr('id') == 'form-search') {
clean();
}
}
});
}
function save() {
// Verifica se o objeto a ser manipulado existe.
if (tipoSolicitacao != null) {
var json = null;
switch (action) {
case 'add':
case 'edit':
// Obtém os dados do formulário.
tipoSolicitacao.nome = $('#nome', form).val();
tipoSolicitacao.status = $('#status', form).val();
// Serializa o objeto no formato JSON.
json = tipoSolicitacao.toJSON();
break;
case 'delete':
json = tipoSolicitacao.toJSON();
break;
}
// Instancia um validador de formulário.
formValidator = new TipoSolicitacaoFormValidator(form);
// Valida o formulário.
//validation=formValidator.validate();
if (formValidator.validate()) {
// Efetua uma requisição AJAX para essa página.
$.ajax({
type: 'post',
url: '/sods/admin/tipos_solicitacao/',
dataType: 'text',
cache: false,
timeout: 70000,
async: true,
data: {
'action': action,
'json': json
},
success: function(data, status, xhr) {
modal='';
if (data == 'ERRO') {
modal='#modal-danger';
$('#alert-msg').text('Não é possivel excluir um tipo de solicitação referenciado');
$(modal).modal('show');
}
else if (data == 'NOUPDATE'){
modal='#modal-danger';
$('#alert-msg').text('Não é possivel inserir ou editar um tipo de solicitação repetido.');
$(modal).modal('show');
}
else {
modal='#modal-success';
$(modal).modal('show');
list(current_page);
}
window.setTimeout(function() {
$(modal).modal('hide');
}, 4000);
console.log(data);
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function(xhr, status) {
clean();
}
});
}
}
return false;
}
function search() {
form = $('#form-search');
formValidator = new PesquisaFormValidator(form);
}
function clean() {
if (formValidator != null) {
formValidator.reset();
}
}
/* Definindo a manipulação de alguns eventos após o
* carregamento da página.
*/
$(document).ready(function() {
$('#form-add').submit(function(event) {
event.preventDefault();
save();
});
$('#form-edit').submit(function(event) {
event.preventDefault();
save();
});
$('#form-del').submit(function(event) {
event.preventDefault();
save();
});
$('#form-search').submit(function(event) {
event.preventDefault();
filter = $('#filtro', this).val();
value = $('#valor', this).val();
page = 1;
list(page);
});
$('#status', '#form-edit').click(function(event) {
if ($(this).prop('checked')) {
$(this).val('A');
} else {
$(this).val('I');
}
});
createAJAXPagination();
});
</script>
<!-- Container -->
<div class="container">
<h2>Tipos de Solicitação</h2>
<div class="row">
<div class="col-md-12">
<div class="col-md-11">
<button
id="btn-add"
class="btn btn-primary btn-sm pull-right"
data-toggle="modal"
data-target="#modal-add"
onclick="add()">
<b>Adicionar</b>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<button
id="btn-search"
class="btn btn-info btn-sm pull-right"
data-toggle="modal"
data-target="#modal-search"
onclick="search()">
<b>Pesquisar</b>
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
<div class="row">
<div class="col-md-12"> </div>
</div>
<!-- Grid -->
<div id="grid" class="table-responsive">
<?php
echo $controller->getGrid(1);
?>
</div>
<!-- /Grid -->
<!-- Modais -->
<!-- Modal de adição -->
<div id="modal-add" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="modal-add" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button
type="button"
class="close"
data-dismiss="modal"
aria-hidden="true">×
</button>
<h3 class="modal-title">Adicionar Tipo de Solicitação</h3>
</div>
<div class="modal-body">
<form id="form-add" action="" method="post">
<div class="form-group">
<label for="nome">Nome</label>
<input
type="text"
id="nome"
name="nome"
class="form-control"
maxlength="80" />
</div>
<div class="form-group">
<div>
<label for="status">Status</label>
</div>
<input
type="checkbox"
id="status"
name="status"
value="A"
checked="checked"
disabled /> Ativo
</div>
<div class="modal-footer">
<button
type="submit"
class="btn btn-success">
Salvar
<span class="glyphicon glyphicon-floppy-disk"></span>
</button>
<button
type="reset"
class="btn btn-primary"
onclick="clean()">
Limpar
<span class="glyphicon glyphicon-file"></span>
</button>
<button
type="button"
class="btn btn-default"
data-dismiss="modal"
onclick="clean()">
Cancelar
<span class="glyphicon glyphicon-floppy-remove"></span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal de edição -->
<div class="modal fade" id="modal-edit" tabindex="-1" role="dialog"
aria-labelledby="modal-edit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Editar Tipo de Solicitação</h3>
</div>
<div class="modal-body">
<form role="form" id="form-edit" action="" method="post">
<div class="form-group">
<label for="nome">Nome</label>
<input
type="text"
id="nome"
name="nome"
class="form-control"
maxlength="80" />
</div>
<div class="form-group">
<div>
<label for="status">Status</label>
</div>
<input
type="checkbox"
id="status"
name="status"
value="A"
checked="checked" /> Ativo
</div>
<div class="modal-footer">
<button
type="submit"
class="btn btn-success" >Salvar
<span class="glyphicon glyphicon-floppy-disk"></span>
</button>
<button
type="reset"
class="btn btn-primary"
onclick="clean()">Limpar
<span class="glyphicon glyphicon-file"></span>
</button>
<button
type="button"
class="btn btn-default"
data-dismiss="modal"
onclick="clean()">Cancelar
<span class="glyphicon glyphicon-floppy-remove"></span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal de exclusão -->
<div id="modal-del" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="modal-del" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Exclusão de Tipo de Solicitação</h4>
</div>
<form id="form-del" action="" method="post">
<div class="modal-body">
<h5>Confirma a exclusão?</h5>
</div>
<div class="modal-footer">
<button
type="submit"
class="btn btn-danger">Sim
<span class="glyphicon glyphicon-floppy-disk"></span>
</button>
<button
type="button"
class="btn btn-primary"
data-dismiss="modal">Não
<span class="glyphicon glyphicon-floppy-remove"></span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal de pesquisa -->
<div
id="modal-search"
class="modal fade"
tabindex="-1"
role="dialog"
aria-labelledby="modal-edit"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button
type="button"
class="close"
data-dismiss="modal"
aria-hidden="true">×
</button>
<h3 class="modal-title">Pesquisar Lotação</h3>
</div>
<form id="form-search" role="form" method="post">
<div class="modal-body">
<div class="form-group">
<label for="nome">Filtro:</label>
<select
id="filtro"
name="filtro"
class="form-control">
<option value="">SELECIONE UM FILTRO</option>
<option value="id">ID</option>
<option value="nome">Nome</option>
<option value="status">Status</option>
</select>
</div>
<div class="form-group">
<label for="valor">Valor:</label>
<input id="valor" name="valor" type="text" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button
type="submit"
class="btn btn-success">Pesquisar
<span class="glyphicon glyphicon-search"></span>
</button>
<button
type="reset"
class="btn btn-primary"
onclick="clean()">Limpar
<span class="glyphicon glyphicon-file"></span>
</button>
<button
type="button"
class="btn btn-default"
data-dismiss="modal"
onclick="clean()">Cancelar
</button>
</div>
</form>
</div>
</div>
</div>
<!-- /Modais -->
<!-- Alertas -->
<div id="modal-danger" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="modal-del" aria-hidden="true">
<div class="alert alert-danger fade in" role="alert">
<button type="button" class="close" onclick="$('#modal-danger').modal('toggle');">
<span aria-hidden="true">×</span><span class="sr-only">Fechar</span>
</button>
<strong>FALHA:</strong>
<span id="alert-msg">Não é possível excluir um registro com referências.</span>
</div>
</div>
<div class="modal fade" id="modal-success" tabindex="-1" role="dialog" aria-labelledby="modal-del"
aria-hidden="true">
<div class="alert alert-success fade in" role="alert">
<button type="button" class="close" onclick="$('#modal-success').modal('toggle');">
<span aria-hidden="true">×</span><span class="sr-only">Fechar</span>
</button>
<strong>SUCESSO:</strong>
<span id="alert-msg">Dados atualizados</span>
</div>
</div>
<!-- Alertas -->
</div>
<!-- /Container -->
<?php
// Rodapé
@include $_SERVER['DOCUMENT_ROOT'] . '/sods/includes/rodape.php';
?> | gpl-2.0 |
ludovicdigitalcube/Syntec | sites/all/themes/Syntec/theme-settings.php | 449 | <?php
/**
* @file
* Theme settings file for the {{ THEME NAME }} theme.
*/
require_once dirname(__FILE__) . '/template.php';
/**
* Implements hook_form_FORM_alter().
*/
function Syntec_form_system_theme_settings_alter(&$form, $form_state) {
// You can use this hook to append your own theme settings to the theme
// settings form for your subtheme. You should also take a look at the
// 'extensions' concept in the Omega base theme.
}
| gpl-2.0 |
pzingg/saugus_elgg | units/admin/admin_users_panel.php | 746 | <?php
// Users panel
// $parameter = a row from the elgg.users database
if (isset($parameter)) {
$run_result .= templates_draw(array(
'context' => 'adminTable',
'name' => "<p>" . $parameter->username . "</p>",
'column1' => "<a href=\"" . url . "_userdetails/?profile_id=" .$parameter->ident . "&context=admin\" >" . stripslashes($parameter->name) . "</a> [<a href=\"".url . $parameter->username ."/\">" . gettext("Profile") . "</a>]",
'column2' => "<a href=\"mailto:" . $parameter->email. "\" >" . $parameter->email . "</a>"
)
);
}
?> | gpl-2.0 |
devernay/openfx-misc | Anaglyph/Anaglyph.cpp | 18379 | /* ***** BEGIN LICENSE BLOCK *****
* This file is part of openfx-misc <https://github.com/devernay/openfx-misc>,
* Copyright (C) 2013-2018 INRIA
*
* openfx-misc 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.
*
* openfx-misc 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 openfx-misc. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
/*
* OFX Anaglyph plugin.
* Make an anaglyph image out of the inputs.
*/
#include <algorithm>
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
#include <windows.h>
#endif
#include <cmath>
#include "ofxsProcessing.H"
#include "ofxsMacros.h"
#include "ofxsThreadSuite.h"
using namespace OFX;
OFXS_NAMESPACE_ANONYMOUS_ENTER
#define kPluginName "AnaglyphOFX"
#define kPluginGrouping "Views/Stereo"
#define kPluginDescription "Make an anaglyph image out of the two views of the input."
#define kPluginIdentifier "net.sf.openfx.anaglyphPlugin"
#define kPluginVersionMajor 1 // Incrementing this number means that you have broken backwards compatibility of the plug-in.
#define kPluginVersionMinor 0 // Increment this when you have fixed a bug or made it faster.
#define kSupportsTiles 1
#define kSupportsMultiResolution 1
#define kSupportsRenderScale 1
#define kSupportsMultipleClipPARs false
#define kSupportsMultipleClipDepths false
#define kRenderThreadSafety eRenderFullySafe
#define kParamAmtColour "amtcolor"
#define kParamAmtColourLabel "Color Amount"
#define kParamAmtColourHint "Amount of colour in the anaglyph: 0 = grayscale anaglyph, 1 = full-color anaglyph. Fusion is more difficult with full-color anaglyphs."
#define kParamSwap "swap"
#define kParamSwapLabel "(right=red)"
#define kParamSwapHint "Swap left and right views"
#define kParamOffset "offset"
#define kParamOffsetLabel "Horizontal Offset"
#define kParamOffsetHint "Horizontal offset. " \
"The red view is shifted to the left by half this amount, " \
"and the cyan view is shifted to the right by half this amount (in pixels)." // rounded up // rounded down
// Base class for the RGBA and the Alpha processor
class AnaglyphBase
: public ImageProcessor
{
protected:
const Image *_srcLeftImg;
const Image *_srcRightImg;
double _amtcolour;
bool _swap;
int _offset;
public:
/** @brief no arg ctor */
AnaglyphBase(ImageEffect &instance)
: ImageProcessor(instance)
, _srcLeftImg(NULL)
, _srcRightImg(NULL)
, _amtcolour(0.)
, _swap(false)
, _offset(0)
{
}
/** @brief set the left src image */
void setSrcLeftImg(const Image *v) {_srcLeftImg = v; }
/** @brief set the right src image */
void setSrcRightImg(const Image *v) {_srcRightImg = v; }
/** @brief set the amount of colour */
void setAmtColour(double v) {_amtcolour = v; }
/** @brief set view swap */
void setSwap(bool v) {_swap = v; }
/** @brief set view offset */
void setOffset(int v) {_offset = v; }
};
// template to do the RGBA processing
template <class PIX, int max>
class ImageAnaglypher
: public AnaglyphBase
{
public:
// ctor
ImageAnaglypher(ImageEffect &instance)
: AnaglyphBase(instance)
{}
private:
// and do some processing
void multiThreadProcessImages(OfxRectI procWindow)
{
const Image *srcRedImg = _srcLeftImg;
const Image *srcCyanImg = _srcRightImg;
if (_swap) {
std::swap(srcRedImg, srcCyanImg);
}
const OfxRectI& srcRedBounds = srcRedImg->getBounds();
const OfxRectI& srcCyanBounds = srcCyanImg->getBounds();
for (int y = procWindow.y1; y < procWindow.y2; y++) {
if ( _effect.abort() ) {
break;
}
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for (int x = procWindow.x1; x < procWindow.x2; x++) {
// clamp x to avoid black borders
int xRed = (std::min)((std::max)(srcRedBounds.x1, x + (_offset + 1) / 2), srcRedBounds.x2 - 1);
int xCyan = (std::min)((std::max)(srcCyanBounds.x1, x - _offset / 2), srcCyanBounds.x2 - 1);
const PIX *srcRedPix = (const PIX *)(srcRedImg ? srcRedImg->getPixelAddress(xRed, y) : 0);
const PIX *srcCyanPix = (const PIX *)(srcCyanImg ? srcCyanImg->getPixelAddress(xCyan, y) : 0);
dstPix[3] = 0; // start with transparent
if (srcRedPix) {
PIX srcLuminance = luminance(srcRedPix[0], srcRedPix[1], srcRedPix[2]);
dstPix[0] = (PIX)(srcLuminance * (1.f - (float)_amtcolour) + srcRedPix[0] * (float)_amtcolour);
dstPix[3] += (PIX)(0.5f * srcRedPix[3]);
} else {
// no src pixel here, be black and transparent
dstPix[0] = 0;
}
if (srcCyanPix) {
PIX srcLuminance = luminance(srcCyanPix[0], srcCyanPix[1], srcCyanPix[2]);
dstPix[1] = (PIX)(srcLuminance * (1.f - (float)_amtcolour) + srcCyanPix[1] * (float)_amtcolour);
dstPix[2] = (PIX)(srcLuminance * (1.f - (float)_amtcolour) + srcCyanPix[2] * (float)_amtcolour);
dstPix[3] += (PIX)(0.5f * srcCyanPix[3]);
} else {
// no src pixel here, be black and transparent
dstPix[1] = 0;
dstPix[2] = 0;
}
// increment the dst pixel
dstPix += 4;
}
}
} // multiThreadProcessImages
private:
/** @brief luminance from linear RGB according to Rec.709.
See http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC9 */
static PIX luminance(PIX red,
PIX green,
PIX blue)
{
return PIX(0.2126 * red + 0.7152 * green + 0.0722 * blue);
}
};
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class AnaglyphPlugin
: public ImageEffect
{
public:
/** @brief ctor */
AnaglyphPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, _dstClip(NULL)
, _srcClip(NULL)
, _amtcolour(NULL)
, _swap(NULL)
, _offset(NULL)
{
_dstClip = fetchClip(kOfxImageEffectOutputClipName);
assert( _dstClip && (!_dstClip->isConnected() || _dstClip->getPixelComponents() == ePixelComponentRGBA) );
_srcClip = getContext() == eContextGenerator ? NULL : fetchClip(kOfxImageEffectSimpleSourceClipName);
assert( (!_srcClip && getContext() == eContextGenerator) ||
( _srcClip && (!_srcClip->isConnected() || _srcClip->getPixelComponents() == ePixelComponentRGBA) ) );
_amtcolour = fetchDoubleParam(kParamAmtColour);
_swap = fetchBooleanParam(kParamSwap);
_offset = fetchIntParam(kParamOffset);
assert(_amtcolour && _swap && _offset);
}
private:
/* Override the render */
virtual void render(const RenderArguments &args) OVERRIDE FINAL;
/* set up and run a processor */
void setupAndProcess(AnaglyphBase &, const RenderArguments &args);
virtual void getFrameViewsNeeded(const FrameViewsNeededArguments& args, FrameViewsNeededSetter& frameViews) OVERRIDE FINAL;
private:
// do not need to delete these, the ImageEffect is managing them for us
Clip *_dstClip;
Clip *_srcClip;
DoubleParam *_amtcolour;
BooleanParam *_swap;
IntParam *_offset;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
AnaglyphPlugin::setupAndProcess(AnaglyphBase &processor,
const RenderArguments &args)
{
// get a dst image
auto_ptr<Image> dst( _dstClip->fetchImage(args.time) );
if ( !dst.get() ) {
throwSuiteStatusException(kOfxStatFailed);
}
BitDepthEnum dstBitDepth = dst->getPixelDepth();
PixelComponentEnum dstComponents = dst->getPixelComponents();
if ( ( dstBitDepth != _dstClip->getPixelDepth() ) ||
( ( dstComponents != _dstClip->getPixelComponents() ) || (dstComponents != ePixelComponentRGBA) ) ) {
setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong depth or components");
throwSuiteStatusException(kOfxStatFailed);
}
if ( (dst->getRenderScale().x != args.renderScale.x) ||
( dst->getRenderScale().y != args.renderScale.y) ||
( ( dst->getField() != eFieldNone) /* for DaVinci Resolve */ && ( dst->getField() != args.fieldToRender) ) ) {
setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
throwSuiteStatusException(kOfxStatFailed);
}
// fetch main input image
auto_ptr<const Image> srcLeft( ( _srcClip && _srcClip->isConnected() ) ?
_srcClip->fetchImagePlane(args.time, 0, kFnOfxImagePlaneColour) : 0 );
if ( srcLeft.get() ) {
if ( (srcLeft->getRenderScale().x != args.renderScale.x) ||
( srcLeft->getRenderScale().y != args.renderScale.y) ||
( ( srcLeft->getField() != eFieldNone) /* for DaVinci Resolve */ && ( srcLeft->getField() != args.fieldToRender) ) ) {
setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
throwSuiteStatusException(kOfxStatFailed);
}
}
auto_ptr<const Image> srcRight( ( _srcClip && _srcClip->isConnected() ) ?
_srcClip->fetchImagePlane(args.time, 1, kFnOfxImagePlaneColour) : 0 );
if ( srcRight.get() ) {
if ( (srcRight->getRenderScale().x != args.renderScale.x) ||
( srcRight->getRenderScale().y != args.renderScale.y) ||
( ( srcRight->getField() != eFieldNone) /* for DaVinci Resolve */ && ( srcRight->getField() != args.fieldToRender) ) ) {
setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties");
throwSuiteStatusException(kOfxStatFailed);
}
}
// make sure bit depths are sane
if ( srcLeft.get() ) {
BitDepthEnum srcBitDepth = srcLeft->getPixelDepth();
PixelComponentEnum srcComponents = srcLeft->getPixelComponents();
// see if they have the same depths and bytes and all
if ( (srcBitDepth != dstBitDepth) || (srcComponents != dstComponents) ) {
throwSuiteStatusException(kOfxStatErrImageFormat);
}
}
if ( srcRight.get() ) {
BitDepthEnum srcBitDepth = srcRight->getPixelDepth();
PixelComponentEnum srcComponents = srcRight->getPixelComponents();
// see if they have the same depths and bytes and all
if ( (srcBitDepth != dstBitDepth) || (srcComponents != dstComponents) ) {
throwSuiteStatusException(kOfxStatErrImageFormat);
}
}
double amtcolour = _amtcolour->getValueAtTime(args.time);
bool swap = _swap->getValueAtTime(args.time);
int offset = _offset->getValueAtTime(args.time);
// set the images
processor.setDstImg( dst.get() );
processor.setSrcLeftImg( srcLeft.get() );
processor.setSrcRightImg( srcRight.get() );
// set the render window
processor.setRenderWindow(args.renderWindow);
// set the parameters
processor.setAmtColour(amtcolour);
processor.setSwap(swap);
processor.setOffset( (int)std::floor(offset * args.renderScale.x + 0.5) );
// Call the base class process member, this will call the derived templated process code
processor.process();
} // AnaglyphPlugin::setupAndProcess
void
AnaglyphPlugin::getFrameViewsNeeded(const FrameViewsNeededArguments& args,
FrameViewsNeededSetter& frameViews)
{
OfxRangeD range;
range.min = range.max = args.time;
frameViews.addFrameViewsNeeded(*_srcClip, range, 0);
frameViews.addFrameViewsNeeded(*_srcClip, range, 1);
}
// the overridden render function
void
AnaglyphPlugin::render(const RenderArguments &args)
{
assert( kSupportsMultipleClipPARs || !_srcClip || _srcClip->getPixelAspectRatio() == _dstClip->getPixelAspectRatio() );
assert( kSupportsMultipleClipDepths || !_srcClip || _srcClip->getPixelDepth() == _dstClip->getPixelDepth() );
// instantiate the render code based on the pixel depth of the dst clip
BitDepthEnum dstBitDepth = _dstClip->getPixelDepth();
PixelComponentEnum dstComponents = _dstClip->getPixelComponents();
// do the rendering
assert(dstComponents == ePixelComponentRGBA);
switch (dstBitDepth) {
case eBitDepthUByte: {
ImageAnaglypher<unsigned char, 255> fred(*this);
setupAndProcess(fred, args);
break;
}
case eBitDepthUShort: {
ImageAnaglypher<unsigned short, 65535> fred(*this);
setupAndProcess(fred, args);
break;
}
case eBitDepthFloat: {
ImageAnaglypher<float, 1> fred(*this);
setupAndProcess(fred, args);
break;
}
default:
throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
mDeclarePluginFactory(AnaglyphPluginFactory, {ofxsThreadSuiteCheck();}, {});
#if 0
void
AnaglyphPluginFactory::load()
{
// we can't be used on hosts that don't support the stereoscopic suite
// returning an error here causes a blank menu entry in Nuke
//if (!fetchSuite(kOfxVegasStereoscopicImageEffectSuite, 1, true)) {
// throwHostMissingSuiteException(kOfxVegasStereoscopicImageEffectSuite);
//}
}
#endif
void
AnaglyphPluginFactory::describe(ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabel(kPluginName);
desc.setPluginGrouping(kPluginGrouping);
desc.setPluginDescription(kPluginDescription);
// add the supported contexts, only filter at the moment
desc.addSupportedContext(eContextFilter);
// add supported pixel depths
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
// set a few flags
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setSupportsMultiResolution(kSupportsMultiResolution);
desc.setSupportsTiles(kSupportsTiles);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(false);
desc.setSupportsMultipleClipPARs(kSupportsMultipleClipPARs);
desc.setSupportsMultipleClipDepths(kSupportsMultipleClipDepths);
desc.setRenderThreadSafety(kRenderThreadSafety);
// returning an error here crashes Nuke
//if (!fetchSuite(kOfxVegasStereoscopicImageEffectSuite, 1, true)) {
// throwHostMissingSuiteException(kOfxVegasStereoscopicImageEffectSuite);
//}
//We're using the view calls (i.e: getFrameViewsNeeded)
desc.setIsViewAware(true);
//We render the same thing on all views
desc.setIsViewInvariant(eViewInvarianceAllViewsInvariant);
#ifdef OFX_EXTENSIONS_NATRON
desc.setChannelSelector(ePixelComponentNone);
#endif
}
void
AnaglyphPluginFactory::describeInContext(ImageEffectDescriptor &desc,
ContextEnum /*context*/)
{
if ( !fetchSuite(kFnOfxImageEffectPlaneSuite, 2, true) ) {
throwHostMissingSuiteException(kFnOfxImageEffectPlaneSuite);
}
// Source clip only in the filter context
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(kSupportsTiles);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(kSupportsTiles);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
{
DoubleParamDescriptor *param = desc.defineDoubleParam(kParamAmtColour);
param->setLabel(kParamAmtColourLabel);
param->setHint(kParamAmtColourHint);
param->setDefault(0.);
param->setRange(0., 1.);
param->setIncrement(0.01);
param->setDisplayRange(0., 1.);
param->setDoubleType(eDoubleTypeScale);
param->setAnimates(true);
if (page) {
page->addChild(*param);
}
}
{
BooleanParamDescriptor *param = desc.defineBooleanParam(kParamSwap);
param->setLabel(kParamSwapLabel);
param->setDefault(false);
param->setHint(kParamSwapHint);
param->setAnimates(true);
if (page) {
page->addChild(*param);
}
}
{
IntParamDescriptor *param = desc.defineIntParam(kParamOffset);
param->setLabel(kParamOffsetLabel);
param->setHint(kParamOffsetHint);
param->setDefault(0);
param->setRange(-1000, 1000);
param->setDisplayRange(-100, 100);
param->setAnimates(true);
if (page) {
page->addChild(*param);
}
}
} // AnaglyphPluginFactory::describeInContext
ImageEffect*
AnaglyphPluginFactory::createInstance(OfxImageEffectHandle handle,
ContextEnum /*context*/)
{
return new AnaglyphPlugin(handle);
}
static AnaglyphPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
mRegisterPluginFactoryInstance(p)
OFXS_NAMESPACE_ANONYMOUS_EXIT
| gpl-2.0 |
dropndotltd/relaunch | wp-content/themes/affluent/includes/layout/layout_comments.php | 1488 | <?php
//Generates the comments layout
function cpotheme_layout_comments($comment, $args, $depth){
$GLOBALS['comment'] = $comment;
//Normal Comments
switch($comment->comment_type): case '': ?>
<li class="comment" id="comment-<?php comment_ID(); ?>">
<div class="comment-avatar">
<?php echo get_avatar($comment, 50); ?>
</div>
<div class="comment-title">
<div class="comment-options secondary-color-bg">
<?php edit_comment_link(__('Edit', 'cpotheme')); ?>
<?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth']))); ?>
</div>
<div class="comment-author">
<?php echo get_comment_author_link(); ?>
</div>
<div class="comment-date">
<a href="<?php echo esc_url(get_comment_link($comment->comment_ID)); ?>">
<?php printf(__('%1$s at %2$s', 'cpotheme'), get_comment_date(), get_comment_time()); ?>
</a>
</div>
</div>
<div class="comment-content">
<?php if($comment->comment_approved == '0'): ?>
<em class="comment-approval"><?php _e('Your comment is awaiting approval.', 'cpotheme'); ?></em>
<?php endif; ?>
<?php comment_text(); ?>
</div>
<?php break;
//Pingbacks & Trackbacks
case 'pingback':
case 'trackback': ?>
<li class="pingback">
<?php comment_author_link(); ?><?php edit_comment_link(__('Edit', 'cpotheme'), ' (', ')'); ?>
<?php break;
endswitch;
} | gpl-2.0 |
openfoodfoundation/openfoodnetwork-wp | wp-content/plugins/theblog-shortcodes/shortcodes/google-adsense-responsive.php | 3335 | <?php
/* GOOGLE ADSENSE RESPONSIVE ADS */
if(!function_exists('cactus_echo_responsive_ad')){
function cactus_echo_responsive_ad($publisher_id,$ad_slot_id){
$idx = rand(0,1000);
?>
<div id="google-ads-<?php echo $idx;?>"></div>
<script type="text/javascript">
/* Calculate the width of available ad space */
ad = document.getElementById('google-ads-<?php echo $idx;?>');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width; // for modern browsers
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Replace ca-pub-XXX with your AdSense Publisher ID */
google_ad_client = '<?php echo $publisher_id;?>';
/* Replace 1234567890 with the AdSense Ad Slot ID */
google_ad_slot = '<?php echo $ad_slot_id;?>';
/* Do not change anything after this line */
if ( adWidth >= 728 )
google_ad_size = ["728", "90"]; /* Leaderboard 728x90 */
else if ( adWidth >= 468 )
google_ad_size = ["468", "60"]; /* Banner (468 x 60) */
else if ( adWidth >= 336 )
google_ad_size = ["336", "280"]; /* Large Rectangle (336 x 280) */
else if ( adWidth >= 300 )
google_ad_size = ["300", "250"]; /* Medium Rectangle (300 x 250) */
else if ( adWidth >= 250 )
google_ad_size = ["250", "250"]; /* Square (250 x 250) */
else if ( adWidth >= 200 )
google_ad_size = ["200", "200"]; /* Small Square (200 x 200) */
else if ( adWidth >= 180 )
google_ad_size = ["180", "150"]; /* Small Rectangle (180 x 150) */
else
google_ad_size = ["125", "125"]; /* Button (125 x 125) */
document.write (
'<ins class="adsbygoogle" style="display:inline-block;width:'
+ google_ad_size[0] + 'px;height:'
+ google_ad_size[1] + 'px" data-ad-client="'
+ google_ad_client + '" data-ad-slot="'
+ google_ad_slot + '"></ins>'
);
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<?php
}
}
if(!function_exists('cactus_display_ads')){
function cactus_display_ads($section){
$ad_top_1 = ot_get_option($section);
$adsense_publisher_id = ot_get_option('adsense_id');
$adsense_slot_top_1 = ot_get_option('adsense_slot_' . $section);
if($adsense_publisher_id != '' && $adsense_slot_top_1 != ''){
?>
<div class='ad <?php echo $section;?>'><?php cactus_echo_responsive_ad($adsense_publisher_id, $adsense_slot_top_1);?></div>
<?php
} elseif($ad_top_1 != ''){?>
<div class='ad <?php echo $section;?>'><?php echo $ad_top_1;?></div>
<?php }
}
}
if(!function_exists('tm_adsense_responsive')){
function tm_adsense_responsive($atts){
$pub_id = '';
$slot_id = '';
$class = '';
if(isset($atts['pub']) && $atts['pub'] != '') $pub_id = $atts['pub'];
if(isset($atts['slot']) && $atts['slot'] != '') $slot_id = $atts['slot'];
if(isset($atts['class']) && $atts['class'] != '') $class = $atts['class'];
if($pub_id != '' && $slot_id != ''){
?>
<div class='ad <?php echo $class;?>'><?php cactus_echo_responsive_ad($pub_id,$slot_id);?></div>
<?php
}
}
}
add_shortcode('adsense','tm_adsense_responsive');
/* end GOOGLE ADSENSE RESPONSIVE ADS SUPPORT*/ | gpl-2.0 |
haidarafif0809/qwooxcqmkozzxce | cek_stok_konversi_penjualan.php | 730 | <?php session_start();
include 'db.php';
$satuan_konversi = $_POST['satuan_konversi'];
$jumlah_barang = $_POST['jumlah_barang'];
$kode_barang = $_POST['kode_barang'];
$id_produk = $_POST['id_produk'];
$queryy = $db->query("SELECT SUM(sisa) AS total_sisa FROM hpp_masuk WHERE kode_barang = '$kode_barang' ");
$dataaa = mysqli_fetch_array($queryy);
$stok = $dataaa['total_sisa'];
$query = $db->query("SELECT konversi FROM satuan_konversi WHERE id_satuan = '$satuan_konversi' AND id_produk = '$id_produk'");
$data = mysqli_fetch_array($query);
$hasil = $jumlah_barang * $data['konversi'];
echo $hasil1 = $stok - $hasil;
//Untuk Memutuskan Koneksi Ke Database
mysqli_close($db);
?>
| gpl-2.0 |
pablolima/ElectronicMedicalPrescriptions | Receituario/Ajuda.xaml.cs | 557 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Receituario
{
/// <summary>
/// Interaction logic for Ajuda.xaml
/// </summary>
public partial class Ajuda : Window
{
public Ajuda()
{
InitializeComponent();
}
}
}
| gpl-2.0 |
JimMackin/SuiteCRM-Build-Maker | scripts/suite_install/AdvancedOpenPortal.php | 394 | <?php
function update_aop() {
updateScheduler();
}
function updateScheduler(){
require_once('modules/Schedulers/Scheduler.php');
$scheduler = new Scheduler();
$schedulers = $scheduler->get_full_list('','job = "function::pollMonitoredInboxesCustomAOP"');
foreach($schedulers as $scheduler){
$scheduler->job = "function::pollMonitoredInboxesAOP";
$scheduler->save();
}
}
| gpl-2.0 |
TestLinkOpenSourceTRMS/testlink-code | lib/functions/oauth_providers/github.php | 3554 | <?php
/**
* TestLink Open Source Project - http://testlink.sourceforge.net/
* This script is distributed under the GNU General Public License 2 or later.
*
* @filesource github.php
*
* Github OAUTH API (authentication)
*
* @internal revisions
* @since 1.9.17
*
*/
// Get token
function oauth_get_token($authCfg, $code) {
$result = new stdClass();
$result->status = array('status' => tl::OK, 'msg' => null);
// Params to get token
$oauthParams = array(
'code' => $code,
'client_id' => $authCfg['oauth_client_id'],
'client_secret' => $authCfg['oauth_client_secret']
);
$oauthParams['redirect_uri'] = $oauthCfg['redirect_uri'];
if( isset($_SERVER['HTTPS']) ) {
$oauthParams['redirect_uri'] =
str_replace('http://', 'https://', $oauthParams['redirect_uri']);
}
$curlAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1';
$curlContentType = array('Content-Type: application/xml','Accept: application/json');
// Step #1 - Get the token
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $authCfg['token_url']);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($oauthParams));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result_curl = curl_exec($curl);
if( $result_curl === false ) {
echo 'Curl error: ' . curl_error($curl);
echo '<pre>';
var_dump(curl_getinfo($curl));
echo '</pre>';
die();
}
curl_close($curl);
$tokenInfo = json_decode($result_curl);
// If token is received start session
if (isset($tokenInfo->access_token)) {
$oauthParams['access_token'] = $tokenInfo->access_token;
$curlContentType = array('Authorization: token ' . $tokenInfo->access_token, 'Content-Type: application/xml','Accept: application/json');
$queryString = http_build_query($tokenInfo);
$targetURL = array();
$targetURL['user'] = $authCfg['oauth_profile'] . '?' . $queryString;
$targetURL['email'] = $authCfg['oauth_profile'] . '/emails?'. $queryString;
// Get User
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $targetURL['user']);
curl_setopt($curl, CURLOPT_USERAGENT, $curlAgent);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlContentType);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result_curl = curl_exec($curl);
$userInfo = json_decode($result_curl, true);
curl_close($curl);
if (!isset($userInfo['login'])) {
$result->status['msg'] = 'User ID is empty';
$result->status['status'] = tl::ERROR;
}
// Get email
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $targetURL['email'] );
curl_setopt($curl, CURLOPT_USERAGENT, $curlAgent);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlContentType);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result_curl = curl_exec($curl);
$emailInfo = json_decode($result_curl, true);
curl_close($curl);
$result->options = new stdClass();
$result->options->givenName = $userInfo['login'];
$result->options->familyName = $userInfo['id'];
$result->options->user = $emailInfo[0]['email'];
$result->options->auth = 'oauth';
} else {
$result->status['msg'] = 'An error occurred during getting token';
$result->status['status'] = tl::ERROR;
}
return $result;
}
| gpl-2.0 |
mywebclass/cidrupal | sites/all/modules/wconsumer/lib/Drupal/wconsumer/Rest/Authentication/HttpAuth/HttpAuth.php | 3159 | <?php
/**
* HTTP Authentication
*
* @package wconsumer
* @subpackage request
*/
namespace Drupal\wconsumer\Rest\Authentication\HttpAuth;
use Drupal\wconsumer\Rest\Authentication as AuthencationBase,
Drupal\wconsumer\Common\AuthInterface,
Guzzle\Plugin\CurlAuth\CurlAuthPlugin as GuzzleHttpAuth,
Drupal\wconsumer\Exception as WcException;
/**
* HTTP Authentication
*
* Used for services that require a specific HTTP username and/or password
*
* @package wconsumer
* @subpackage request
*/
class HttpAuth extends AuthencationBase implements AuthInterface {
/**
* Define if they need a username
*
* @var boolean
*/
public $needsUsername = false;
/**
* Define if they need a password
*
* @var boolean
*/
public $needsPassword = false;
/**
* Format Registry Credentials
*
* @param array
* @return array
*/
public function formatRegistry($data)
{
if ($this->needsUsername AND ( ! isset($data['username']) OR empty($data['username'])))
throw new WcException('HTTP Auth requires username and is not set or is empty.');
if ($this->needsPassword AND ( ! isset($data['password']) OR empty($data['password'])))
throw new WcException('HTTP Auth requires password and is not set or is empty.');
return array(
'username' => ($this->needsUsername) ? $data['username'] : '',
'password' => ($this->needsPassword) ? $data['password'] : ''
);
}
/**
* Format the Saved Credentials
*
* Not used in HTTP Auth API
*
* @param array
* @return array Empty array
*/
public function formatCredentials($data)
{
return array();
}
/**
* Validate if they're setup
*
* @param string
* @return boolean
*/
public function is_initialized($type = 'user')
{
switch($type) {
case 'system' :
$registry = $this->_instance->getRegistry();
if (! $registry OR ! isset($registry->credentials)) return FALSE;
if ($this->needsUsername AND empty($registry->credentials['username']))
return FALSE;
if ($this->needsPassword AND empty($registry->credentials['password']))
return FALSE;
return TRUE;
break;
case 'user' :
return TRUE;
break;
default :
return FALSE;
}
}
/**
* Sign the request before sending it off
*
* @param object Client
* @access private
*/
public function sign_request(&$client)
{
$registry = $this->_instance->getRegistry();
// Add the auth plugin to the client object
$authPlugin = new GuzzleHttpAuth(
($this->needsUsername) ? $registry->credentials['username'] : '',
($this->needsPassword) ? $registry->credentials['password'] : ''
);
$client->addSubscriber($authPlugin);
}
/**
* Authenticate the User
*
* Not needed for HTTP Auth
*/
public function authenticate(&$user) { }
/**
* Log the user out
*
* Not needed for HTTP Auth
*/
public function logout(&$logout) { }
/**
* Callback
*
* Not needed for HTTP Auth
*/
public function onCallback(&$user, $values) { }
}
| gpl-2.0 |
bbinet/GoIoT | apps/cloud/cloudapi.lua | 1353 |
local http = require 'socket.http'
local ltn12 = require 'ltn12'
local url = require 'socket.url'
local pp = require 'shared.util.PrettyPrint'
local cjson = require 'cjson.safe'
local KEY = nil
local URL = nil
local function api(method, obj, path)
assert(path)
print(URL..'/'..path)
local u = url.parse(URL..'/'..path, {path=path, scheme='http'})
local rstring = cjson.encode(obj)
--print('JSON', rstring)
local re = {}
u.source = ltn12.source.string(rstring)
u.sink, re = ltn12.sink.table(re)
u.method = method
u.headers = {}
u.headers['U-ApiKey'] = KEY
u.headers["content-length"] = string.len(rstring)
--print(string.len(rstring))
u.headers["content-type"] = "application/json;charset=utf-8"
local r, code, headers, status = http.request(u)
print(r, code)--, pp(headers), status)
if r and code == 200 then
return true
else
return nil, 'Error: code['..(code or 'Unknown')..'] status ['..(status or '')..']'
end
--[[
if r and code == 200 then
if #re == 0 then
return r, code, headers, status
end
local j, err = cjson.decode(table.concat(re))
if j then
print(pp(j))
return j
else
return nil, code, headers, status, err
end
end
return nil, code, headers, status
]]--
end
return {
init = function (key, url, timeout)
KEY = key
URL = url
http.TIMEOUT = timeout or 5
end,
call = api,
}
| gpl-2.0 |
marcoargenti/Cleaner | src/main/java/schema/information_schema/tables/SessionStatus.java | 2855 | /**
* This class is generated by jOOQ
*/
package schema.information_schema.tables;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.5.4"
},
comments = "This class is generated by jOOQ"
)
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SessionStatus extends org.jooq.impl.TableImpl<schema.information_schema.tables.records.SessionStatusRecord> {
private static final long serialVersionUID = 1681869408;
/**
* The reference instance of <code>information_schema.SESSION_STATUS</code>
*/
public static final schema.information_schema.tables.SessionStatus SESSION_STATUS = new schema.information_schema.tables.SessionStatus();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<schema.information_schema.tables.records.SessionStatusRecord> getRecordType() {
return schema.information_schema.tables.records.SessionStatusRecord.class;
}
/**
* The column <code>information_schema.SESSION_STATUS.VARIABLE_NAME</code>.
*/
public final org.jooq.TableField<schema.information_schema.tables.records.SessionStatusRecord, java.lang.String> VARIABLE_NAME = createField("VARIABLE_NAME", org.jooq.impl.SQLDataType.VARCHAR.length(64).nullable(false).defaulted(true), this, "");
/**
* The column <code>information_schema.SESSION_STATUS.VARIABLE_VALUE</code>.
*/
public final org.jooq.TableField<schema.information_schema.tables.records.SessionStatusRecord, java.lang.String> VARIABLE_VALUE = createField("VARIABLE_VALUE", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, "");
/**
* Create a <code>information_schema.SESSION_STATUS</code> table reference
*/
public SessionStatus() {
this("SESSION_STATUS", null);
}
/**
* Create an aliased <code>information_schema.SESSION_STATUS</code> table reference
*/
public SessionStatus(java.lang.String alias) {
this(alias, schema.information_schema.tables.SessionStatus.SESSION_STATUS);
}
private SessionStatus(java.lang.String alias, org.jooq.Table<schema.information_schema.tables.records.SessionStatusRecord> aliased) {
this(alias, aliased, null);
}
private SessionStatus(java.lang.String alias, org.jooq.Table<schema.information_schema.tables.records.SessionStatusRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, schema.information_schema.InformationSchema.INFORMATION_SCHEMA, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public schema.information_schema.tables.SessionStatus as(java.lang.String alias) {
return new schema.information_schema.tables.SessionStatus(alias, this);
}
/**
* Rename this table
*/
public schema.information_schema.tables.SessionStatus rename(java.lang.String name) {
return new schema.information_schema.tables.SessionStatus(name, null);
}
}
| gpl-2.0 |
mohammadhamad/mhh | repos/base-hw/src/base/pager.cc | 2976 | /*
* \brief Pager implementations that are specific for the HW-core
* \author Martin Stein
* \date 2012-03-29
*/
/*
* Copyright (C) 2012-2013 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
/* Genode includes */
#include <base/pager.h>
#include <base/printf.h>
using namespace Genode;
/*************
** Mapping **
*************/
Mapping::Mapping(addr_t const va, addr_t const pa, bool const wc,
bool const io, unsigned const sl2, bool const w)
:
virt_address(va), phys_address(pa), write_combined(wc),
io_mem(io), size_log2(sl2), writable(w)
{ }
Mapping::Mapping()
:
virt_address(0), phys_address(0), write_combined(0),
io_mem(0), size_log2(0), writable(0)
{ }
void Mapping::prepare_map_operation() { }
/***************
** Ipc_pager **
***************/
addr_t Ipc_pager::fault_ip() const { return _fault.ip; }
addr_t Ipc_pager::fault_addr() const { return _fault.addr; }
bool Ipc_pager::is_write_fault() const { return _fault.writes; }
void Ipc_pager::set_reply_mapping(Mapping m) { _mapping = m; }
/******************
** Pager_object **
******************/
Thread_capability Pager_object::thread_cap() const { return _thread_cap; }
void Pager_object::thread_cap(Thread_capability const & c) { _thread_cap = c; }
Signal * Pager_object::_signal() const { return (Signal *)_signal_buf; }
void Pager_object::wake_up() { fault_resolved(); }
void Pager_object::exception_handler(Signal_context_capability) { }
Pager_object::Pager_object(unsigned const badge, Affinity::Location)
:
_signal_valid(0),
_badge(badge)
{ }
unsigned Pager_object::signal_context_id() const
{
return _signal_context_cap.dst();
}
/***************************
** Pager_activation_base **
***************************/
void Pager_activation_base::ep(Pager_entrypoint * const ep) { _ep = ep; }
Pager_activation_base::Pager_activation_base(char const * const name,
size_t const stack_size)
:
Thread_base(name, stack_size), _cap_valid(Lock::LOCKED), _ep(0)
{ }
Native_capability Pager_activation_base::cap()
{
if (!_cap.valid()) { _cap_valid.lock(); }
return _cap;
}
/**********************
** Pager_entrypoint **
**********************/
void Pager_entrypoint::dissolve(Pager_object * const o)
{
remove_locked(o);
o->stop_paging();
_activation->Signal_receiver::dissolve(o);
}
Pager_entrypoint::Pager_entrypoint(Cap_session *,
Pager_activation_base * const activation)
:
_activation(activation)
{
_activation->ep(this);
}
Pager_capability Pager_entrypoint::manage(Pager_object * const o)
{
unsigned const d = _activation->cap().dst();
unsigned const b = o->badge();
auto const p = reinterpret_cap_cast<Pager_object>(Native_capability(d, b));
o->start_paging(_activation->Signal_receiver::manage(o), p);
insert(o);
return p;
}
| gpl-2.0 |
mmtsweng/remembrancer_pi | src/remembrancer_pi.cpp | 11203 |
#include "wx/wxprec.h"
#include "wx/timer.h"
#include "wx/fileconf.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif //precompiled headers
#include <wx/aui/aui.h>
#include "time.h"
#include "remembrancer_pi.h"
#include "dialogDefinitions.h"
#include "icons.h"
// the class factories, used to create and destroy instances of the PlugIn
extern "C" DECL_EXP opencpn_plugin* create_pi(void *ppimgr)
{
return new remembrancer_pi(ppimgr);
}
extern "C" DECL_EXP void destroy_pi(opencpn_plugin* p)
{
delete p;
}
//UI Elements
AlertDialog *m_alertWindow;
PropertyDialog *m_propertiesWindow;
wxWindow *m_parent_window;
wxAuiManager *m_AUImgr;
wxString m_alertFileWav;
bool m_alertPlaySound;
/*
Constructor
Initialize Images
*/
remembrancer_pi::remembrancer_pi(void *ppimgr)
: opencpn_plugin_18(ppimgr)
{
try
{
initialize_images();
}
catch(...)
{
}
}
/*
Initialization
*/
int remembrancer_pi::Init(void)
{
// Get a pointer to the opencpn display canvas, to use as a parent for windows created
m_parent_window = GetOCPNCanvasWindow();
// Get a reference to the OCPN Configuration object
m_pconfig = GetOCPNConfigObject();
// Create the Context Menu Items
// In order to avoid an ASSERT on msw debug builds,
// we need to create a dummy menu to act as a surrogate parent of the created MenuItems
// The Items will be re-parented when added to the real context meenu
wxMenu dummy_menu;
wxMenuItem *pmi = new wxMenuItem(&dummy_menu, -1, _("Show PlugIn DemoWindow"));
m_show_id = AddCanvasContextMenuItem(pmi, this );
SetCanvasContextMenuItemViz(m_show_id, true);
wxMenuItem *pmih = new wxMenuItem(&dummy_menu, -1, _("Hide PlugIn DemoWindow"));
m_hide_id = AddCanvasContextMenuItem(pmih, this );
SetCanvasContextMenuItemViz(m_hide_id, false);
//Set Default values - not configuration values
m_alertWindow = NULL;
m_propertiesWindow = NULL;
m_activeRoute = false;
LoadConfig();
InitReminder();
// This PlugIn needs a toolbar icon
m_toolbar_item_id = InsertPlugInTool(_T(""), _img_remembrancer_inactive, _img_remembrancer_inactive, wxITEM_CHECK,
_("Remembrancer"), _T(""), NULL, REMEMBRANCER_TOOL_POSITION, 0, this);
return (
INSTALLS_CONTEXTMENU_ITEMS |
WANTS_PLUGIN_MESSAGING |
WANTS_PREFERENCES |
WANTS_CONFIG |
WANTS_TOOLBAR_CALLBACK |
WANTS_OPENGL_OVERLAY_CALLBACK |
INSTALLS_TOOLBAR_TOOL |
INSTALLS_CONTEXTMENU_ITEMS
);
}
/*
DeInitialize the plugin
Disconnect timer
*/
bool remembrancer_pi::DeInit(void)
{
wxLogMessage(_T("REMEMBRANCER: DeInit"));
m_AUImgr->DetachPane(m_alertWindow);
m_AUImgr->DetachPane(m_propertiesWindow);
if(m_alertWindow)
{
m_alertWindow->Close();
}
if (m_propertiesWindow)
{
m_propertiesWindow->Close();
}
m_timer.Stop();
m_timer.Disconnect(wxEVT_TIMER, wxTimerEventHandler(remembrancer_pi::OnTimer), NULL, this);
if (_img_remembrancer_active)
{
delete _img_remembrancer_active;
}
if (_img_remembrancer_inactive)
{
delete _img_remembrancer_inactive;
}
return true;
}
/*
Timer Event
Fires every X ms
Check to see if we are actively following a route, and alert if so
*/
void remembrancer_pi::OnTimer(wxTimerEvent& event)
{
if (m_activeRoute && m_alertingEnabled)
{
//wxLogMessage(_T("REMEMBRANCER: Alert fired"));
if (!m_alertWindow)
{
m_alertWindow = new AlertDialog(*this, m_parent_window);
}
m_alertWindow->Show(true);
PlayAlertSound();
}
}
/*
JSON Message received handler
- Listens for route activation and deactivation
*/
void remembrancer_pi::SetPluginMessage(wxString &message_id, wxString &message_body)
{
//wxLogMessage(_T("REMEMBRANCER: JSON Message Received...\n") + message_body);
if (message_id == _T("OCPN_RTE_ACTIVATED"))
{
m_activeRoute = true;
SetToolbarToolBitmaps(m_toolbar_item_id, _img_remembrancer_active, _img_remembrancer_active);
}
if (message_id == _T("OCPN_RTE_DEACTIVATED"))
{
m_activeRoute = false;
SetToolbarToolBitmaps(m_toolbar_item_id, _img_remembrancer_inactive, _img_remembrancer_inactive);
}
}
/*
InitAutopilotStatus
Make sure alerts don't show up until autopilot NMEA messages are parsed
Start reminder-check timer
*/
void remembrancer_pi::InitReminder()
{
if (m_timer.IsRunning())
{
m_timer.Stop();
m_timer.Disconnect(wxEVT_TIMER, wxTimerEventHandler(remembrancer_pi::OnTimer), NULL, this);
}
//Start Timer
wxString message;
message.Printf(wxT("REMEMBRANCER: Starting Timer at %d seconds per alarm"), m_reminderDelaySeconds);
wxLogMessage(message);
m_timer.Connect(wxEVT_TIMER, wxTimerEventHandler(remembrancer_pi::OnTimer), NULL, this);
m_timer.Start(m_reminderDelaySeconds * 1000);
}
/*
Method to return the bitmap for the toolbar
*/
wxBitmap *remembrancer_pi::GetPlugInBitmap()
{
return _img_remembrancer_inactive;
}
/*
Show Preferences
*/
void remembrancer_pi::OnToolbarToolCallback(int id)
{
ShowPropertiesWindow();
SetToolbarItemState(m_toolbar_item_id, false);
}
/*
Load Configuration Settings
*/
bool remembrancer_pi::LoadConfig(void)
{
wxFileConfig *pConf = m_pconfig;
if(!pConf)
{
wxLogMessage(_T("REMEMBRANCER: No configuration"));
return false;
}
pConf->SetPath ( _T( "/Settings/Remembrancer" ) );
pConf->Read ( _T( "AlertingEnabled" ), &m_alertingEnabled, 1 );
pConf->Read ( _T( "AlertingDelaySeconds" ), &m_reminderDelaySeconds, 60 );
pConf->Read ( _T( "SoundFile" ), &m_alertFileWav, _T("") );
return true;
}
/*
Method to Save user defined settings to the opencpn.conf settings file
*/
bool remembrancer_pi::SaveConfig(void)
{
wxFileConfig *pConf = m_pconfig;
if(pConf)
{
pConf->SetPath ( _T ( "/Settings/Remembrancer" ) );
pConf->Write ( _T ( "AlertingEnabled" ), m_alertingEnabled );
pConf->Write ( _T ( "AlertingDelaySeconds" ), m_reminderDelaySeconds );
pConf->Write ( _T ( "SoundFile" ), m_alertFileWav );
//Automatically write changes
pConf->Flush();
return true;
}
else
{
wxLogMessage(_T("REMEMBRANCER: No configuration"));
return false;
}
}
/*
Refresh icons
*/
void remembrancer_pi::ResetToolbarIcon()
{
RequestRefresh(m_parent_window);
}
/*
Method to play the alert sound for 1 second max
*/
void remembrancer_pi::PlayAlertSound()
{
if (m_alertFileWav.length()>0)
{
OCPN_Sound soundplayer;
soundplayer.Create(m_alertFileWav);
if(soundplayer.IsOk())
{
soundplayer.Play();
wxSleep(1);
if (soundplayer.IsPlaying())
{
soundplayer.Stop();
}
}
}
}
/*
Method to show the Properies window
*/
void remembrancer_pi::ShowPropertiesWindow()
{
if (!m_propertiesWindow)
{
wxLogMessage(m_alertFileWav);
m_propertiesWindow = new PropertyDialog(*this, m_parent_window);
m_propertiesWindow->m_txtDelay->SetValue(wxString::Format(_T("%d"), m_reminderDelaySeconds));
m_propertiesWindow->m_fipSoundFile->SetPath(m_alertFileWav);
m_propertiesWindow->m_ckEnabled->SetValue(m_alertingEnabled);
m_propertiesWindow->Update();
}
if (m_propertiesWindow->ShowModal() == wxID_OK)
{
m_alertFileWav = m_propertiesWindow->m_fipSoundFile->GetPath();
m_alertingEnabled = m_propertiesWindow->m_ckEnabled->GetValue();
m_reminderDelaySeconds = wxAtoi(m_propertiesWindow->m_txtDelay->GetValue());
SaveConfig();
m_propertiesWindow->Close();
//Restart Timer with new settings
InitReminder();
}
}
/*
Method to show the properties window from the plugins screen
*/
void remembrancer_pi::ShowPreferencesDialog( wxWindow* parent )
{
ShowPropertiesWindow();
}
//////////////////////////////////////
// Items Below are //
// Common to all plugins //
//////////////////////////////////////
int remembrancer_pi::GetAPIVersionMajor()
{
return MY_API_VERSION_MAJOR;
}
int remembrancer_pi::GetAPIVersionMinor()
{
return MY_API_VERSION_MINOR;
}
int remembrancer_pi::GetPlugInVersionMajor()
{
return PLUGIN_VERSION_MAJOR;
}
int remembrancer_pi::GetPlugInVersionMinor()
{
return PLUGIN_VERSION_MINOR;
}
wxString remembrancer_pi::GetCommonName()
{
return _("Remembrancer");
}
wxString remembrancer_pi::GetShortDescription()
{
return _("Remembrancer PlugIn for OpenCPN");
}
wxString remembrancer_pi::GetLongDescription()
{
return _("Remembrancer PlugIn for OpenCPN\n\rPlugIn that processes OCPN messages and displays an alert if a route is active (an autopilot is engaged).");
}
void remembrancer_pi::OnContextMenuItemCallback(int id)
{
wxLogMessage(_T("REMEMBRANCER: OnContextMenuCallBack()"));
::wxBell();
// Note carefully that this is a "reference to a wxAuiPaneInfo classs instance"
// Copy constructor (i.e. wxAuiPaneInfo pane = m_AUImgr->GetPane(m_pdemo_window);) will not work
wxAuiPaneInfo &pane = m_AUImgr->GetPane(m_alertWindow);
if(!pane.IsOk())
return;
if(!pane.IsShown())
{
SetCanvasContextMenuItemViz(m_hide_id, true);
SetCanvasContextMenuItemViz(m_show_id, false);
pane.Show(true);
m_AUImgr->Update();
}
else
{
SetCanvasContextMenuItemViz(m_hide_id, false);
SetCanvasContextMenuItemViz(m_show_id, true);
pane.Show(false);
m_AUImgr->Update();
}
}
void remembrancer_pi::UpdateAuiStatus(void)
{
// This method is called after the PlugIn is initialized
// and the frame has done its initial layout, possibly from a saved wxAuiManager "Perspective"
// It is a chance for the PlugIn to syncronize itself internally with the state of any Panes that
// were added to the frame in the PlugIn ctor.
// We use this callback here to keep the context menu selection in sync with the window state
printf("REMEMBRANCER: UpdateAuiStatus");
wxAuiPaneInfo &pane = m_AUImgr->GetPane(m_alertWindow);
if(!pane.IsOk())
return;
printf("update %d\n",pane.IsShown());
SetCanvasContextMenuItemViz(m_hide_id, pane.IsShown());
SetCanvasContextMenuItemViz(m_show_id, !pane.IsShown());
}
bool remembrancer_pi::RenderOverlay(wxDC &dc, PlugIn_ViewPort *vp)
{
return false;
}
void remembrancer_pi::SetCursorLatLon(double lat, double lon)
{
}
bool remembrancer_pi::RenderGLOverlay(wxGLContext *pcontext, PlugIn_ViewPort *vp)
{
return false;
}
int remembrancer_pi::GetToolbarToolCount(void)
{
return 1;
}
void remembrancer_pi::SetPositionFixEx(PlugIn_Position_Fix_Ex &pfix)
{
}
| gpl-2.0 |
AssociazionePrometeo/gianomanager | app/Policies/UserPolicy.php | 185 | <?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
class UserPolicy extends ModelPolicy
{
protected $model = 'user';
use HandlesAuthorization;
}
| gpl-2.0 |
hpfem/hermes3d | src/solver/amesos.cpp | 3159 | // This file is part of Hermes3D
//
// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Email: [email protected], home page: http://hpfem.org/.
//
// Hermes3D 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.
//
// Hermes3D 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 Hermes3D; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "../h3dconfig.h"
#include "amesos.h"
#include "../linear_problem.h"
#include <common/callstack.h>
#include <common/timer.h>
#ifdef HAVE_AMESOS
#include <Amesos_ConfigDefs.h>
#endif
#ifdef HAVE_AMESOS
Amesos AmesosSolver::factory;
#endif
// Amesos solver ///////////////////////////////////////////////////////////////////////////////////
AmesosSolver::AmesosSolver(const char *solver_type, EpetraMatrix *m, EpetraVector *rhs)
: LinearSolver(), m(m), rhs(rhs)
{
_F_
#ifdef HAVE_AMESOS
solver = factory.Create(solver_type, problem);
assert(solver != NULL);
#else
warning("hermes3d was not built with AMESOS support.");
exit(128);
#endif
}
AmesosSolver::AmesosSolver(const char *solver_type, LinearProblem *lp)
: LinearSolver(lp)
{
_F_
#ifdef HAVE_AMESOS
solver = factory.Create(solver_type, problem);
assert(solver != NULL);
m = new EpetraMatrix;
rhs = new EpetraVector;
#else
warning("hermes3d was not built with AMESOS support.");
exit(128);
#endif
}
AmesosSolver::~AmesosSolver()
{
_F_
#ifdef HAVE_AMESOS
if (lp != NULL) {
delete m;
delete rhs;
}
delete solver;
#endif
}
bool AmesosSolver::is_available(const char *name)
{
_F_
#ifdef HAVE_AMESOS
return factory.Query(name);
#else
return false;
#endif
}
void AmesosSolver::set_use_transpose(bool use_transpose)
{
_F_
#ifdef HAVE_AMESOS
solver->SetUseTranspose(use_transpose);
#endif
}
bool AmesosSolver::use_transpose()
{
_F_
#ifdef HAVE_AMESOS
return solver->UseTranspose();
#else
return false;
#endif
}
bool AmesosSolver::solve()
{
_F_
#ifdef HAVE_AMESOS
assert(m != NULL);
assert(rhs != NULL);
if (lp != NULL)
lp->assemble(m, rhs);
assert(m->size == rhs->size);
Timer tmr;
tmr.start();
Epetra_Vector x(*rhs->std_map);
problem.SetOperator(m->mat);
problem.SetRHS(rhs->vec);
problem.SetLHS(&x);
if ((error = solver->SymbolicFactorization()) != 0) return false;
if ((error = solver->NumericFactorization()) != 0) return false;
if ((error = solver->Solve()) != 0) return false;
tmr.stop();
time = tmr.get_seconds();
delete [] sln;
sln = new scalar[m->size]; MEM_CHECK(sln);
// copy the solution into sln vector
memset(sln, 0, m->size * sizeof(scalar));
for (int i = 0; i < m->size; i++) sln[i] = x[i];
return true;
#else
return false;
#endif
}
| gpl-2.0 |
wp-plugins/fs-social-comments | includes/class-fs-social-comments-deactivator.php | 665 | <?php
/**
* Fired during plugin deactivation
*
* @link http://www.lifeisfood.it/
* @since 1.0.0
*
* @package Fs_Social_Comments
* @subpackage Fs_Social_Comments/includes
*/
/**
* Fired during plugin deactivation.
*
* This class defines all code necessary to run during the plugin's deactivation.
*
* @since 1.0.0
* @package Fs_Social_Comments
* @subpackage Fs_Social_Comments/includes
* @author Fabio Sirchia <[email protected]>
*/
class Fs_Social_Comments_Deactivator {
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function deactivate() {
}
}
| gpl-2.0 |
asandroq/virtuality | src/virtuality/luascriptapi.cpp | 1574 | /*
*
* The Virtuality Renderer
* Copyright (C) 2001 Alex Sandro Queiroz e Silva
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* To contact the author send eletronic mail to [email protected]
*/
#include <scriptapi.hpp>
#include <luascriptapi.hpp>
namespace Virtuality {
namespace LuaScriptAPI {
void exportLuaScriptAPI(lua_State* L)
{
// geometric functions
lua_register(L, "reflect", reflect);
lua_register(L, "refract", refract);
lua_register(L, "faceforward", faceforward);
// shading functions
lua_register(L, "ambient", ambient);
lua_register(L, "diffuse", diffuse);
lua_register(L, "specular", specular);
}
int reflect(lua_State* L)
{
return 0;
}
int refract(lua_State* L)
{
return 0;
}
int faceforward(lua_State* L)
{
return 0;
}
int ambient(lua_State* L)
{
return 0;
}
int diffuse(lua_State* L)
{
return 0;
}
int specular(lua_State* L)
{
return 0;
}
}
}
| gpl-2.0 |
help3r/civcraft-1 | civcraft/src/com/avrgaming/civcraft/threading/tasks/PlayerLoginAsyncTask.java | 11403 | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.threading.tasks;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.avrgaming.anticheat.ACManager;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.endgame.EndConditionDiplomacy;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.exception.InvalidConfiguration;
import com.avrgaming.civcraft.exception.InvalidNameException;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivLog;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.CultureChunk;
import com.avrgaming.civcraft.object.Relation;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.sessiondb.SessionEntry;
import com.avrgaming.civcraft.threading.TaskMaster;
import com.avrgaming.civcraft.tutorial.CivTutorial;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.ChunkCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.war.War;
import com.avrgaming.global.perks.PlatinumManager;
public class PlayerLoginAsyncTask implements Runnable {
UUID playerUUID;
public PlayerLoginAsyncTask(UUID playerUUID) {
this.playerUUID = playerUUID;
}
public Player getPlayer() throws CivException {
return Bukkit.getPlayer(playerUUID);
}
@Override
public void run() {
try {
CivLog.info("Running PlayerLoginAsyncTask for "+getPlayer().getName()+" UUID("+playerUUID+")");
//Resident resident = CivGlobal.getResident(getPlayer().getName());
Resident resident = CivGlobal.getResidentViaUUID(playerUUID);
if (resident != null && !resident.getName().equals(getPlayer().getName()))
{
CivGlobal.removeResident(resident);
resident.setName(getPlayer().getName());
resident.save();
CivGlobal.addResident(resident);
}
/*
* Test to see if player has changed their name. If they have, these residents
* will not match. Disallow players changing their name without admin approval.
*/
if (CivGlobal.getResidentViaUUID(getPlayer().getUniqueId()) != resident) {
TaskMaster.syncTask(new PlayerKickBan(getPlayer().getName(), true, false,
"Your user ID on record does not match the player name you're attempting to log in with."+
"If you changed your name, please change it back or contact an admin to request a name change."));
return;
}
if (resident == null) {
CivLog.info("No resident found. Creating for "+getPlayer().getName());
try {
resident = new Resident(getPlayer().getUniqueId(), getPlayer().getName());
} catch (InvalidNameException e) {
TaskMaster.syncTask(new PlayerKickBan(getPlayer().getName(), true, false, "You have an invalid name. Sorry."));
return;
}
CivGlobal.addResident(resident);
CivLog.info("Added resident:"+resident.getName());
resident.setRegistered(System.currentTimeMillis());
CivTutorial.showTutorialInventory(getPlayer());
resident.setisProtected(true);
int mins;
try {
mins = CivSettings.getInteger(CivSettings.civConfig, "global.pvp_timer");
} catch (InvalidConfiguration e1) {
e1.printStackTrace();
return;
}
CivMessage.send(resident, CivColor.LightGray+"You have a PvP timer enabled for "+mins+" mins. You cannot attack or be attacked until it expires.");
CivMessage.send(resident, CivColor.LightGray+"To remove it, type /resident pvptimer");
}
/*
* Resident is present. Lets check the UUID against the stored UUID.
* We are not going to allow residents to change names without admin permission.
* If someone logs in with a name that does not match the stored UUID, we'll kick them.
*/
if (resident.getUUID() == null) {
/* This resident does not yet have a UUID stored. Free lunch. */
resident.setUUID(getPlayer().getUniqueId());
CivLog.info("Resident named:"+resident.getName()+" was acquired by UUID:"+resident.getUUIDString());
} else if (!resident.getUUID().equals(getPlayer().getUniqueId())) {
TaskMaster.syncTask(new PlayerKickBan(getPlayer().getName(), true, false,
"You're attempting to log in with a name already in use. Please change your name."));
return;
}
if (!resident.isGivenKit()) {
TaskMaster.syncTask(new GivePlayerStartingKit(resident.getName()));
}
if (War.isWarTime() && War.isOnlyWarriors()) {
if (getPlayer().isOp() || getPlayer().hasPermission(CivSettings.MINI_ADMIN)) {
//Allowed to connect since player is OP or mini admin.
} else if (!resident.hasTown() || !resident.getTown().getCiv().getDiplomacyManager().isAtWar()) {
TaskMaster.syncTask(new PlayerKickBan(getPlayer().getName(), true, false, "Only players in civilizations at war can connect right now. Sorry."));
return;
}
}
/* turn on allchat by default for admins and moderators. */
if (getPlayer().hasPermission(CivSettings.MODERATOR) || getPlayer().hasPermission(CivSettings.MINI_ADMIN)) {
resident.allchat = true;
Resident.allchatters.add(resident.getName());
}
if (resident.getTreasury().inDebt()) {
TaskMaster.asyncTask("", new PlayerDelayedDebtWarning(resident), 1000);
}
if (!getPlayer().isOp()) {
CultureChunk cc = CivGlobal.getCultureChunk(new ChunkCoord(getPlayer().getLocation()));
if (cc != null && cc.getCiv() != resident.getCiv()) {
Relation.Status status = cc.getCiv().getDiplomacyManager().getRelationStatus(getPlayer());
String color = PlayerChunkNotifyAsyncTask.getNotifyColor(cc, status, getPlayer());
String relationName = status.name();
if (War.isWarTime() && status.equals(Relation.Status.WAR)) {
/*
* Test for players who were not logged in when war time started.
* If they were not logged in, they are enemies, and are inside our borders
* they need to be teleported back to their own town hall.
*/
if (resident.getLastOnline() < War.getStart().getTime()) {
resident.teleportHome();
CivMessage.send(resident, CivColor.LightGray+"You've been teleported back to your home since you've logged into enemy during WarTime.");
}
}
CivMessage.sendCiv(cc.getCiv(), color+getPlayer().getDisplayName()+"("+relationName+") has logged-in to our borders.");
}
}
resident.setLastOnline(System.currentTimeMillis());
resident.setLastIP(getPlayer().getAddress().getAddress().getHostAddress());
resident.setSpyExposure(resident.getSpyExposure());
resident.save();
//TODO send town board messages?
//TODO set default modes?
resident.showWarnings(getPlayer());
resident.loadPerks();
try {
String perkMessage = "";
if (CivSettings.getString(CivSettings.perkConfig, "system.free_perks").equalsIgnoreCase("true")) {
resident.giveAllFreePerks();
perkMessage = "You have access to the Following Perks: ";
} else if (CivSettings.getString(CivSettings.perkConfig, "system.free_admin_perks").equalsIgnoreCase("true")) {
if (getPlayer().hasPermission(CivSettings.MINI_ADMIN) || getPlayer().hasPermission(CivSettings.FREE_PERKS)) {
resident.giveAllFreePerks();
perkMessage = "You have access to the Following Perks: ";
perkMessage += "Weather, Name Change, ";
}
}
if (getPlayer().hasPermission(CivSettings.ARCTIC_PERKS))
{
resident.giveAllArcticPerks();
perkMessage += "Arctic, ";
}
if (getPlayer().hasPermission(CivSettings.AZTEC_PERKS))
{
resident.giveAllAztecPerks();
perkMessage += "Aztec, ";
}
if (getPlayer().hasPermission(CivSettings.EGYPTIAN_PERKS))
{
resident.giveAllEgyptianPerks();
perkMessage += "Egyptian, ";
}
if (getPlayer().hasPermission(CivSettings.HELL_PERKS))
{
resident.giveAllHellPerks();
perkMessage += "Hell, ";
}
if (getPlayer().hasPermission(CivSettings.ROMAN_PERKS))
{
resident.giveAllRomanPerks();
perkMessage += "Roman, ";
}
perkMessage += "Apply them with /res perks";
CivMessage.send(resident, CivColor.LightGreen+perkMessage);
} catch (InvalidConfiguration e) {
e.printStackTrace();
}
/* Send Anti-Cheat challenge to player. */
if (!getPlayer().hasPermission("civ.ac_valid")) {
resident.setUsesAntiCheat(false);
ACManager.sendChallenge(getPlayer());
} else {
resident.setUsesAntiCheat(true);
}
// Check for pending respawns.
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup("global:respawnPlayer");
ArrayList<SessionEntry> deleted = new ArrayList<SessionEntry>();
for (SessionEntry e : entries) {
String[] split = e.value.split(":");
BlockCoord coord = new BlockCoord(split[1]);
getPlayer().teleport(coord.getLocation());
deleted.add(e);
}
for (SessionEntry e : deleted) {
CivGlobal.getSessionDB().delete(e.request_id, "global:respawnPlayer");
}
try {
Player p = CivGlobal.getPlayer(resident);
PlatinumManager.givePlatinumDaily(resident,
CivSettings.platinumRewards.get("loginDaily").name,
CivSettings.platinumRewards.get("loginDaily").amount,
"Welcome back to CivCraft! Here is %d for logging in today!" );
ArrayList<SessionEntry> deathEvents = CivGlobal.getSessionDB().lookup("pvplogger:death:"+resident.getName());
if (deathEvents.size() != 0) {
CivMessage.send(resident, CivColor.Rose+CivColor.BOLD+"You were killed while offline because you logged out while in PvP!");
class SyncTask implements Runnable {
String playerName;
public SyncTask(String playerName) {
this.playerName = playerName;
}
@Override
public void run() {
Player p;
try {
p = CivGlobal.getPlayer(playerName);
p.setHealth(0);
CivGlobal.getSessionDB().delete_all("pvplogger:death:"+p.getName());
} catch (CivException e) {
// You cant excape death that easily!
}
}
}
TaskMaster.syncTask(new SyncTask(p.getName()));
}
} catch (CivException e1) {
//try really hard not to give offline players who were kicked platinum.
}
if (EndConditionDiplomacy.canPeopleVote()) {
CivMessage.send(resident, CivColor.LightGreen+"The Council of Eight is built! Use /vote to vote for your favorite Civilization!");
}
} catch (CivException playerNotFound) {
// Player logged out while async task was running.
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| gpl-2.0 |
icteidon/RQ | administrator/components/com_advancedmodules/views/module/tmpl/edit_assignment.php | 4463 | <?php
/**
* @package Advanced Module Manager
* @version 3.1.0
*
* @author Peter van Westen <[email protected]>
* @link http://www.nonumber.nl
* @copyright Copyright © 2012 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/**
* @package Joomla.Administrator
* @subpackage com_advancedmodules
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
jimport('joomla.filesystem.file');
$lang = JFactory::getLanguage();
if ($lang->getTag() != 'en-GB') {
// Loads English language file as fallback (for undefined stuff in other language file)
$lang->load('com_advancedmodules', JPATH_ADMINISTRATOR, 'en-GB');
}
$lang->load('com_advancedmodules', JPATH_ADMINISTRATOR, null, 1);
$html = array();
$html[] = JHtml::_('sliders.panel', JText::_('AMM_MODULE_ASSIGNMENT'), 'assignment-options');
$html[] = '<fieldset class="panelform">';
$html[] = '<ul class="adminformlist">';
if ($this->config->show_mirror_module) {
$html[] = $this->render($this->assignments, 'mirror_module');
$html[] = '</ul>';
$html[] = '<div style="clear: both;"></div>';
$html[] = '<div id="'.rand(1000000, 9999999).'___mirror_module.0" class="nntoggler">';
$html[] = '<ul class="adminformlist">';
}
if ($this->config->show_match_method
&& ($this->config->show_assignto_content
|| $this->config->show_assignto_components
|| $this->config->show_assignto_urls
|| $this->config->show_assignto_browser
|| $this->config->show_assignto_date
|| $this->config->show_assignto_usergrouplevels
|| $this->config->show_assignto_languages
|| $this->config->show_assignto_templates
)
) {
if ($this->config->show_match_method) {
$html[] = $this->render($this->assignments, 'match_method');
}
}
if ($this->config->show_show_ignores) {
$str = $this->render($this->assignments, 'show_ignores');
$def_val = $this->config->show_ignores ? '2' : '-1';
$def_text = $this->config->show_ignores ? JText::_('JSHOW') : JText::_('JHIDE');
$html[] = preg_replace('#(<input [^>]*id="advancedparams_show_ignores2"[^>]*value=)"2"([^>]*/>.*?)(</label>)#si', '\1"'.$def_val.'"\2 ('.$def_text.')\3', $str);
} else
{
$html[] = '<input type="hidden" name="show_ignores" value="1" />';
}
$html[] = $this->render($this->assignments, 'assignto_menuitems');
if ($this->config->show_assignto_homepage) {
$html[] = $this->render($this->assignments, 'assignto_homepage');
}
if ($this->config->show_assignto_content) {
$html[] = $this->render($this->assignments, 'assignto_content');
}
if ($this->config->show_assignto_components) {
$html[] = $this->render($this->assignments, 'assignto_components');
}
if ($this->config->show_assignto_urls) {
$configuration = JFactory::getConfig();
$use_sef = ($this->config->use_sef == 2) ? $configuration->getValue('config.sef') == 1 : $this->config->use_sef;
$html[] = '<input type="hidden" name="use_sef" value="'.(int) $use_sef.'" />';
$html[] = $this->render($this->assignments, 'assignto_urls');
}
if ($this->config->show_assignto_browsers) {
$html[] = $this->render($this->assignments, 'assignto_browsers');
}
if ($this->config->show_assignto_date) {
$html[] = $this->render($this->assignments, 'assignto_date');
}
$html[] = $this->render($this->assignments, 'assignto_users_open');
$html[] = '
<div class="panel nn_panel nn_panel_title nn_panel_top">
<div class="nn_block nn_title">
'.JText::_('NN_ACCESS_LEVELS').'
<div style="clear: both;"></div>
</div>
</div>
<div class="panel nn_panel">
<div class="nn_block">
<ul class="adminformlist">
<li>
'.$this->form->getLabel('access').'
<fieldset class="radio">
'.$this->form->getInput('access').'
</fieldset>
</li>
</ul>
<div style="clear: both;"></div>
</div>
</div>';
if ($this->config->show_assignto_usergrouplevels) {
$html[] = $this->render($this->assignments, 'assignto_usergrouplevels');
}
$html[] = $this->render($this->assignments, 'assignto_users_close');
if ($this->config->show_assignto_languages) {
$html[] = $this->render($this->assignments, 'assignto_languages');
}
if ($this->config->show_assignto_templates) {
$html[] = $this->render($this->assignments, 'assignto_templates');
}
if ($this->config->show_mirror_module) {
$html[] = '</div>';
}
$html[] = '</ul>';
$html[] = '</fieldset>';
echo implode("\n\n", $html); | gpl-2.0 |
dhardy/openmalaria | model/Transmission/NonVector.cpp | 7376 | /*
This file is part of OpenMalaria.
Copyright (C) 2005-2009 Swiss Tropical Institute and Liverpool School Of Tropical Medicine
OpenMalaria is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Transmission/NonVector.h"
#include "Transmission/PerHostTransmission.h"
#include "inputData.h"
#include "util/random.h"
#include "Surveys.h" // sim-end timestep
#include <cfloat>
namespace OM { namespace Transmission {
//static (class) variables
const double NonVectorTransmission::totalInfectionrateVariance= 1.0;
const double NonVectorTransmission::min_EIR_mult= 0.01;
NonVectorTransmission::NonVectorTransmission(const scnXml::NonVector& nonVectorData)
{
nspore = nonVectorData.getEipDuration() / Global::interval;
initialKappa.resize (Global::intervalsPerYear);
vector<int> nDays (Global::intervalsPerYear, 0);
initialisationEIR.assign (Global::intervalsPerYear, 0.0);
//The minimum EIR allowed in the array. The product of the average EIR and a constant.
double minEIR=min_EIR_mult*averageEIR(nonVectorData);
const scnXml::NonVector::EIRDailySequence& daily = nonVectorData.getEIRDaily();
for (size_t mpcday = 0; mpcday < daily.size(); ++mpcday) {
double EIRdaily = std::max((double)daily[mpcday], minEIR);
// istep is the time period to which the day is assigned. The result of the
// division is automatically rounded down to the next integer.
size_t i1 = (mpcday / Global::interval) % Global::intervalsPerYear;
//EIR() is the sum of the EIRs assigned to the 73 different recurring time points
nDays[i1]++;
initialisationEIR[i1] += EIRdaily;
}
// Calculate total annual EIR
// divide by number of records assigned to each interval (usually one per day)
for (size_t j=0;j<Global::intervalsPerYear; j++) {
initialisationEIR[j] *= Global::interval / (double)nDays[j];
annualEIR += initialisationEIR[j];
}
}
NonVectorTransmission::~NonVectorTransmission () {}
//! initialise the main simulation
void NonVectorTransmission::initMainSimulation (){
// initialKappa is used in calculateEIR
initialKappa = kappa;
// error check:
for (size_t i = 0; i < initialKappa.size(); ++i) {
if (!(initialKappa[i] > 0.0)) // if not positive
throw runtime_error ("initialKappa is invalid");
}
simulationMode = InputData().getEntoData().getMode();
if (simulationMode < 2 || simulationMode > 4)
throw util::xml_scenario_error("mode attribute has invalid value (expected: 2, 3 or 4)");
}
void NonVectorTransmission::setTransientEIR (const scnXml::NonVector& nonVectorData) {
// Note: requires Global::timeStep >= 0, but this can only be called in intervention period anyway.
simulationMode = transientEIRknown;
if (nspore != nonVectorData.getEipDuration() / Global::interval)
throw util::xml_scenario_error ("change-of-EIR intervention cannot change EIP duration");
const scnXml::NonVector::EIRDailySequence& daily = nonVectorData.getEIRDaily();
vector<int> nDays ((daily.size()-1)/Global::interval + 1, 0);
interventionEIR.assign (nDays.size(), 0.0);
if (static_cast<int>(nDays.size()) < Surveys.getFinalTimestep()+1) {
cerr << "Days: " << daily.size() << "\nIntervals: " << nDays.size() << "\nRequired: " << Surveys.getFinalTimestep()+1 << endl;
throw util::xml_scenario_error ("Insufficient intervention phase EIR values provided");
}
//The minimum EIR allowed in the array. The product of the average EIR and a constant.
double minEIR=min_EIR_mult*averageEIR(nonVectorData);
for (size_t mpcday = 0; mpcday < daily.size(); ++mpcday) {
double EIRdaily = std::max((double)daily[mpcday], minEIR);
// istep is the time period to which the day is assigned. The result of the
// division is automatically rounded down to the next integer.
size_t istep = mpcday / Global::interval;
nDays[istep]++;
interventionEIR[istep] += EIRdaily;
}
// divide by number of records assigned to each interval (usually one per day)
for (size_t i = 0; i < interventionEIR.size(); ++i)
interventionEIR[i] *= Global::interval / nDays[i];
annualEIR=0.0;
}
void NonVectorTransmission::changeEIRIntervention (const scnXml::NonVector& ed) {
setTransientEIR (ed);
}
double NonVectorTransmission::calculateEIR(int simulationTime, PerHostTransmission& perHost, double ageInYears){
// where the full model, with estimates of human mosquito transmission is in use, use this:
double eir;
switch (simulationMode) {
case equilibriumMode:
eir = initialisationEIR[(simulationTime-1) % Global::intervalsPerYear];
break;
case transientEIRknown:
// where the EIR for the intervention phase is known, obtain this from
// the interventionEIR array
eir = interventionEIR[Global::timeStep];
break;
case dynamicEIR:
eir = initialisationEIR[(simulationTime-1) % Global::intervalsPerYear];
if (Global::timeStep >= 0) {
// we modulate the initialization based on the human infectiousness nspore timesteps ago in the
// simulation relative to infectiousness at the same time-of-year, pre-intervention.
// nspore gives the sporozoite development delay.
eir *=
kappa[(simulationTime-nspore-1) % Global::intervalsPerYear] /
initialKappa[(simulationTime-nspore-1) % Global::intervalsPerYear];
}
break;
default: // Anything else.. don't continue silently
throw util::xml_scenario_error ("Invalid simulation mode");
}
#ifndef NDEBUG
if (!finite(eir)) {
ostringstream msg;
msg << "Error: non-vect eir is: " << eir
<< "\nkappa:\t" << kappa[(simulationTime-nspore-1) % Global::intervalsPerYear]
<< "\ninitialKappa:\t" << initialKappa[(simulationTime-nspore-1) % Global::intervalsPerYear] << endl;
throw overflow_error(msg.str());
}
#endif
return eir * perHost.relativeAvailabilityHetAge (ageInYears);
}
// ----- Private functs ------
double NonVectorTransmission::averageEIR (const scnXml::NonVector& nonVectorData) {
// Calculates the arithmetic mean of the whole daily EIR vector read from the .XML file
double valaverageEIR=0.0;
size_t i = 0;
for (const scnXml::NonVector::EIRDailySequence& daily = nonVectorData.getEIRDaily();
i < daily.size(); ++i) {
valaverageEIR += (double)daily[i];
}
return valaverageEIR / i;
}
// ----- checkpointing -----
void NonVectorTransmission::checkpoint (istream& stream) {
TransmissionModel::checkpoint (stream);
nspore & stream;
interventionEIR & stream;
initialKappa & stream;
}
void NonVectorTransmission::checkpoint (ostream& stream) {
TransmissionModel::checkpoint (stream);
nspore & stream;
interventionEIR & stream;
initialKappa & stream;
}
} }
| gpl-2.0 |
wshearn/openshift-quickstart-modx | php/core/model/modx/mysql/modresourcegroupresource.map.inc.php | 1861 | <?php
/**
* @package modx
* @subpackage mysql
*/
$xpdo_meta_map['modResourceGroupResource']= array (
'package' => 'modx',
'version' => '1.1',
'table' => 'document_groups',
'extends' => 'xPDOSimpleObject',
'fields' =>
array (
'document_group' => 0,
'document' => 0,
),
'fieldMeta' =>
array (
'document_group' =>
array (
'dbtype' => 'int',
'precision' => '10',
'phptype' => 'integer',
'null' => false,
'default' => 0,
'index' => 'index',
),
'document' =>
array (
'dbtype' => 'int',
'precision' => '10',
'phptype' => 'integer',
'null' => false,
'default' => 0,
'index' => 'index',
),
),
'indexes' =>
array (
'document_group' =>
array (
'alias' => 'document_group',
'primary' => false,
'unique' => false,
'type' => 'BTREE',
'columns' =>
array (
'document_group' =>
array (
'length' => '',
'collation' => 'A',
'null' => false,
),
),
),
'document' =>
array (
'alias' => 'document',
'primary' => false,
'unique' => false,
'type' => 'BTREE',
'columns' =>
array (
'document' =>
array (
'length' => '',
'collation' => 'A',
'null' => false,
),
),
),
),
'aggregates' =>
array (
'ResourceGroup' =>
array (
'class' => 'modResourceGroup',
'key' => 'id',
'local' => 'document_group',
'foreign' => 'id',
'cardinality' => 'one',
'owner' => 'foreign',
),
'Resource' =>
array (
'class' => 'modResource',
'key' => 'id',
'local' => 'document',
'foreign' => 'id',
'cardinality' => 'one',
'owner' => 'foreign',
),
),
);
| gpl-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.