code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* App Control
*
* Central controller attached to the top level <html>
* element
*/
"use strict";
( function ( angular, app ) {
// get user profile data
app.controller( "AppCtrl", [ '$rootScope', '$scope', '$state', 'UserService',
function ( $rootScope, $scope, $state, UserService ) {
//
// bodyClass definitions
//
// in a larger project this would be abstracted to allow for multiple
// classes to easily be added or removed
//
// current state
$rootScope.$on( '$stateChangeStart',
function ( event, toState, toParams, fromState, fromParams ) {
var currentState = toState.name.replace( '.', '-' );
$scope.bodyClass = 'state-' + currentState;
}
);
/**
* Format Avatar
*/
$scope.currentUserAvatar = function ( src, size ) {
return UserService.getCurrentUserAvatar( size );
};
}
] );
} )( angular, SimplySocial ); | Kevinlearynet/angular-trial-app | scripts/controllers/app-controller.js | JavaScript | gpl-2.0 | 901 |
package org.openzal.zal.ldap;
import javax.annotation.Nonnull;
public class LdapServerType
{
@Nonnull
private final com.zimbra.cs.ldap.LdapServerType mLdapServerType;
public final static LdapServerType MASTER = new LdapServerType(com.zimbra.cs.ldap.LdapServerType.MASTER);
public final static LdapServerType REPLICA = new LdapServerType(com.zimbra.cs.ldap.LdapServerType.REPLICA);
public LdapServerType(@Nonnull Object ldapServerType)
{
mLdapServerType = (com.zimbra.cs.ldap.LdapServerType)ldapServerType;
}
protected <T> T toZimbra(Class<T> cls)
{
return cls.cast(mLdapServerType);
}
public boolean isMaster() {
return mLdapServerType.isMaster();
}
}
| ZeXtras/OpenZAL | src/java/org/openzal/zal/ldap/LdapServerType.java | Java | gpl-2.0 | 694 |
'use strict';
/**
* @ngdoc function
* @name quickNewsApp.controller:CbcCtrl
* @description
* # CbcCtrl
* Controller of the quickNewsApp
*/
angular.module('quickNewsApp')
.controller('CbcCtrl', function ($scope, $http) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.postLimit = 10;
$scope.showMorePosts = function() {
$scope.postLimit += 5;
};
$scope.isSet = function(checkTab) {
return this.tab === checkTab;
};
$scope.setTab = function(activeTab) {
this.tab = activeTab;
$scope.postLimit = 10;
$scope.getFeed(activeTab);
};
$scope.getActiveTab = function() {
return this.tab;
};
$scope.getFeed = function(category) {
/*jshint unused: false */
$scope.loading = true;
var url = '//quicknews.amanuppal.ca:5000/cbc?url=' + category;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.entries = data.items;
console.log($scope.entries);
$scope.numEntries = Object.keys($scope.entries).length;
$scope.loading = false;
})
.error(function(data, status, headers, config) {
console.log('Error loading feed: ' + url + ', status: ' + status);
});
};
});
| amtux/quick-news | app/scripts/controllers/cbc.js | JavaScript | gpl-2.0 | 1,204 |
package org.hectordam.proyectohector;
import java.util.ArrayList;
import org.hectordam.proyectohector.R;
import org.hectordam.proyectohector.base.Bar;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class Mapa extends FragmentActivity implements LocationListener,ConnectionCallbacks, OnConnectionFailedListener{
private GoogleMap mapa;
private LocationClient locationClient;
private CameraUpdate camara;
private static final LocationRequest LOC_REQUEST = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(16)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapa);
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
mapa = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
ArrayList<Bar> bares = getIntent().getParcelableArrayListExtra("bares");
if (bares != null) {
//marcarBares(bares);
}
mapa.setMyLocationEnabled(true);
configuraLocalizador();
camara = CameraUpdateFactory.newLatLng(new LatLng(41.6561, -0.8773));
mapa.moveCamera(camara);
mapa.animateCamera(CameraUpdateFactory.zoomTo(11.0f), 2000, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mapa, menu);
return true;
}
/**
* Añade las marcas de todas las gasolineras
* @param gasolineras
*/
private void marcarBares(ArrayList<Bar> bares) {
if (bares.size() > 0) {
for (Bar bar : bares) {
mapa.addMarker(new MarkerOptions()
.position(new LatLng(bar.getLatitud(), bar.getLongitud()))
.title(bar.getNombre()));
}
}
}
/**
* Se muestra la Activity
*/
@Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
@Override
protected void onStop() {
super.onStop();
locationClient.disconnect();
}
private void configuraLocalizador() {
if (locationClient == null) {
locationClient = new LocationClient(this, this, this);
}
}
@Override
public void onConnected(Bundle arg0) {
locationClient.requestLocationUpdates(LOC_REQUEST, this);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onDisconnected() {
}
@Override
public void onLocationChanged(Location arg0) {
}
}
| gilmh/PracticaAndroid | AgenBar/src/org/hectordam/proyectohector/Mapa.java | Java | gpl-2.0 | 3,630 |
/* $Id$ */
/*
Copyright (C) 2003 - 2013 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
#ifndef VIDEO_HPP_INCLUDED
#define VIDEO_HPP_INCLUDED
#include "events.hpp"
#include "exceptions.hpp"
#include "lua_jailbreak_exception.hpp"
#include <boost/utility.hpp>
struct surface;
//possible flags when setting video modes
#define FULL_SCREEN SDL_FULLSCREEN
surface display_format_alpha(surface surf);
surface get_video_surface();
SDL_Rect screen_area();
bool non_interactive();
//which areas of the screen will be updated when the buffer is flipped?
void update_rect(size_t x, size_t y, size_t w, size_t h);
void update_rect(const SDL_Rect& rect);
void update_whole_screen();
class CVideo : private boost::noncopyable {
public:
enum FAKE_TYPES {
NO_FAKE,
FAKE,
FAKE_TEST
};
CVideo(FAKE_TYPES type = NO_FAKE);
~CVideo();
int bppForMode( int x, int y, int flags);
int modePossible( int x, int y, int bits_per_pixel, int flags, bool current_screen_optimal=false);
int setMode( int x, int y, int bits_per_pixel, int flags );
//did the mode change, since the last call to the modeChanged() method?
bool modeChanged();
//functions to get the dimensions of the current video-mode
int getx() const;
int gety() const;
//blits a surface with black as alpha
void blit_surface(int x, int y, surface surf, SDL_Rect* srcrect=NULL, SDL_Rect* clip_rect=NULL);
void flip();
surface& getSurface();
bool isFullScreen() const;
struct error : public game::error
{
error() : game::error("Video initialization failed") {}
};
class quit
: public tlua_jailbreak_exception
{
public:
quit()
: tlua_jailbreak_exception()
{
}
private:
IMPLEMENT_LUA_JAILBREAK_EXCEPTION(quit)
};
//functions to allow changing video modes when 16BPP is emulated
void setBpp( int bpp );
int getBpp();
void make_fake();
/**
* Creates a fake frame buffer for the unit tests.
*
* @param width The width of the buffer.
* @param height The height of the buffer.
* @param bpp The bpp of the buffer.
*/
void make_test_fake(const unsigned width = 1024,
const unsigned height = 768, const unsigned bpp = 32);
bool faked() const { return fake_screen_; }
//functions to set and clear 'help strings'. A 'help string' is like a tooltip, but it appears
//at the bottom of the screen, so as to not be intrusive. Setting a help string sets what
//is currently displayed there.
int set_help_string(const std::string& str);
void clear_help_string(int handle);
void clear_all_help_strings();
//function to stop the screen being redrawn. Anything that happens while
//the update is locked will be hidden from the user's view.
//note that this function is re-entrant, meaning that if lock_updates(true)
//is called twice, lock_updates(false) must be called twice to unlock
//updates.
void lock_updates(bool value);
bool update_locked() const;
private:
void initSDL();
bool mode_changed_;
int bpp_; // Store real bits per pixel
//if there is no display at all, but we 'fake' it for clients
bool fake_screen_;
//variables for help strings
int help_string_;
int updatesLocked_;
};
//an object which will lock the display for the duration of its lifetime.
struct update_locker
{
update_locker(CVideo& v, bool lock=true) : video(v), unlock(lock) {
if(lock) {
video.lock_updates(true);
}
}
~update_locker() {
unlock_update();
}
void unlock_update() {
if(unlock) {
video.lock_updates(false);
unlock = false;
}
}
private:
CVideo& video;
bool unlock;
};
class resize_monitor : public events::pump_monitor {
void process(events::pump_info &info);
};
//an object which prevents resizing of the screen occurring during
//its lifetime.
struct resize_lock {
resize_lock();
~resize_lock();
};
#endif
| battle-for-wesnoth/svn | src/video.hpp | C++ | gpl-2.0 | 4,277 |
<?php
namespace Bookly\Backend;
use Bookly\Backend\Modules;
use Bookly\Frontend;
use Bookly\Lib;
/**
* Class Backend
* @package Bookly\Backend
*/
class Backend
{
public function __construct()
{
// Backend controllers.
$this->apearanceController = Modules\Appearance\Controller::getInstance();
$this->calendarController = Modules\Calendar\Controller::getInstance();
$this->customerController = Modules\Customers\Controller::getInstance();
$this->notificationsController = Modules\Notifications\Controller::getInstance();
$this->paymentController = Modules\Payments\Controller::getInstance();
$this->serviceController = Modules\Services\Controller::getInstance();
$this->smsController = Modules\Sms\Controller::getInstance();
$this->settingsController = Modules\Settings\Controller::getInstance();
$this->staffController = Modules\Staff\Controller::getInstance();
$this->couponsController = Modules\Coupons\Controller::getInstance();
$this->customFieldsController = Modules\CustomFields\Controller::getInstance();
$this->appointmentsController = Modules\Appointments\Controller::getInstance();
$this->debugController = Modules\Debug\Controller::getInstance();
// Frontend controllers that work via admin-ajax.php.
$this->bookingController = Frontend\Modules\Booking\Controller::getInstance();
$this->customerProfileController = Frontend\Modules\CustomerProfile\Controller::getInstance();
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_AUTHORIZENET ) ) {
$this->authorizeNetController = Frontend\Modules\AuthorizeNet\Controller::getInstance();
}
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_PAYULATAM ) ) {
$this->payulatamController = Frontend\Modules\PayuLatam\Controller::getInstance();
}
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_STRIPE ) ) {
$this->stripeController = Frontend\Modules\Stripe\Controller::getInstance();
}
$this->wooCommerceController = Frontend\Modules\WooCommerce\Controller::getInstance();
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
add_action( 'wp_loaded', array( $this, 'init' ) );
add_action( 'admin_init', array( $this, 'addTinyMCEPlugin' ) );
}
public function init()
{
if ( ! session_id() ) {
@session_start();
}
}
public function addTinyMCEPlugin()
{
new Modules\TinyMce\Plugin();
}
public function addAdminMenu()
{
/** @var \WP_User $current_user */
global $current_user;
// Translated submenu pages.
$calendar = __( 'Calendar', 'bookly' );
$appointments = __( 'Appointments', 'bookly' );
$staff_members = __( 'Staff Members', 'bookly' );
$services = __( 'Services', 'bookly' );
$sms = __( 'SMS Notifications', 'bookly' );
$notifications = __( 'Email Notifications', 'bookly' );
$customers = __( 'Customers', 'bookly' );
$payments = __( 'Payments', 'bookly' );
$appearance = __( 'Appearance', 'bookly' );
$settings = __( 'Settings', 'bookly' );
$coupons = __( 'Coupons', 'bookly' );
$custom_fields = __( 'Custom Fields', 'bookly' );
if ( $current_user->has_cap( 'administrator' ) || Lib\Entities\Staff::query()->where( 'wp_user_id', $current_user->ID )->count() ) {
if ( function_exists( 'add_options_page' ) ) {
$dynamic_position = '80.0000001' . mt_rand( 1, 1000 ); // position always is under `Settings`
add_menu_page( 'Bookly', 'Bookly', 'read', 'ab-system', '',
plugins_url( 'resources/images/menu.png', __FILE__ ), $dynamic_position );
add_submenu_page( 'ab-system', $calendar, $calendar, 'read', 'ab-calendar',
array( $this->calendarController, 'index' ) );
add_submenu_page( 'ab-system', $appointments, $appointments, 'manage_options', 'ab-appointments',
array( $this->appointmentsController, 'index' ) );
do_action( 'bookly_render_menu_after_appointments' );
if ( $current_user->has_cap( 'administrator' ) ) {
add_submenu_page( 'ab-system', $staff_members, $staff_members, 'manage_options', Modules\Staff\Controller::page_slug,
array( $this->staffController, 'index' ) );
} else {
if ( get_option( 'ab_settings_allow_staff_members_edit_profile' ) == 1 ) {
add_submenu_page( 'ab-system', __( 'Profile', 'bookly' ), __( 'Profile', 'bookly' ), 'read', Modules\Staff\Controller::page_slug,
array( $this->staffController, 'index' ) );
}
}
add_submenu_page( 'ab-system', $services, $services, 'manage_options', Modules\Services\Controller::page_slug,
array( $this->serviceController, 'index' ) );
add_submenu_page( 'ab-system', $customers, $customers, 'manage_options', Modules\Customers\Controller::page_slug,
array( $this->customerController, 'index' ) );
add_submenu_page( 'ab-system', $notifications, $notifications, 'manage_options', 'ab-notifications',
array( $this->notificationsController, 'index' ) );
add_submenu_page( 'ab-system', $sms, $sms, 'manage_options', Modules\Sms\Controller::page_slug,
array( $this->smsController, 'index' ) );
add_submenu_page( 'ab-system', $payments, $payments, 'manage_options', 'ab-payments',
array( $this->paymentController, 'index' ) );
add_submenu_page( 'ab-system', $appearance, $appearance, 'manage_options', 'ab-appearance',
array( $this->apearanceController, 'index' ) );
add_submenu_page( 'ab-system', $custom_fields, $custom_fields, 'manage_options', 'ab-custom-fields',
array( $this->customFieldsController, 'index' ) );
add_submenu_page( 'ab-system', $coupons, $coupons, 'manage_options', 'ab-coupons',
array( $this->couponsController, 'index' ) );
add_submenu_page( 'ab-system', $settings, $settings, 'manage_options', Modules\Settings\Controller::page_slug,
array( $this->settingsController, 'index' ) );
if ( isset ( $_GET['page'] ) && $_GET['page'] == 'ab-debug' ) {
add_submenu_page( 'ab-system', 'Debug', 'Debug', 'manage_options', 'ab-debug',
array( $this->debugController, 'index' ) );
}
global $submenu;
do_action( 'bookly_admin_menu', 'ab-system' );
unset ( $submenu['ab-system'][0] );
}
}
}
} | Tjdowdell/Susan_Batchelor_Website | wp-content/plugins/appointment-booking/backend/Backend.php | PHP | gpl-2.0 | 7,231 |
## See "d_bankfull" in update_flow_depth() ######## (2/21/13)
## See "(5/13/10)" for a temporary fix.
#------------------------------------------------------------------------
# Copyright (c) 2001-2014, Scott D. Peckham
#
# Sep 2014. Wrote new update_diversions().
# New standard names and BMI updates and testing.
# Nov 2013. Converted TopoFlow to a Python package.
# Feb 2013. Adapted to use EMELI framework.
# Jan 2013. Shared scalar doubles are now 0D numpy arrays.
# This makes them mutable and allows components with
# a reference to them to see them change.
# So far: Q_outlet, Q_peak, Q_min...
# Jan 2013. Revised handling of input/output names.
# Oct 2012. CSDMS Standard Names and BMI.
# May 2012. Commented out diversions.update() for now. #######
# May 2012. Shared scalar doubles are now 1-element 1D numpy arrays.
# This makes them mutable and allows components with
# a reference to them to see them change.
# So far: Q_outlet, Q_peak, Q_min...
# May 2010. Changes to initialize() and read_cfg_file()
# Mar 2010. Changed codes to code, widths to width,
# angles to angle, nvals to nval, z0vals to z0val,
# slopes to slope (for GUI tools and consistency
# across all process components)
# Aug 2009. Updates.
# Jul 2009. Updates.
# May 2009. Updates.
# Jan 2009. Converted from IDL.
#-----------------------------------------------------------------------
# NB! In the CFG file, change MANNING and LAW_OF_WALL flags to
# a single string entry like "friction method". #########
#-----------------------------------------------------------------------
# Notes: Set self.u in manning and law_of_wall functions ??
# Update friction factor in manning() and law_of_wall() ?
# Double check how Rh is used in law_of_the_wall().
# d8_flow has "flow_grids", but this one has "codes".
# Make sure values are not stored twice.
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
# NOTES: This file defines a "base class" for channelized flow
# components as well as functions used by most or
# all channel flow methods. The methods of this class
# (especially "update_velocity") should be over-ridden as
# necessary for different methods of modeling channelized
# flow. See channels_kinematic_wave.py,
# channels_diffusive_wave.py and channels_dynamic_wave.py.
#-----------------------------------------------------------------------
# NOTES: update_free_surface_slope() is called by the
# update_velocity() methods of channels_diffusive_wave.py
# and channels_dynamic_wave.py.
#-----------------------------------------------------------------------
#
# class channels_component
#
# ## get_attribute() # (defined in each channel component)
# get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
#-----------------------------
# set_constants()
# initialize()
# update()
# finalize()
# set_computed_input_vars() # (5/11/10)
#----------------------------------
# initialize_d8_vars() ########
# initialize_computed_vars()
# initialize_diversion_vars() # (9/22/14)
# initialize_outlet_values()
# initialize_peak_values()
# initialize_min_and_max_values() # (2/3/13)
#-------------------------------------
# update_R()
# update_R_integral()
# update_discharge()
# update_diversions() # (9/22/14)
# update_flow_volume()
# update_flow_depth()
# update_free_surface_slope()
# update_shear_stress() # (9/9/14, depth-slope product)
# update_shear_speed() # (9/9/14)
# update_trapezoid_Rh()
# update_friction_factor() # (9/9/14)
#----------------------------------
# update_velocity() # (override as needed)
# update_velocity_on_edges()
# update_froude_number() # (9/9/14)
#----------------------------------
# update_outlet_values()
# update_peak_values() # (at the main outlet)
# update_Q_out_integral() # (moved here from basins.py)
# update_mins_and_maxes() # (don't add into update())
# check_flow_depth()
# check_flow_velocity()
#----------------------------------
# open_input_files()
# read_input_files()
# close_input_files()
#----------------------------------
# update_outfile_names()
# bundle_output_files() # (9/21/14. Not used yet)
# open_output_files()
# write_output_files()
# close_output_files()
# save_grids()
# save_pixel_values()
#----------------------------------
# manning_formula()
# law_of_the_wall()
# print_status_report()
# remove_bad_slopes()
# Functions: # (stand-alone versions of these)
# Trapezoid_Rh()
# Manning_Formula()
# Law_of_the_Wall()
#-----------------------------------------------------------------------
import numpy as np
import os, os.path
from topoflow.utils import BMI_base
# from topoflow.utils import d8_base
from topoflow.utils import file_utils ###
from topoflow.utils import model_input
from topoflow.utils import model_output
from topoflow.utils import ncgs_files ###
from topoflow.utils import ncts_files ###
from topoflow.utils import rtg_files ###
from topoflow.utils import text_ts_files ###
from topoflow.utils import tf_d8_base as d8_base
from topoflow.utils import tf_utils
#-----------------------------------------------------------------------
class channels_component( BMI_base.BMI_component ):
#-----------------------------------------------------------
# Note: rainfall_volume_flux *must* be liquid-only precip.
#-----------------------------------------------------------
_input_var_names = [
'atmosphere_water__rainfall_volume_flux', # (P_rain)
'glacier_ice__melt_volume_flux', # (MR)
## 'land_surface__elevation',
## 'land_surface__slope',
'land_surface_water__baseflow_volume_flux', # (GW)
'land_surface_water__evaporation_volume_flux', # (ET)
'soil_surface_water__infiltration_volume_flux', # (IN)
'snowpack__melt_volume_flux', # (SM)
'water-liquid__mass-per-volume_density' ] # (rho_H2O)
#------------------------------------------------------------------
# 'canals__count', # n_canals
# 'canals_entrance__x_coordinate', # canals_in_x
# 'canals_entrance__y_coordinate', # canals_in_y
# 'canals_entrance_water__volume_fraction', # Q_canals_fraction
# 'canals_exit__x_coordinate', # canals_out_x
# 'canals_exit__y_coordinate', # canals_out_y
# 'canals_exit_water__volume_flow_rate', # Q_canals_out
# 'sinks__count', # n_sinks
# 'sinks__x_coordinate', # sinks_x
# 'sinks__y_coordinate', # sinks_y
# 'sinks_water__volume_flow_rate', # Q_sinks
# 'sources__count', # n_sources
# 'sources__x_coordinate', # sources_x
# 'sources__y_coordinate', # sources_y
# 'sources_water__volume_flow_rate' ] # Q_sources
#----------------------------------
# Maybe add these out_vars later.
#----------------------------------
# ['time_sec', 'time_min' ]
_output_var_names = [
'basin_outlet_water_flow__half_of_fanning_friction_factor', # f_outlet
'basin_outlet_water_x-section__mean_depth', # d_outlet
'basin_outlet_water_x-section__peak_time_of_depth', # Td_peak
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate', # T_peak
'basin_outlet_water_x-section__peak_time_of_volume_flux', # Tu_peak
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate', # vol_Q
'basin_outlet_water_x-section__time_max_of_mean_depth', # d_peak
'basin_outlet_water_x-section__time_max_of_volume_flow_rate', # Q_peak
'basin_outlet_water_x-section__time_max_of_volume_flux', # u_peak
'basin_outlet_water_x-section__volume_flow_rate', # Q_outlet
'basin_outlet_water_x-section__volume_flux', # u_outlet
#--------------------------------------------------
'canals_entrance_water__volume_flow_rate', # Q_canals_in
#--------------------------------------------------
'channel_bottom_surface__slope', # S_bed
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length', # z0val_max
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length', # z0val_min
'channel_bottom_water_flow__log_law_roughness_length', # z0val
'channel_bottom_water_flow__magnitude_of_shear_stress', # tau
'channel_bottom_water_flow__shear_speed', # u_star
'channel_centerline__sinuosity', # sinu
'channel_water__volume', # vol
'channel_water_flow__froude_number', # froude
'channel_water_flow__half_of_fanning_friction_factor', # f
'channel_water_flow__domain_max_of_manning_n_parameter', # nval_max
'channel_water_flow__domain_min_of_manning_n_parameter', # nval_min
'channel_water_flow__manning_n_parameter', # nval
'channel_water_surface__slope', # S_free
#---------------------------------------------------
# These might only be available at the end of run.
#---------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth', # d_max
'channel_water_x-section__domain_min_of_mean_depth', # d_min
'channel_water_x-section__domain_max_of_volume_flow_rate', # Q_max
'channel_water_x-section__domain_min_of_volume_flow_rate', # Q_min
'channel_water_x-section__domain_max_of_volume_flux', # u_max
'channel_water_x-section__domain_min_of_volume_flux', # u_min
#---------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius', # Rh
'channel_water_x-section__initial_mean_depth', # d0
'channel_water_x-section__mean_depth', # d
'channel_water_x-section__volume_flow_rate', # Q
'channel_water_x-section__volume_flux', # u
'channel_water_x-section__wetted_area', # A_wet
'channel_water_x-section__wetted_perimeter', # P_wet
## 'channel_water_x-section_top__width', # (not used)
'channel_x-section_trapezoid_bottom__width', # width
'channel_x-section_trapezoid_side__flare_angle', # angle
'land_surface_water__runoff_volume_flux', # R
'land_surface_water__domain_time_integral_of_runoff_volume_flux', # vol_R
'model__time_step', # dt
'model_grid_cell__area' ] # da
_var_name_map = {
'atmosphere_water__rainfall_volume_flux': 'P_rain',
'glacier_ice__melt_volume_flux': 'MR',
## 'land_surface__elevation': 'DEM',
## 'land_surface__slope': 'S_bed',
'land_surface_water__baseflow_volume_flux': 'GW',
'land_surface_water__evaporation_volume_flux': 'ET',
'soil_surface_water__infiltration_volume_flux': 'IN',
'snowpack__melt_volume_flux': 'SM',
'water-liquid__mass-per-volume_density': 'rho_H2O',
#------------------------------------------------------------------------
'basin_outlet_water_flow__half_of_fanning_friction_factor':'f_outlet',
'basin_outlet_water_x-section__mean_depth': 'd_outlet',
'basin_outlet_water_x-section__peak_time_of_depth': 'Td_peak',
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'T_peak',
'basin_outlet_water_x-section__peak_time_of_volume_flux': 'Tu_peak',
'basin_outlet_water_x-section__volume_flow_rate': 'Q_outlet',
'basin_outlet_water_x-section__volume_flux': 'u_outlet',
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'vol_Q',
'basin_outlet_water_x-section__time_max_of_mean_depth': 'd_peak',
'basin_outlet_water_x-section__time_max_of_volume_flow_rate':'Q_peak',
'basin_outlet_water_x-section__time_max_of_volume_flux': 'u_peak',
#--------------------------------------------------------------------------
'canals_entrance_water__volume_flow_rate': 'Q_canals_in',
#--------------------------------------------------------------------------
'channel_bottom_surface__slope': 'S_bed',
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'z0val_max',
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'z0val_min',
'channel_bottom_water_flow__log_law_roughness_length': 'z0val',
'channel_bottom_water_flow__magnitude_of_shear_stress': 'tau',
'channel_bottom_water_flow__shear_speed': 'u_star',
'channel_centerline__sinuosity': 'sinu',
'channel_water__volume': 'vol',
'channel_water_flow__domain_max_of_manning_n_parameter': 'nval_max',
'channel_water_flow__domain_min_of_manning_n_parameter': 'nval_min',
'channel_water_flow__froude_number': 'froude',
'channel_water_flow__half_of_fanning_friction_factor': 'f',
'channel_water_flow__manning_n_parameter': 'nval',
'channel_water_surface__slope': 'S_free',
#-----------------------------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth': 'd_max',
'channel_water_x-section__domain_min_of_mean_depth': 'd_min',
'channel_water_x-section__domain_max_of_volume_flow_rate': 'Q_max',
'channel_water_x-section__domain_min_of_volume_flow_rate': 'Q_min',
'channel_water_x-section__domain_max_of_volume_flux': 'u_max',
'channel_water_x-section__domain_min_of_volume_flux': 'u_min',
#-----------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius': 'Rh',
'channel_water_x-section__initial_mean_depth': 'd0',
'channel_water_x-section__mean_depth': 'd',
'channel_water_x-section__volume_flow_rate': 'Q',
'channel_water_x-section__volume_flux': 'u',
'channel_water_x-section__wetted_area': 'A_wet',
'channel_water_x-section__wetted_perimeter': 'P_wet',
## 'channel_water_x-section_top__width': # (not used)
'channel_x-section_trapezoid_bottom__width': 'width', ####
'channel_x-section_trapezoid_side__flare_angle': 'angle', ####
'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'vol_R',
'land_surface_water__runoff_volume_flux': 'R',
'model__time_step': 'dt',
'model_grid_cell__area': 'da',
#------------------------------------------------------------------
'canals__count': 'n_canals',
'canals_entrance__x_coordinate': 'canals_in_x',
'canals_entrance__y_coordinate': 'canals_in_y',
'canals_entrance_water__volume_fraction': 'Q_canals_fraction',
'canals_exit__x_coordinate': 'canals_out_x',
'canals_exit__y_coordinate': 'canals_out_y',
'canals_exit_water__volume_flow_rate': 'Q_canals_out',
'sinks__count': 'n_sinks',
'sinks__x_coordinate': 'sinks_x',
'sinks__y_coordinate': 'sinks_y',
'sinks_water__volume_flow_rate': 'Q_sinks',
'sources__count': 'n_sources',
'sources__x_coordinate': 'sources_x',
'sources__y_coordinate': 'sources_y',
'sources_water__volume_flow_rate': 'Q_sources' }
#------------------------------------------------
# Create an "inverse var name map"
# inv_map = dict(zip(map.values(), map.keys()))
#------------------------------------------------
## _long_name_map = dict( zip(_var_name_map.values(),
## _var_name_map.keys() ) )
_var_units_map = {
'atmosphere_water__rainfall_volume_flux': 'm s-1',
'glacier_ice__melt_volume_flux': 'm s-1',
## 'land_surface__elevation': 'm',
## 'land_surface__slope': '1',
'land_surface_water__baseflow_volume_flux': 'm s-1',
'land_surface_water__evaporation_volume_flux': 'm s-1',
'soil_surface_water__infiltration_volume_flux': 'm s-1',
'snowpack__melt_volume_flux': 'm s-1',
'water-liquid__mass-per-volume_density': 'kg m-3',
#---------------------------------------------------------------------------
'basin_outlet_water_flow__half_of_fanning_friction_factor': '1',
'basin_outlet_water_x-section__mean_depth': 'm',
'basin_outlet_water_x-section__peak_time_of_depth': 'min',
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'min',
'basin_outlet_water_x-section__peak_time_of_volume_flux': 'min',
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'm3',
'basin_outlet_water_x-section__time_max_of_mean_depth': 'm',
'basin_outlet_water_x-section__time_max_of_volume_flow_rate': 'm3 s-1',
'basin_outlet_water_x-section__time_max_of_volume_flux': 'm s-1',
'basin_outlet_water_x-section__volume_flow_rate': 'm3',
'basin_outlet_water_x-section__volume_flux': 'm s-1',
#---------------------------------------------------------------------------
'canals_entrance_water__volume_flow_rate': 'm3 s-1',
#---------------------------------------------------------------------------
'channel_bottom_surface__slope': '1',
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'm',
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'm',
'channel_bottom_water_flow__log_law_roughness_length': 'm',
'channel_bottom_water_flow__magnitude_of_shear_stress': 'kg m-1 s-2',
'channel_bottom_water_flow__shear_speed': 'm s-1',
'channel_centerline__sinuosity': '1',
'channel_water__volume': 'm3',
'channel_water_flow__froude_number': '1',
'channel_water_flow__half_of_fanning_friction_factor': '1',
'channel_water_flow__manning_n_parameter': 'm-1/3 s',
'channel_water_flow__domain_max_of_manning_n_parameter': 'm-1/3 s',
'channel_water_flow__domain_min_of_manning_n_parameter': 'm-1/3 s',
'channel_water_surface__slope': '1',
#--------------------------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth': 'm',
'channel_water_x-section__domain_min_of_mean_depth': 'm',
'channel_water_x-section__domain_max_of_volume_flow_rate': 'm3 s-1',
'channel_water_x-section__domain_min_of_volume_flow_rate': 'm3 s-1',
'channel_water_x-section__domain_max_of_volume_flux': 'm s-1',
'channel_water_x-section__domain_min_of_volume_flux': 'm s-1',
#--------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius': 'm',
'channel_water_x-section__initial_mean_depth': 'm',
'channel_water_x-section__mean_depth': 'm',
'channel_water_x-section__volume_flow_rate': 'm3 s-1',
'channel_water_x-section__volume_flux': 'm s-1',
'channel_water_x-section__wetted_area': 'm2',
'channel_water_x-section__wetted_perimeter': 'm',
'channel_x-section_trapezoid_bottom__width': 'm',
'channel_x-section_trapezoid_side__flare_angle': 'rad', # CHECKED
'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'm3',
'land_surface_water__runoff_volume_flux': 'm s-1',
'model__time_step': 's',
'model_grid_cell__area': 'm2',
#------------------------------------------------------------------
'canals__count': '1',
'canals_entrance__x_coordinate': 'm',
'canals_entrance__y_coordinate': 'm',
'canals_entrance_water__volume_fraction': '1',
'canals_exit__x_coordinate': 'm',
'canals_exit__y_coordinate': 'm',
'canals_exit_water__volume_flow_rate': 'm3 s-1',
'sinks__count': '1',
'sinks__x_coordinate': 'm',
'sinks__y_coordinate': 'm',
'sinks_water__volume_flow_rate': 'm3 s-1',
'sources__count': '1',
'sources__x_coordinate': 'm',
'sources__y_coordinate': 'm',
'sources_water__volume_flow_rate': 'm3 s-1' }
#------------------------------------------------
# Return NumPy string arrays vs. Python lists ?
#------------------------------------------------
## _input_var_names = np.array( _input_var_names )
## _output_var_names = np.array( _output_var_names )
#-------------------------------------------------------------------
def get_input_var_names(self):
#--------------------------------------------------------
# Note: These are currently variables needed from other
# components vs. those read from files or GUI.
#--------------------------------------------------------
return self._input_var_names
# get_input_var_names()
#-------------------------------------------------------------------
def get_output_var_names(self):
return self._output_var_names
# get_output_var_names()
#-------------------------------------------------------------------
def get_var_name(self, long_var_name):
return self._var_name_map[ long_var_name ]
# get_var_name()
#-------------------------------------------------------------------
def get_var_units(self, long_var_name):
return self._var_units_map[ long_var_name ]
# get_var_units()
#-------------------------------------------------------------------
## def get_var_type(self, long_var_name):
##
## #---------------------------------------
## # So far, all vars have type "double",
## # but use the one in BMI_base instead.
## #---------------------------------------
## return 'float64'
##
## # get_var_type()
#-------------------------------------------------------------------
def set_constants(self):
#------------------------
# Define some constants
#------------------------
self.g = np.float64(9.81) # (gravitation const.)
self.aval = np.float64(0.476) # (integration const.)
self.kappa = np.float64(0.408) # (von Karman's const.)
self.law_const = np.sqrt(self.g) / self.kappa
self.one_third = np.float64(1.0) / 3.0
self.two_thirds = np.float64(2.0) / 3.0
self.deg_to_rad = np.pi / 180.0
# set_constants()
#-------------------------------------------------------------------
def initialize(self, cfg_file=None, mode="nondriver", SILENT=False):
if not(SILENT):
print ' '
print 'Channels component: Initializing...'
self.status = 'initializing' # (OpenMI 2.0 convention)
self.mode = mode
self.cfg_file = cfg_file
#-----------------------------------------------
# Load component parameters from a config file
#-----------------------------------------------
self.set_constants() # (12/7/09)
# print 'CHANNELS calling initialize_config_vars()...'
self.initialize_config_vars()
# print 'CHANNELS calling read_grid_info()...'
self.read_grid_info()
#print 'CHANNELS calling initialize_basin_vars()...'
self.initialize_basin_vars() # (5/14/10)
#-----------------------------------------
# This must come before "Disabled" test.
#-----------------------------------------
# print 'CHANNELS calling initialize_time_vars()...'
self.initialize_time_vars()
#----------------------------------
# Has component been turned off ?
#----------------------------------
if (self.comp_status == 'Disabled'):
if not(SILENT):
print 'Channels component: Disabled.'
self.SAVE_Q_GRIDS = False # (It is True by default.)
self.SAVE_Q_PIXELS = False # (It is True by default.)
self.DONE = True
self.status = 'initialized' # (OpenMI 2.0 convention)
return
## print '################################################'
## print 'min(d0), max(d0) =', self.d0.min(), self.d0.max()
## print '################################################'
#---------------------------------------------
# Open input files needed to initialize vars
#---------------------------------------------
# Can't move read_input_files() to start of
# update(), since initial values needed here.
#---------------------------------------------
# print 'CHANNELS calling open_input_files()...'
self.open_input_files()
print 'CHANNELS calling read_input_files()...'
self.read_input_files()
#-----------------------
# Initialize variables
#-----------------------
print 'CHANNELS calling initialize_d8_vars()...'
self.initialize_d8_vars() # (depend on D8 flow grid)
print 'CHANNELS calling initialize_computed_vars()...'
self.initialize_computed_vars()
#--------------------------------------------------
# (5/12/10) I think this is obsolete now.
#--------------------------------------------------
# Make sure self.Q_ts_file is not NULL (12/22/05)
# This is only output file that is set by default
# and is still NULL if user hasn't opened the
# output var dialog for the channel process.
#--------------------------------------------------
## if (self.SAVE_Q_PIXELS and (self.Q_ts_file == '')):
## self.Q_ts_file = (self.case_prefix + '_0D-Q.txt')
self.open_output_files()
self.status = 'initialized' # (OpenMI 2.0 convention)
# initialize()
#-------------------------------------------------------------------
## def update(self, dt=-1.0, time_seconds=None):
def update(self, dt=-1.0):
#---------------------------------------------
# Note that u and d from previous time step
# must be used on RHS of the equations here.
#---------------------------------------------
self.status = 'updating' # (OpenMI 2.0 convention)
#-------------------------------------------------------
# There may be times where we want to call this method
# even if component is not the driver. But note that
# the TopoFlow driver also makes this same call.
#-------------------------------------------------------
if (self.mode == 'driver'):
self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s]')
### interval=0.5) # [seconds]
# For testing (5/19/12)
# self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s] CHANNEL')
## DEBUG = True
DEBUG = False
#-------------------------
# Update computed values
#-------------------------
if (DEBUG): print '#### Calling update_R()...'
self.update_R()
if (DEBUG): print '#### Calling update_R_integral()...'
self.update_R_integral()
if (DEBUG): print '#### Calling update_discharge()...'
self.update_discharge()
if (DEBUG): print '#### Calling update_diversions()...'
self.update_diversions()
if (DEBUG): print '#### Calling update_flow_volume()...'
self.update_flow_volume()
if (DEBUG): print '#### Calling update_flow_depth()...'
self.update_flow_depth()
#-----------------------------------------------------------------
if not(self.DYNAMIC_WAVE):
if (DEBUG): print '#### Calling update_trapezoid_Rh()...'
self.update_trapezoid_Rh()
# print 'Rhmin, Rhmax =', self.Rh.min(), self.Rh.max()a
#-----------------------------------------------------------------
# (9/9/14) Moved this here from update_velocity() methods.
#-----------------------------------------------------------------
if not(self.KINEMATIC_WAVE):
if (DEBUG): print '#### Calling update_free_surface_slope()...'
self.update_free_surface_slope()
if (DEBUG): print '#### Calling update_shear_stress()...'
self.update_shear_stress()
if (DEBUG): print '#### Calling update_shear_speed()...'
self.update_shear_speed()
#-----------------------------------------------------------------
# Must update friction factor before velocity for DYNAMIC_WAVE.
#-----------------------------------------------------------------
if (DEBUG): print '#### Calling update_friction_factor()...'
self.update_friction_factor()
#-----------------------------------------------------------------
if (DEBUG): print '#### Calling update_velocity()...'
self.update_velocity()
self.update_velocity_on_edges() # (set to zero)
if (DEBUG): print '#### Calling update_froude_number()...'
self.update_froude_number()
#-----------------------------------------------------------------
## print 'Rmin, Rmax =', self.R.min(), self.R.max()
## print 'Qmin, Qmax =', self.Q.min(), self.Q.max()
## print 'umin, umax =', self.u.min(), self.u.max()
## print 'dmin, dmax =', self.d.min(), self.d.max()
## print 'nmin, nmax =', self.nval.min(), self.nval.max()
## print 'Rhmin, Rhmax =', self.Rh.min(), self.Rh.max()
## print 'Smin, Smax =', self.S_bed.min(), self.S_bed.max()
if (DEBUG): print '#### Calling update_outlet_values()...'
self.update_outlet_values()
if (DEBUG): print '#### Calling update peak values()...'
self.update_peak_values()
if (DEBUG): print '#### Calling update_Q_out_integral()...'
self.update_Q_out_integral()
#---------------------------------------------
# This takes extra time and is now done
# only at the end, in finalize(). (8/19/13)
#---------------------------------------------
# But then "topoflow_driver" doesn't get
# correctly updated values for some reason.
#---------------------------------------------
## self.update_mins_and_maxes()
#------------------------
# Check computed values
#------------------------
D_OK = self.check_flow_depth()
U_OK = self.check_flow_velocity()
OK = (D_OK and U_OK)
#-------------------------------------------
# Read from files as needed to update vars
#-----------------------------------------------------
# NB! This is currently not needed for the "channel
# process" because values don't change over time and
# read_input_files() is called by initialize().
#-----------------------------------------------------
# if (self.time_index > 0):
# self.read_input_files()
#----------------------------------------------
# Write user-specified data to output files ?
#----------------------------------------------
# Components use own self.time_sec by default.
#-----------------------------------------------
if (DEBUG): print '#### Calling write_output_files()...'
self.write_output_files()
## self.write_output_files( time_seconds )
#-----------------------------
# Update internal clock
# after write_output_files()
#-----------------------------
if (DEBUG): print '#### Calling update_time()'
self.update_time( dt )
if (OK):
self.status = 'updated' # (OpenMI 2.0 convention)
else:
self.status = 'failed'
self.DONE = True
# update()
#-------------------------------------------------------------------
def finalize(self):
#---------------------------------------------------
# We can compute mins and maxes in the final grids
# here, but the framework will not then pass them
# to any component (e.g. topoflow_driver) that may
# need them.
#---------------------------------------------------
REPORT = True
self.update_mins_and_maxes( REPORT=REPORT ) ## (2/6/13)
self.print_final_report(comp_name='Channels component')
self.status = 'finalizing' # (OpenMI)
self.close_input_files() # TopoFlow input "data streams"
self.close_output_files()
self.status = 'finalized' # (OpenMI)
#---------------------------
# Release all of the ports
#----------------------------------------
# Make this call in "finalize()" method
# of the component's CCA Imple file
#----------------------------------------
# self.release_cca_ports( d_services )
# finalize()
#-------------------------------------------------------------------
def set_computed_input_vars(self):
#---------------------------------------------------------------
# Note: The initialize() method calls initialize_config_vars()
# (in BMI_base.py), which calls this method at the end.
#--------------------------------------------------------------
cfg_extension = self.get_attribute( 'cfg_extension' ).lower()
# cfg_extension = self.get_cfg_extension().lower()
self.KINEMATIC_WAVE = ("kinematic" in cfg_extension)
self.DIFFUSIVE_WAVE = ("diffusive" in cfg_extension)
self.DYNAMIC_WAVE = ("dynamic" in cfg_extension)
##########################################################
# (5/17/12) If MANNING, we need to set z0vals to -1 so
# they are always defined for use with new framework.
##########################################################
if (self.MANNING):
if (self.nval != None):
self.nval = np.float64( self.nval ) #### 10/9/10, NEED
self.nval_min = self.nval.min()
self.nval_max = self.nval.max()
#-----------------------------------
self.z0val = np.float64(-1)
self.z0val_min = np.float64(-1)
self.z0val_max = np.float64(-1)
if (self.LAW_OF_WALL):
if (self.z0val != None):
self.z0val = np.float64( self.z0val ) #### (10/9/10)
self.z0val_min = self.z0val.min()
self.z0val_max = self.z0val.max()
#-----------------------------------
self.nval = np.float64(-1)
self.nval_min = np.float64(-1)
self.nval_max = np.float64(-1)
#-------------------------------------------
# These currently can't be set to anything
# else in the GUI, but need to be defined.
#-------------------------------------------
self.code_type = 'Grid'
self.slope_type = 'Grid'
#---------------------------------------------------------
# Make sure that all "save_dts" are larger or equal to
# the specified process dt. There is no point in saving
# results more often than they change.
# Issue a message to this effect if any are smaller ??
#---------------------------------------------------------
self.save_grid_dt = np.maximum(self.save_grid_dt, self.dt)
self.save_pixels_dt = np.maximum(self.save_pixels_dt, self.dt)
#---------------------------------------------------
# This is now done in CSDMS_base.read_config_gui()
# for any var_name that starts with "SAVE_".
#---------------------------------------------------
# self.SAVE_Q_GRID = (self.SAVE_Q_GRID == 'Yes')
# set_computed_input_vars()
#-------------------------------------------------------------------
def initialize_d8_vars(self):
#---------------------------------------------
# Compute and store a variety of (static) D8
# flow grid variables. Embed structure into
# the "channel_base" component.
#---------------------------------------------
self.d8 = d8_base.d8_component()
###############################################
# (5/13/10) Do next line here for now, until
# the d8 cfg_file includes static prefix.
# Same is done in GW_base.py.
###############################################
# tf_d8_base.read_grid_info() also needs
# in_directory to be set. (10/27/11)
###############################################
#--------------------------------------------------
# D8 component builds its cfg filename from these
#--------------------------------------------------
self.d8.site_prefix = self.site_prefix
self.d8.in_directory = self.in_directory
self.d8.initialize( cfg_file=None,
SILENT=self.SILENT,
REPORT=self.REPORT )
## self.code = self.d8.code # Don't need this.
#-------------------------------------------
# We'll need this once we shift from using
# "tf_d8_base.py" to the new "d8_base.py"
#-------------------------------------------
# self.d8.update(self.time, SILENT=False, REPORT=True)
# initialize_d8_vars()
#-------------------------------------------------------------
def initialize_computed_vars(self):
#-----------------------------------------------
# Convert bank angles from degrees to radians.
#-----------------------------------------------
self.angle = self.angle * self.deg_to_rad # [radians]
#------------------------------------------------
# 8/29/05. Multiply ds by (unitless) sinuosity
# Orig. ds is used by subsurface flow
#------------------------------------------------
# NB! We should also divide slopes in S_bed by
# the sinuosity, as now done here.
#----------------------------------------------------
# NB! This saves a modified version of ds that
# is only used within the "channels" component.
# The original "ds" is stored within the
# topoflow model component and is used for
# subsurface flow, etc.
#----------------------------------------------------
### self.d8.ds_chan = (self.sinu * ds)
### self.ds = (self.sinu * self.d8.ds)
self.d8.ds = (self.sinu * self.d8.ds) ### USE LESS MEMORY
###################################################
###################################################
### S_bed = (S_bed / self.sinu) #*************
self.slope = (self.slope / self.sinu)
self.S_bed = self.slope
###################################################
###################################################
#---------------------------
# Initialize spatial grids
#-----------------------------------------------
# NB! It is not a good idea to initialize the
# water depth grid to a nonzero scalar value.
#-----------------------------------------------
print 'Initializing u, f, d grids...'
self.u = np.zeros([self.ny, self.nx], dtype='Float64')
self.f = np.zeros([self.ny, self.nx], dtype='Float64')
self.d = np.zeros([self.ny, self.nx], dtype='Float64') + self.d0
#########################################################
# Add this on (2/3/13) so make the TF driver happy
# during its initialize when it gets reference to R.
# But in "update_R()", be careful not to break the ref.
# "Q" may be subject to the same issue.
#########################################################
self.Q = np.zeros([self.ny, self.nx], dtype='Float64')
self.R = np.zeros([self.ny, self.nx], dtype='Float64')
#---------------------------------------------------
# Initialize new grids. Is this needed? (9/13/14)
#---------------------------------------------------
self.tau = np.zeros([self.ny, self.nx], dtype='Float64')
self.u_star = np.zeros([self.ny, self.nx], dtype='Float64')
self.froude = np.zeros([self.ny, self.nx], dtype='Float64')
#---------------------------------------
# These are used to check mass balance
#---------------------------------------
self.vol_R = self.initialize_scalar( 0, dtype='float64')
self.vol_Q = self.initialize_scalar( 0, dtype='float64')
#-------------------------------------------
# Make sure all slopes are valid & nonzero
# since otherwise flow will accumulate
#-------------------------------------------
if (self.KINEMATIC_WAVE):
self.remove_bad_slopes() #(3/8/07. Only Kin Wave case)
#----------------------------------------
# Initial volume of water in each pixel
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
L2 = self.d * np.tan(self.angle)
self.A_wet = self.d * (self.width + L2)
self.P_wet = self.width + (np.float64(2) * self.d / np.cos(self.angle) )
self.vol = self.A_wet * self.d8.ds # [m3]
#-------------------------------------------------------
# Note: depth is often zero at the start of a run, and
# both width and then P_wet are also zero in places.
# Therefore initialize Rh as shown.
#-------------------------------------------------------
self.Rh = np.zeros([self.ny, self.nx], dtype='Float64')
## self.Rh = self.A_wet / self.P_wet # [m]
## print 'P_wet.min() =', self.P_wet.min()
## print 'width.min() =', self.width.min()
## self.initialize_diversion_vars() # (9/22/14)
self.initialize_outlet_values()
self.initialize_peak_values()
self.initialize_min_and_max_values() ## (2/3/13)
#########################################
# Maybe save all refs in a dictionary
# called "self_values" here ? (2/19/13)
# Use a "reverse" var_name mapping?
# inv_map = dict(zip(map.values(), map.keys()))
#########################################
## w = np.where( self.width <= 0 )
## nw = np.size( w[0] ) # (This is correct for 1D or 2D.)
## if (nw > 0):
## print 'WARNING:'
## print 'Number of locations where width==0 =', nw
## if (nw < 10):
## print 'locations =', w
## print ' '
# initialize_computed_vars()
#-------------------------------------------------------------
def initialize_diversion_vars(self):
#-----------------------------------------
# Compute source IDs from xy coordinates
#-----------------------------------------
source_rows = np.int32( self.sources_y / self.ny )
source_cols = np.int32( self.sources_x / self.nx )
self.source_IDs = (source_rows, source_cols)
## self.source_IDs = (source_rows * self.nx) + source_cols
#---------------------------------------
# Compute sink IDs from xy coordinates
#---------------------------------------
sink_rows = np.int32( self.sinks_y / self.ny )
sink_cols = np.int32( self.sinks_x / self.nx )
self.sink_IDs = (sink_rows, sink_cols)
## self.sink_IDs = (sink_rows * self.nx) + sink_cols
#-------------------------------------------------
# Compute canal entrance IDs from xy coordinates
#-------------------------------------------------
canal_in_rows = np.int32( self.canals_in_y / self.ny )
canal_in_cols = np.int32( self.canals_in_x / self.nx )
self.canal_in_IDs = (canal_in_rows, canal_in_cols)
## self.canal_in_IDs = (canal_in_rows * self.nx) + canal_in_cols
#---------------------------------------------
# Compute canal exit IDs from xy coordinates
#---------------------------------------------
canal_out_rows = np.int32( self.canals_out_y / self.ny )
canal_out_cols = np.int32( self.canals_out_x / self.nx )
self.canal_out_IDs = (canal_out_rows, canal_out_cols)
## self.canal_out_IDs = (canal_out_rows * self.nx) + canal_out_cols
#--------------------------------------------------
# This will be computed from Q_canal_fraction and
# self.Q and then passed back to Diversions
#--------------------------------------------------
self.Q_canals_in = np.array( self.n_sources, dtype='float64' )
# initialize_diversion_vars()
#-------------------------------------------------------------------
def initialize_outlet_values(self):
#---------------------------------------------------
# Note: These are retrieved and used by TopoFlow
# for the stopping condition. TopoFlow
# receives a reference to these, but in
# order to see the values change they need
# to be stored as mutable, 1D numpy arrays.
#---------------------------------------------------
# Note: Q_last is internal to TopoFlow.
#---------------------------------------------------
# self.Q_outlet = self.Q[ self.outlet_ID ]
self.Q_outlet = self.initialize_scalar(0, dtype='float64')
self.u_outlet = self.initialize_scalar(0, dtype='float64')
self.d_outlet = self.initialize_scalar(0, dtype='float64')
self.f_outlet = self.initialize_scalar(0, dtype='float64')
# initialize_outlet_values()
#-------------------------------------------------------------------
def initialize_peak_values(self):
#-------------------------
# Initialize peak values
#-------------------------
self.Q_peak = self.initialize_scalar(0, dtype='float64')
self.T_peak = self.initialize_scalar(0, dtype='float64')
self.u_peak = self.initialize_scalar(0, dtype='float64')
self.Tu_peak = self.initialize_scalar(0, dtype='float64')
self.d_peak = self.initialize_scalar(0, dtype='float64')
self.Td_peak = self.initialize_scalar(0, dtype='float64')
# initialize_peak_values()
#-------------------------------------------------------------------
def initialize_min_and_max_values(self):
#-------------------------------
# Initialize min & max values
# (2/3/13), for new framework.
#-------------------------------
v = 1e6
self.Q_min = self.initialize_scalar(v, dtype='float64')
self.Q_max = self.initialize_scalar(-v, dtype='float64')
self.u_min = self.initialize_scalar(v, dtype='float64')
self.u_max = self.initialize_scalar(-v, dtype='float64')
self.d_min = self.initialize_scalar(v, dtype='float64')
self.d_max = self.initialize_scalar(-v, dtype='float64')
# initialize_min_and_max_values()
#-------------------------------------------------------------------
# def update_excess_rainrate(self):
def update_R(self):
#----------------------------------------
# Compute the "excess rainrate", R.
# Each term must have same units: [m/s]
# Sum = net gain/loss rate over pixel.
#----------------------------------------------------
# R can be positive or negative. If negative, then
# water is removed from the surface at rate R until
# surface water is consumed.
#--------------------------------------------------------------
# P = precip_rate [m/s] (converted by read_input_data()).
# SM = snowmelt rate [m/s]
# GW = seep rate [m/s] (water_table intersects surface)
# ET = evap rate [m/s]
# IN = infil rate [m/s]
# MR = icemelt rate [m/s]
#------------------------------------------------------------
# Use refs to other comp vars from new framework. (5/18/12)
#------------------------------------------------------------
P = self.P_rain # (This is now liquid-only precip. 9/14/14)
SM = self.SM
GW = self.GW
ET = self.ET
IN = self.IN
MR = self.MR
## if (self.DEBUG):
## print 'At time:', self.time_min, ', P =', P, '[m/s]'
#--------------
# For testing
#--------------
## print '(Pmin, Pmax) =', P.min(), P.max()
## print '(SMmin, SMmax) =', SM.min(), SM.max()
## print '(GWmin, GWmax) =', GW.min(), GW.max()
## print '(ETmin, ETmax) =', ET.min(), ET.max()
## print '(INmin, INmax) =', IN.min(), IN.max()
## print '(MRmin, MRmax) =', MR.min(), MR.max()
## # print '(Hmin, Hmax) =', H.min(), H.max()
## print ' '
self.R = (P + SM + GW + MR) - (ET + IN)
# update_R()
#-------------------------------------------------------------------
def update_R_integral(self):
#-----------------------------------------------
# Update mass total for R, sum over all pixels
#-----------------------------------------------
volume = np.double(self.R * self.da * self.dt) # [m^3]
if (np.size(volume) == 1):
self.vol_R += (volume * self.rti.n_pixels)
else:
self.vol_R += np.sum(volume)
# update_R_integral()
#-------------------------------------------------------------------
def update_discharge(self):
#---------------------------------------------------------
# The discharge grid, Q, gives the flux of water _out_
# of each grid cell. This entire amount then flows
# into one of the 8 neighbor grid cells, as indicated
# by the D8 flow code. The update_flow_volume() function
# is called right after this one in update() and uses
# the Q grid.
#---------------------------------------------------------
# 7/15/05. The cross-sectional area of a trapezoid is
# given by: Ac = d * (w + (d * tan(theta))),
# where w is the bottom width. If we were to
# use: Ac = w * d, then we'd have Ac=0 when w=0.
# We also need angle units to be radians.
#---------------------------------------------------------
#-----------------------------
# Compute the discharge grid
#------------------------------------------------------
# A_wet is initialized in initialize_computed_vars().
# A_wet is updated in update_trapezoid_Rh().
#------------------------------------------------------
### self.Q = np.float64(self.u * A_wet)
self.Q[:] = self.u * self.A_wet ## (2/19/13, in place)
#--------------
# For testing
#--------------
## print '(umin, umax) =', self.u.min(), self.u.max()
## print '(d0min, d0max) =', self.d0.min(), self.d0.max()
## print '(dmin, dmax) =', self.d.min(), self.d.max()
## print '(amin, amax) =', self.angle.min(), self.angle.max()
## print '(wmin, wmax) =', self.width.min(), self.width.max()
## print '(Qmin, Qmax) =', self.Q.min(), self.Q.max()
## print '(L2min, L2max) =', L2.min(), L2.max()
## print '(Qmin, Qmax) =', self.Q.min(), self.Q.max()
#--------------
# For testing
#--------------
# print 'dmin, dmax =', self.d.min(), self.d.max()
# print 'umin, umax =', self.u.min(), self.u.max()
# print 'Qmin, Qmax =', self.Q.min(), self.Q.max()
# print ' '
# print 'u(outlet) =', self.u[self.outlet_ID]
# print 'Q(outlet) =', self.Q[self.outlet_ID] ########
#----------------------------------------------------
# Wherever depth is less than z0, assume that water
# is not flowing and set u and Q to zero.
# However, we also need (d gt 0) to avoid a divide
# by zero problem, even when numerators are zero.
#----------------------------------------------------
# FLOWING = (d > (z0/aval))
#*** FLOWING[self.d8.noflow_IDs] = False ;******
# u = (u * FLOWING)
# Q = (Q * FLOWING)
# d = np.maximum(d, 0.0) ;(allow depths lt z0, if gt 0.)
# update_discharge()
#-------------------------------------------------------------------
def update_diversions(self):
#--------------------------------------------------------------
# Note: The Channel component requests the following input
# vars from the Diversions component by including
# them in its "get_input_vars()":
# (1) Q_sources, Q_sources_x, Q_sources_y
# (2) Q_sinks, Q_sinks_x, Q_sinks_y
# (3) Q_canals_out, Q_canals_out_x, Q_canals_out_y
# (4) Q_canals_fraction, Q_canals_in_x, Q_canals_in_y.
# source_IDs are computed from (x,y) coordinates during
# initialize().
#
# Diversions component needs to get Q_canals_in from the
# Channel component.
#--------------------------------------------------------------
# Note: This *must* be called after update_discharge() and
# before update_flow_volume().
#--------------------------------------------------------------
# Note: The Q grid stores the volume flow rate *leaving* each
# grid cell in the domain. For sources, an extra amount
# is leaving the cell which can flow into its D8 parent
# cell. For sinks, a lesser amount is leaving the cell
# toward the D8 parent.
#--------------------------------------------------------------
# Note: It is not enough to just update Q and then call the
# update_flow_volume() method. This is because it
# won't update the volume in the channels in the grid
# cells that the extra discharge is leaving from.
#--------------------------------------------------------------
# If a grid cell contains a "source", then an additional Q
# will flow *into* that grid cell and increase flow volume.
#--------------------------------------------------------------
#-------------------------------------------------------------
# This is not fully tested but runs. However, the Diversion
# vars are still computed even when Diversions component is
# disabled. So it slows things down somewhat.
#-------------------------------------------------------------
return
########################
########################
#----------------------------------------
# Update Q and vol due to point sources
#----------------------------------------
## if (hasattr(self, 'source_IDs')):
if (self.n_sources > 0):
self.Q[ self.source_IDs ] += self.Q_sources
self.vol[ self.source_IDs ] += (self.Q_sources * self.dt)
#--------------------------------------
# Update Q and vol due to point sinks
#--------------------------------------
## if (hasattr(self, 'sink_IDs')):
if (self.n_sinks > 0):
self.Q[ self.sink_IDs ] -= self.Q_sinks
self.vol[ self.sink_IDs ] -= (self.Q_sinks * self.dt)
#---------------------------------------
# Update Q and vol due to point canals
#---------------------------------------
## if (hasattr(self, 'canal_in_IDs')):
if (self.n_canals > 0):
#-----------------------------------------------------------------
# Q grid was just modified. Apply the canal diversion fractions
# to compute the volume flow rate into upstream ends of canals.
#-----------------------------------------------------------------
Q_canals_in = self.Q_canals_fraction * self.Q[ self.canal_in_IDs ]
self.Q_canals_in = Q_canals_in
#----------------------------------------------------
# Update Q and vol due to losses at canal entrances
#----------------------------------------------------
self.Q[ self.canal_in_IDs ] -= Q_canals_in
self.vol[ self.canal_in_IDs ] -= (Q_canals_in * self.dt)
#-------------------------------------------------
# Update Q and vol due to gains at canal exits.
# Diversions component accounts for travel time.
#-------------------------------------------------
self.Q[ self.canal_out_IDs ] += self.Q_canals_out
self.vol[ self.canal_out_IDs ] += (self.Q_canals_out * self.dt)
# update_diversions()
#-------------------------------------------------------------------
def update_flow_volume(self):
#-----------------------------------------------------------
# Notes: This function must be called after
# update_discharge() and update_diversions().
#-----------------------------------------------------------
# Notes: Q = surface discharge [m^3/s]
# R = excess precip. rate [m/s]
# da = pixel area [m^2]
# dt = channel flow timestep [s]
# vol = total volume of water in pixel [m^3]
# v2 = temp version of vol
# w1 = IDs of pixels that...
# p1 = IDs of parent pixels that...
#-----------------------------------------------------------
dt = self.dt # [seconds]
#----------------------------------------------------
# Add contribution (or loss ?) from excess rainrate
#----------------------------------------------------
# Contributions over entire grid cell from rainfall,
# snowmelt, icemelt and baseflow (minus losses from
# evaporation and infiltration) are assumed to flow
# into the channel within the grid cell.
# Note that R is allowed to be negative.
#----------------------------------------------------
self.vol += (self.R * self.da) * dt # (in place)
#-----------------------------------------
# Add contributions from neighbor pixels
#-------------------------------------------------------------
# Each grid cell passes flow to *one* downstream neighbor.
# Note that multiple grid cells can flow toward a given grid
# cell, so a grid cell ID may occur in d8.p1 and d8.p2, etc.
#-------------------------------------------------------------
# (2/16/10) RETEST THIS. Before, a copy called "v2" was
# used but this doesn't seem to be necessary.
#-------------------------------------------------------------
if (self.d8.p1_OK):
self.vol[ self.d8.p1 ] += (dt * self.Q[self.d8.w1])
if (self.d8.p2_OK):
self.vol[ self.d8.p2 ] += (dt * self.Q[self.d8.w2])
if (self.d8.p3_OK):
self.vol[ self.d8.p3 ] += (dt * self.Q[self.d8.w3])
if (self.d8.p4_OK):
self.vol[ self.d8.p4 ] += (dt * self.Q[self.d8.w4])
if (self.d8.p5_OK):
self.vol[ self.d8.p5 ] += (dt * self.Q[self.d8.w5])
if (self.d8.p6_OK):
self.vol[ self.d8.p6 ] += (dt * self.Q[self.d8.w6])
if (self.d8.p7_OK):
self.vol[ self.d8.p7 ] += (dt * self.Q[self.d8.w7])
if (self.d8.p8_OK):
self.vol[ self.d8.p8 ] += (dt * self.Q[self.d8.w8])
#----------------------------------------------------
# Subtract the amount that flows out to D8 neighbor
#----------------------------------------------------
self.vol -= (self.Q * dt) # (in place)
#--------------------------------------------------------
# While R can be positive or negative, the surface flow
# volume must always be nonnegative. This also ensures
# that the flow depth is nonnegative. (7/13/06)
#--------------------------------------------------------
## self.vol = np.maximum(self.vol, 0.0)
## self.vol[:] = np.maximum(self.vol, 0.0) # (2/19/13)
np.maximum( self.vol, 0.0, self.vol ) # (in place)
# update_flow_volume
#-------------------------------------------------------------------
def update_flow_depth(self):
#-----------------------------------------------------------
# Notes: 7/18/05. Modified to use the equation for volume
# of a trapezoidal channel: vol = Ac * ds, where
# Ac=d*[w + d*tan(t)], and to solve the resulting
# quadratic (discarding neg. root) for new depth, d.
# 8/29/05. Now original ds is used for subsurface
# flow and there is a ds_chan which can include a
# sinuosity greater than 1. This may be especially
# important for larger pixel sizes.
# Removed (ds > 1) here which was only meant to
# avoid a "divide by zero" error at pixels where
# (ds eq 0). This isn't necessary since the
# Flow_Lengths function in utils_TF.pro never
# returns a value of zero.
#----------------------------------------------------------
# Modified to avoid double where calls, which
# reduced cProfile run time for this method from
# 1.391 to 0.644. (9/23/14)
#----------------------------------------------------------
# Commented this out on (2/18/10) because it doesn't
# seem to be used anywhere now. Checked all
# of the Channels components.
#----------------------------------------------------------
# self.d_last = self.d.copy()
#-----------------------------------
# Make some local aliases and vars
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
d = self.d
width = self.width ###
angle = self.angle
SCALAR_ANGLES = (np.size(angle) == 1)
#------------------------------------------------------
# (2/18/10) New code to deal with case where the flow
# depth exceeds a bankfull depth.
# For now, d_bankfull is hard-coded.
#
# CHANGE Manning's n here, too?
#------------------------------------------------------
d_bankfull = 4.0 # [meters]
################################
wb = (self.d > d_bankfull) # (array of True or False)
self.width[ wb ] = self.d8.dw[ wb ]
if not(SCALAR_ANGLES):
self.angle[ wb ] = 0.0
# w_overbank = np.where( d > d_bankfull )
# n_overbank = np.size( w_overbank[0] )
# if (n_overbank != 0):
# width[ w_overbank ] = self.d8.dw[ w_overbank ]
# if not(SCALAR_ANGLES): angle[w_overbank] = 0.0
#------------------------------------------------------
# (2/18/10) New code to deal with case where the top
# width exceeds the grid cell width, dw.
#------------------------------------------------------
top_width = width + (2.0 * d * np.sin(self.angle))
wb = (top_width > self.d8.dw) # (array of True or False)
self.width[ wb ] = self.d8.dw[ wb ]
if not(SCALAR_ANGLES):
self.angle[ wb ] = 0.0
# wb = np.where(top_width > self.d8.dw)
# nb = np.size(w_bad[0])
# if (nb != 0):
# width[ wb ] = self.d8.dw[ wb ]
# if not(SCALAR_ANGLES): angle[ wb ] = 0.0
#----------------------------------
# Is "angle" a scalar or a grid ?
#----------------------------------
if (SCALAR_ANGLES):
if (angle == 0.0):
d = self.vol / (width * self.d8.ds)
else:
denom = 2.0 * np.tan(angle)
arg = 2.0 * denom * self.vol / self.d8.ds
arg += width**(2.0)
d = (np.sqrt(arg) - width) / denom
else:
#-----------------------------------------------------
# Pixels where angle is 0 must be handled separately
#-----------------------------------------------------
w1 = ( angle == 0 ) # (arrays of True or False)
w2 = np.invert( w1 )
#-----------------------------------
A_top = width[w1] * self.d8.ds[w1]
d[w1] = self.vol[w1] / A_top
#-----------------------------------
denom = 2.0 * np.tan(angle[w2])
arg = 2.0 * denom * self.vol[w2] / self.d8.ds[w2]
arg += width[w2]**(2.0)
d[w2] = (np.sqrt(arg) - width[w2]) / denom
#-----------------------------------------------------
# Pixels where angle is 0 must be handled separately
#-----------------------------------------------------
# wz = np.where( angle == 0 )
# nwz = np.size( wz[0] )
# wzc = np.where( angle != 0 )
# nwzc = np.size( wzc[0] )
#
# if (nwz != 0):
# A_top = width[wz] * self.d8.ds[wz]
# ## A_top = self.width[wz] * self.d8.ds_chan[wz]
# d[wz] = self.vol[wz] / A_top
#
# if (nwzc != 0):
# term1 = 2.0 * np.tan(angle[wzc])
# arg = 2.0 * term1 * self.vol[wzc] / self.d8.ds[wzc]
# arg += width[wzc]**(2.0)
# d[wzc] = (np.sqrt(arg) - width[wzc]) / term1
#------------------------------------------
# Set depth values on edges to zero since
# they become spikes (no outflow) 7/15/06
#------------------------------------------
d[ self.d8.noflow_IDs ] = 0.0
#------------------------------------------------
# 4/19/06. Force flow depth to be positive ?
#------------------------------------------------
# This seems to be needed with the non-Richards
# infiltration routines when starting with zero
# depth everywhere, since all water infiltrates
# for some period of time. It also seems to be
# needed more for short rainfall records to
# avoid a negative flow depth error.
#------------------------------------------------
# 7/13/06. Still needed for Richards method
#------------------------------------------------
## self.d = np.maximum(d, 0.0)
np.maximum(d, 0.0, self.d) # (2/19/13, in place)
#-------------------------------------------------
# Find where d <= 0 and save for later (9/23/14)
#-------------------------------------------------
self.d_is_pos = (self.d > 0)
self.d_is_neg = np.invert( self.d_is_pos )
# update_flow_depth
#-------------------------------------------------------------------
def update_free_surface_slope(self):
#-----------------------------------------------------------
# Notes: It is assumed that the flow directions don't
# change even though the free surface is changing.
#-----------------------------------------------------------
delta_d = (self.d - self.d[self.d8.parent_IDs])
self.S_free[:] = self.S_bed + (delta_d / self.d8.ds)
#--------------------------------------------
# Don't do this; negative slopes are needed
# to decelerate flow in dynamic wave case
# and for backwater effects.
#--------------------------------------------
# Set negative slopes to zero
#------------------------------
### self.S_free = np.maximum(self.S_free, 0)
# update_free_surface_slope()
#-------------------------------------------------------------------
def update_shear_stress(self):
#--------------------------------------------------------
# Notes: 9/9/14. Added so shear stress could be shared.
# This uses the depth-slope product.
#--------------------------------------------------------
if (self.KINEMATIC_WAVE):
slope = self.S_bed
else:
slope = self.S_free
self.tau[:] = self.rho_H2O * self.g * self.d * slope
# update_shear_stress()
#-------------------------------------------------------------------
def update_shear_speed(self):
#--------------------------------------------------------
# Notes: 9/9/14. Added so shear speed could be shared.
#--------------------------------------------------------
self.u_star[:] = np.sqrt( self.tau / self.rho_H2O )
# update_shear_speed()
#-------------------------------------------------------------------
def update_trapezoid_Rh(self):
#-------------------------------------------------------------
# Notes: Compute the hydraulic radius of a trapezoid that:
# (1) has a bed width of wb >= 0 (0 for triangular)
# (2) has a bank angle of theta (0 for rectangular)
# (3) is filled with water to a depth of d.
# The units of wb and d are meters. The units of
# theta are assumed to be degrees and are converted.
#-------------------------------------------------------------
# NB! wb should never be zero, so P_wet can never be 0,
# which would produce a NaN (divide by zero).
#-------------------------------------------------------------
# See Notes for TF_Tan function in utils_TF.pro
# AW = d * (wb + (d * TF_Tan(theta_rad)) )
#-------------------------------------------------------------
# 9/9/14. Bug fix. Angles were already in radians but
# were converted to radians again.
#--------------------------------------------------------------
#---------------------------------------------------------
# Compute hydraulic radius grid for trapezoidal channels
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
d = self.d # (local synonyms)
wb = self.width # (trapezoid bottom width)
L2 = d * np.tan( self.angle )
A_wet = d * (wb + L2)
P_wet = wb + (np.float64(2) * d / np.cos(self.angle) )
#---------------------------------------------------
# At noflow_IDs (e.g. edges) P_wet may be zero
# so do this to avoid "divide by zero". (10/29/11)
#---------------------------------------------------
P_wet[ self.d8.noflow_IDs ] = np.float64(1)
Rh = (A_wet / P_wet)
#--------------------------------
# w = np.where(P_wet == 0)
# print 'In update_trapezoid_Rh():'
# print ' P_wet= 0 at', w[0].size, 'cells'
#------------------------------------
# Force edge pixels to have Rh = 0.
# This will make u = 0 there also.
#------------------------------------
Rh[ self.d8.noflow_IDs ] = np.float64(0)
## w = np.where(wb <= 0)
## nw = np.size(w[0])
## if (nw > 0): Rh[w] = np.float64(0)
self.Rh[:] = Rh
self.A_wet[:] = A_wet ## (Now shared: 9/9/14)
self.P_wet[:] = P_wet ## (Now shared: 9/9/14)
#---------------
# For testing
#--------------
## print 'dmin, dmax =', d.min(), d.max()
## print 'wmin, wmax =', wb.min(), wb.max()
## print 'amin, amax =', self.angle.min(), self.angle.max()
# update_trapezoid_Rh()
#-------------------------------------------------------------------
def update_friction_factor(self):
#----------------------------------------
# Note: Added on 9/9/14 to streamline.
#----------------------------------------------------------
# Note: f = half of the Fanning friction factor
# d = flow depth [m]
# z0 = roughness length
# S = bed slope (assumed equal to friction slope)
# g = 9.81 = gravitation constant [m/s^2]
#---------------------------------------------------------
# For law of the wall:
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# law_const = sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
#########################################################
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
###############################################################
# cProfile: This method took: 0.369 secs for topoflow_test()
###############################################################
#--------------------------------------
# Find where (d <= 0). g=good, b=bad
#--------------------------------------
wg = self.d_is_pos
wb = self.d_is_neg
# wg = ( self.d > 0 )
# wb = np.invert( wg )
#-----------------------------
# Compute f for Manning case
#-----------------------------------------
# This makes f=0 and du=0 where (d <= 0)
#-----------------------------------------
if (self.MANNING):
n2 = self.nval ** np.float64(2)
self.f[ wg ] = self.g * (n2[wg] / (self.d[wg] ** self.one_third))
self.f[ wb ] = np.float64(0)
#---------------------------------
# Compute f for Law of Wall case
#---------------------------------
if (self.LAW_OF_WALL):
#------------------------------------------------
# Make sure (smoothness > 1) before taking log.
# Should issue a warning if this is used.
#------------------------------------------------
smoothness = (self.aval / self.z0val) * self.d
np.maximum(smoothness, np.float64(1.1), smoothness) # (in place)
self.f[wg] = (self.kappa / np.log(smoothness[wg])) ** np.float64(2)
self.f[wb] = np.float64(0)
##############################################################
# cProfile: This method took: 0.93 secs for topoflow_test()
##############################################################
# #--------------------------------------
# # Find where (d <= 0). g=good, b=bad
# #--------------------------------------
# wg = np.where( self.d > 0 )
# ng = np.size( wg[0])
# wb = np.where( self.d <= 0 )
# nb = np.size( wb[0] )
#
# #-----------------------------
# # Compute f for Manning case
# #-----------------------------------------
# # This makes f=0 and du=0 where (d <= 0)
# #-----------------------------------------
# if (self.MANNING):
# n2 = self.nval ** np.float64(2)
# if (ng != 0):
# self.f[wg] = self.g * (n2[wg] / (self.d[wg] ** self.one_third))
# if (nb != 0):
# self.f[wb] = np.float64(0)
#
# #---------------------------------
# # Compute f for Law of Wall case
# #---------------------------------
# if (self.LAW_OF_WALL):
# #------------------------------------------------
# # Make sure (smoothness > 1) before taking log.
# # Should issue a warning if this is used.
# #------------------------------------------------
# smoothness = (self.aval / self.z0val) * self.d
# np.maximum(smoothness, np.float64(1.1), smoothness) # (in place)
# ## smoothness = np.maximum(smoothness, np.float64(1.1))
# if (ng != 0):
# self.f[wg] = (self.kappa / np.log(smoothness[wg])) ** np.float64(2)
# if (nb != 0):
# self.f[wb] = np.float64(0)
#---------------------------------------------
# We could share the Fanning friction factor
#---------------------------------------------
### self.fanning = (np.float64(2) * self.f)
# update_friction_factor()
#-------------------------------------------------------------------
def update_velocity(self):
#---------------------------------------------------------
# Note: Do nothing now unless this method is overridden
# by a particular method of computing velocity.
#---------------------------------------------------------
print "Warning: update_velocity() method is inactive."
# print 'KINEMATIC WAVE =', self.KINEMATIC_WAVE
# print 'DIFFUSIVE WAVE =', self.DIFFUSIVE_WAVE
# print 'DYNAMIC WAVE =', self.DYNAMIC_WAVE
# update_velocity()
#-------------------------------------------------------------------
def update_velocity_on_edges(self):
#---------------------------------
# Force edge pixels to have u=0.
#----------------------------------------
# Large slope around 1 flows into small
# slope & leads to a negative velocity.
#----------------------------------------
self.u[ self.d8.noflow_IDs ] = np.float64(0)
# update_velocity_on_edges()
#-------------------------------------------------------------------
def update_froude_number(self):
#----------------------------------------------------------
# Notes: 9/9/14. Added so Froude number could be shared.
# This use of wg & wb reduced cProfile time from:
# 0.644 sec to: 0.121. (9/23/14)
#----------------------------------------------------------
# g = good, b = bad
#--------------------
wg = self.d_is_pos
wb = self.d_is_neg
self.froude[ wg ] = self.u[wg] / np.sqrt( self.g * self.d[wg] )
self.froude[ wb ] = np.float64(0)
# update_froude_number()
#-------------------------------------------------------------
def update_outlet_values(self):
#-------------------------------------------------
# Save computed values at outlet, which are used
# by the TopoFlow driver.
#-----------------------------------------------------
# Note that Q_outlet, etc. are defined as 0D numpy
# arrays to make them "mutable scalars" (i.e.
# this allows changes to be seen by other components
# who have a reference. To preserver the reference,
# however, we must use fill() to assign a new value.
#-----------------------------------------------------
Q_outlet = self.Q[ self.outlet_ID ]
u_outlet = self.u[ self.outlet_ID ]
d_outlet = self.d[ self.outlet_ID ]
f_outlet = self.f[ self.outlet_ID ]
self.Q_outlet.fill( Q_outlet )
self.u_outlet.fill( u_outlet )
self.d_outlet.fill( d_outlet )
self.f_outlet.fill( f_outlet )
## self.Q_outlet.fill( self.Q[ self.outlet_ID ] )
## self.u_outlet.fill( self.u[ self.outlet_ID ] )
## self.d_outlet.fill( self.d[ self.outlet_ID ] )
## self.f_outlet.fill( self.f[ self.outlet_ID ] )
## self.Q_outlet = self.Q[ self.outlet_ID ]
## self.u_outlet = self.u[ self.outlet_ID ]
## self.d_outlet = self.d[ self.outlet_ID ]
## self.f_outlet = self.f[ self.outlet_ID ]
## self.Q_outlet = self.Q.flat[self.outlet_ID]
## self.u_outlet = self.u.flat[self.outlet_ID]
## self.d_outlet = self.d.flat[self.outlet_ID]
## self.f_outlet = self.f.flat[self.outlet_ID]
# update_outlet_values()
#-------------------------------------------------------------
def update_peak_values(self):
if (self.Q_outlet > self.Q_peak):
self.Q_peak.fill( self.Q_outlet )
self.T_peak.fill( self.time_min ) # (time to peak)
#---------------------------------------
if (self.u_outlet > self.u_peak):
self.u_peak.fill( self.u_outlet )
self.Tu_peak.fill( self.time_min )
#---------------------------------------
if (self.d_outlet > self.d_peak):
self.d_peak.fill( self.d_outlet )
self.Td_peak.fill( self.time_min )
## if (self.Q_outlet > self.Q_peak):
## self.Q_peak = self.Q_outlet
## self.T_peak = self.time_min # (time to peak)
## #-----------------------------------
## if (self.u_outlet > self.u_peak):
## self.u_peak = self.u_outlet
## self.Tu_peak = self.time_min
## #-----------------------------------
## if (self.d_outlet > self.d_peak):
## self.d_peak = self.d_outlet
## self.Td_peak = self.time_min
# update_peak_values()
#-------------------------------------------------------------
def update_Q_out_integral(self):
#--------------------------------------------------------
# Note: Renamed "volume_out" to "vol_Q" for consistency
# with vol_P, vol_SM, vol_IN, vol_ET, etc. (5/18/12)
#--------------------------------------------------------
self.vol_Q += (self.Q_outlet * self.dt) ## Experiment: 5/19/12.
## self.vol_Q += (self.Q[self.outlet_ID] * self.dt)
# update_Q_out_integral()
#-------------------------------------------------------------
def update_mins_and_maxes(self, REPORT=False):
#--------------------------------------
# Get mins and max over entire domain
#--------------------------------------
## Q_min = self.Q.min()
## Q_max = self.Q.max()
## #---------------------
## u_min = self.u.min()
## u_max = self.u.max()
## #---------------------
## d_min = self.d.min()
## d_max = self.d.max()
#--------------------------------------------
# Exclude edges where mins are always zero.
#--------------------------------------------
nx = self.nx
ny = self.ny
Q_min = self.Q[1:(ny - 2)+1,1:(nx - 2)+1].min()
Q_max = self.Q[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
u_min = self.u[1:(ny - 2)+1,1:(nx - 2)+1].min()
u_max = self.u[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
d_min = self.d[1:(ny - 2)+1,1:(nx - 2)+1].min()
d_max = self.d[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
if (Q_min < self.Q_min):
self.Q_min.fill( Q_min )
if (Q_max > self.Q_max):
self.Q_max.fill( Q_max )
#------------------------------
if (u_min < self.u_min):
self.u_min.fill( u_min )
if (u_max > self.u_max):
self.u_max.fill( u_max )
#------------------------------
if (d_min < self.d_min):
self.d_min.fill( d_min )
if (d_max > self.d_max):
self.d_max.fill( d_max )
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
## self.Q_min.fill( np.minimum( self.Q_min, Q_min ) )
## self.Q_max.fill( np.maximum( self.Q_max, Q_max ) )
## #---------------------------------------------------
## self.u_min.fill( np.minimum( self.u_min, u_min ) )
## self.u_max.fill( np.maximum( self.u_max, u_max ) )
## #---------------------------------------------------
## self.d_min.fill( np.minimum( self.d_min, d_min ) )
## self.d_max.fill( np.maximum( self.d_max, d_max ) )
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
## self.Q_min.fill( min( self.Q_min, Q_min ) )
## self.Q_max.fill( max( self.Q_max, Q_max ) )
## #---------------------------------------------------
## self.u_min.fill( min( self.u_min, u_min ) )
## self.u_max.fill( max( self.u_max, u_max ) )
## #---------------------------------------------------
## self.d_min.fill( min( self.d_min, d_min ) )
## self.d_max.fill( max( self.d_max, d_max ) )
#----------------------------------------------
# (2/6/13) This produces "immutable scalars".
#----------------------------------------------
## self.Q_min = self.Q.min()
## self.Q_max = self.Q.max()
## self.u_min = self.u.min()
## self.u_max = self.u.max()
## self.d_min = self.d.min()
## self.d_max = self.d.max()
if (REPORT):
print 'In channels_base.update_mins_and_maxes():'
print '(dmin, dmax) =', self.d_min, self.d_max
print '(umin, umax) =', self.u_min, self.u_max
print '(Qmin, Qmax) =', self.Q_min, self.Q_max
print ' '
# update_mins_and_maxes()
#-------------------------------------------------------------------
def check_flow_depth(self):
OK = True
d = self.d
dt = self.dt
nx = self.nx #################
#---------------------------------
# All all flow depths positive ?
#---------------------------------
wbad = np.where( np.logical_or( d < 0.0, np.logical_not(np.isfinite(d)) ))
nbad = np.size( wbad[0] )
if (nbad == 0):
return OK
OK = False
dmin = d[wbad].min()
star_line = '*******************************************'
msg = [ star_line, \
'ERROR: Simulation aborted.', ' ', \
'Negative depth found: ' + str(dmin), \
'Time step may be too large.', \
'Time step: ' + str(dt) + ' [s]', ' ']
for k in xrange(len(msg)):
print msg[k]
#-------------------------------------------
# If not too many, print actual velocities
#-------------------------------------------
if (nbad < 30):
brow = wbad[0][0]
bcol = wbad[1][0]
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
crstr = str(bcol) + ', ' + str(brow)
msg = ['(Column, Row): ' + crstr, \
'Flow depth: ' + str(d[brow, bcol])]
for k in xrange(len(msg)):
print msg[k]
print star_line
print ' '
return OK
# check_flow_depth
#-------------------------------------------------------------------
def check_flow_velocity(self):
OK = True
u = self.u
dt = self.dt
nx = self.nx
#--------------------------------
# Are all velocities positive ?
#--------------------------------
wbad = np.where( np.logical_or( u < 0.0, np.logical_not(np.isfinite(u)) ))
nbad = np.size( wbad[0] )
if (nbad == 0):
return OK
OK = False
umin = u[wbad].min()
star_line = '*******************************************'
msg = [ star_line, \
'ERROR: Simulation aborted.', ' ', \
'Negative or NaN velocity found: ' + str(umin), \
'Time step may be too large.', \
'Time step: ' + str(dt) + ' [s]', ' ']
for k in xrange(len(msg)):
print msg[k]
#-------------------------------------------
# If not too many, print actual velocities
#-------------------------------------------
if (nbad < 30):
brow = wbad[0][0]
bcol = wbad[1][0]
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
crstr = str(bcol) + ', ' + str(brow)
msg = ['(Column, Row): ' + crstr, \
'Velocity: ' + str(u[brow, bcol])]
for k in xrange(len(msg)):
print msg[k]
print star_line
print ' '
return OK
## umin = u[wbad].min()
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
## crstr = str(bcol) + ', ' + str(brow)
## msg = np.array([' ', \
## '*******************************************', \
## 'ERROR: Simulation aborted.', ' ', \
## 'Negative velocity found: ' + str(umin), \
## 'Time step may be too large.', ' ', \
## '(Column, Row): ' + crstr, \
## 'Velocity: ' + str(u[badi]), \
## 'Time step: ' + str(dt) + ' [s]', \
## '*******************************************', ' '])
## for k in xrange( np.size(msg) ):
## print msg[k]
## return OK
# check_flow_velocity
#-------------------------------------------------------------------
def open_input_files(self):
# This doesn't work, because file_unit doesn't get full path. (10/28/11)
# start_dir = os.getcwd()
# os.chdir( self.in_directory )
# print '### start_dir =', start_dir
# print '### in_directory =', self.in_directory
in_files = ['slope_file', 'nval_file', 'z0val_file',
'width_file', 'angle_file', 'sinu_file', 'd0_file']
self.prepend_directory( in_files, INPUT=True )
# self.slope_file = self.in_directory + self.slope_file
# self.nval_file = self.in_directory + self.nval_file
# self.z0val_file = self.in_directory + self.z0val_file
# self.width_file = self.in_directory + self.width_file
# self.angle_file = self.in_directory + self.angle_file
# self.sinu_file = self.in_directory + self.sinu_file
# self.d0_file = self.in_directory + self.d0_file
#self.code_unit = model_input.open_file(self.code_type, self.code_file)
self.slope_unit = model_input.open_file(self.slope_type, self.slope_file)
if (self.MANNING):
self.nval_unit = model_input.open_file(self.nval_type, self.nval_file)
if (self.LAW_OF_WALL):
self.z0val_unit = model_input.open_file(self.z0val_type, self.z0val_file)
self.width_unit = model_input.open_file(self.width_type, self.width_file)
self.angle_unit = model_input.open_file(self.angle_type, self.angle_file)
self.sinu_unit = model_input.open_file(self.sinu_type, self.sinu_file)
self.d0_unit = model_input.open_file(self.d0_type, self.d0_file)
# os.chdir( start_dir )
# open_input_files()
#-------------------------------------------------------------------
def read_input_files(self):
#---------------------------------------------------
# The flow codes are always a grid, size of DEM.
#---------------------------------------------------
# NB! model_input.py also has a read_grid() function.
#---------------------------------------------------
rti = self.rti
## print 'Reading D8 flow grid (in CHANNELS)...'
## self.code = rtg_files.read_grid(self.code_file, rti,
## RTG_type='BYTE')
## print ' '
#-------------------------------------------------------
# All grids are assumed to have a data type of Float32.
#-------------------------------------------------------
slope = model_input.read_next(self.slope_unit, self.slope_type, rti)
if (slope != None): self.slope = slope
# If EOF was reached, hopefully numpy's "fromfile"
# returns None, so that the stored value will be
# the last value that was read.
if (self.MANNING):
nval = model_input.read_next(self.nval_unit, self.nval_type, rti)
if (nval != None):
self.nval = nval
self.nval_min = nval.min()
self.nval_max = nval.max()
if (self.LAW_OF_WALL):
z0val = model_input.read_next(self.z0val_unit, self.z0val_type, rti)
if (z0val != None):
self.z0val = z0val
self.z0val_min = z0val.min()
self.z0val_max = z0val.max()
width = model_input.read_next(self.width_unit, self.width_type, rti)
if (width != None): self.width = width
angle = model_input.read_next(self.angle_unit, self.angle_type, rti)
if (angle != None):
#-----------------------------------------------
# Convert bank angles from degrees to radians.
#-----------------------------------------------
self.angle = angle * self.deg_to_rad # [radians]
### self.angle = angle # (before 9/9/14)
sinu = model_input.read_next(self.sinu_unit, self.sinu_type, rti)
if (sinu != None): self.sinu = sinu
d0 = model_input.read_next(self.d0_unit, self.d0_type, rti)
if (d0 != None): self.d0 = d0
## code = model_input.read_grid(self.code_unit, \
## self.code_type, rti, dtype='UInt8')
## if (code != None): self.code = code
# read_input_files()
#-------------------------------------------------------------------
def close_input_files(self):
# if not(self.slope_unit.closed):
# if (self.slope_unit != None):
#-------------------------------------------------
# NB! self.code_unit was never defined as read.
#-------------------------------------------------
# if (self.code_type != 'scalar'): self.code_unit.close()
if (self.slope_type != 'Scalar'): self.slope_unit.close()
if (self.MANNING):
if (self.nval_type != 'Scalar'): self.nval_unit.close()
if (self.LAW_OF_WALL):
if (self.z0val_type != 'Scalar'): self.z0val_unit.close()
if (self.width_type != 'Scalar'): self.width_unit.close()
if (self.angle_type != 'Scalar'): self.angle_unit.close()
if (self.sinu_type != 'Scalar'): self.sinu_unit.close()
if (self.d0_type != 'Scalar'): self.d0_unit.close()
## if (self.slope_file != ''): self.slope_unit.close()
## if (self.MANNING):
## if (self.nval_file != ''): self.nval_unit.close()
## if (self.LAW_OF_WALL):
## if (self.z0val_file != ''): self.z0val_unit.close()
## if (self.width_file != ''): self.width_unit.close()
## if (self.angle_file != ''): self.angle_unit.close()
## if (self.sinu_file != ''): self.sinu_unit.close()
## if (self.d0_file != ''): self.d0_unit.close()
# close_input_files()
#-------------------------------------------------------------------
def update_outfile_names(self):
#-------------------------------------------------
# Notes: Append out_directory to outfile names.
#-------------------------------------------------
self.Q_gs_file = (self.out_directory + self.Q_gs_file)
self.u_gs_file = (self.out_directory + self.u_gs_file)
self.d_gs_file = (self.out_directory + self.d_gs_file)
self.f_gs_file = (self.out_directory + self.f_gs_file)
#--------------------------------------------------------
self.Q_ts_file = (self.out_directory + self.Q_ts_file)
self.u_ts_file = (self.out_directory + self.u_ts_file)
self.d_ts_file = (self.out_directory + self.d_ts_file)
self.f_ts_file = (self.out_directory + self.f_ts_file)
# update_outfile_names()
#-------------------------------------------------------------------
def bundle_output_files(self):
###################################################
# NOT READY YET. Need "get_long_name()" and a new
# version of "get_var_units". (9/21/14)
###################################################
#-------------------------------------------------------------
# Bundle the output file info into an array for convenience.
# Then we just need one open_output_files(), in BMI_base.py,
# and one close_output_files(). Less to maintain. (9/21/14)
#-------------------------------------------------------------
# gs = grid stack, ts = time series, ps = profile series.
#-------------------------------------------------------------
self.out_files = [
{var_name:'Q',
save_gs:self.SAVE_Q_GRIDS, gs_file:self.Q_gs_file,
save_ts:self.SAVE_Q_PIXELS, ts_file:self.Q_ts_file,
long_name:get_long_name('Q'), units_name:get_var_units('Q')},
#-----------------------------------------------------------------
{var_name:'u',
save_gs:self.SAVE_U_GRIDS, gs_file:self.u_gs_file,
save_ts:self.SAVE_U_PIXELS, ts_file:self.u_ts_file,
long_name:get_long_name('u'), units_name:get_var_units('u')},
#-----------------------------------------------------------------
{var_name:'d',
save_gs:self.SAVE_D_GRIDS, gs_file:self.d_gs_file,
save_ts:self.SAVE_D_PIXELS, ts_file:self.d_ts_file,
long_name:get_long_name('d'), units_name:get_var_units('d')},
#-----------------------------------------------------------------
{var_name:'f',
save_gs:self.SAVE_F_GRIDS, gs_file:self.f_gs_file,
save_ts:self.SAVE_F_PIXELS, ts_file:self.f_ts_file,
long_name:get_long_name('f'), units_name:get_var_units('f')} ]
# bundle_output_files
#-------------------------------------------------------------------
def open_output_files(self):
model_output.check_netcdf()
self.update_outfile_names()
## self.bundle_output_files()
## print 'self.SAVE_Q_GRIDS =', self.SAVE_Q_GRIDS
## print 'self.SAVE_U_GRIDS =', self.SAVE_U_GRIDS
## print 'self.SAVE_D_GRIDS =', self.SAVE_D_GRIDS
## print 'self.SAVE_F_GRIDS =', self.SAVE_F_GRIDS
## #---------------------------------------------------
## print 'self.SAVE_Q_PIXELS =', self.SAVE_Q_PIXELS
## print 'self.SAVE_U_PIXELS =', self.SAVE_U_PIXELS
## print 'self.SAVE_D_PIXELS =', self.SAVE_D_PIXELS
## print 'self.SAVE_F_PIXELS =', self.SAVE_F_PIXELS
# IDs = self.outlet_IDs
# for k in xrange( len(self.out_files) ):
# #--------------------------------------
# # Open new files to write grid stacks
# #--------------------------------------
# if (self.out_files[k].save_gs):
# model_output.open_new_gs_file( self, self.out_files[k], self.rti )
# #--------------------------------------
# # Open new files to write time series
# #--------------------------------------
# if (self.out_files[k].save_ts):
# model_output.open_new_ts_file( self, self.out_files[k], IDs )
#--------------------------------------
# Open new files to write grid stacks
#--------------------------------------
if (self.SAVE_Q_GRIDS):
model_output.open_new_gs_file( self, self.Q_gs_file, self.rti,
var_name='Q',
long_name='volumetric_discharge',
units_name='m^3/s')
if (self.SAVE_U_GRIDS):
model_output.open_new_gs_file( self, self.u_gs_file, self.rti,
var_name='u',
long_name='mean_channel_flow_velocity',
units_name='m/s')
if (self.SAVE_D_GRIDS):
model_output.open_new_gs_file( self, self.d_gs_file, self.rti,
var_name='d',
long_name='max_channel_flow_depth',
units_name='m')
if (self.SAVE_F_GRIDS):
model_output.open_new_gs_file( self, self.f_gs_file, self.rti,
var_name='f',
long_name='friction_factor',
units_name='none')
#--------------------------------------
# Open new files to write time series
#--------------------------------------
IDs = self.outlet_IDs
if (self.SAVE_Q_PIXELS):
model_output.open_new_ts_file( self, self.Q_ts_file, IDs,
var_name='Q',
long_name='volumetric_discharge',
units_name='m^3/s')
if (self.SAVE_U_PIXELS):
model_output.open_new_ts_file( self, self.u_ts_file, IDs,
var_name='u',
long_name='mean_channel_flow_velocity',
units_name='m/s')
if (self.SAVE_D_PIXELS):
model_output.open_new_ts_file( self, self.d_ts_file, IDs,
var_name='d',
long_name='max_channel_flow_depth',
units_name='m')
if (self.SAVE_F_PIXELS):
model_output.open_new_ts_file( self, self.f_ts_file, IDs,
var_name='f',
long_name='friction_factor',
units_name='none')
# open_output_files()
#-------------------------------------------------------------------
def write_output_files(self, time_seconds=None):
#---------------------------------------------------------
# Notes: This function was written to use only model
# time (maybe from a caller) in seconds, and
# the save_grid_dt and save_pixels_dt parameters
# read by read_cfg_file().
#
# read_cfg_file() makes sure that all of
# the "save_dts" are larger than or equal to the
# process dt.
#---------------------------------------------------------
#-----------------------------------------
# Allows time to be passed from a caller
#-----------------------------------------
if (time_seconds is None):
time_seconds = self.time_sec
model_time = int(time_seconds)
#----------------------------------------
# Save computed values at sampled times
#----------------------------------------
if (model_time % int(self.save_grid_dt) == 0):
self.save_grids()
if (model_time % int(self.save_pixels_dt) == 0):
self.save_pixel_values()
#----------------------------------------
# Save computed values at sampled times
#----------------------------------------
## if ((self.time_index % self.grid_save_step) == 0):
## self.save_grids()
## if ((self.time_index % self.pixel_save_step) == 0):
## self.save_pixel_values()
# write_output_files()
#-------------------------------------------------------------------
def close_output_files(self):
if (self.SAVE_Q_GRIDS): model_output.close_gs_file( self, 'Q')
if (self.SAVE_U_GRIDS): model_output.close_gs_file( self, 'u')
if (self.SAVE_D_GRIDS): model_output.close_gs_file( self, 'd')
if (self.SAVE_F_GRIDS): model_output.close_gs_file( self, 'f')
#---------------------------------------------------------------
if (self.SAVE_Q_PIXELS): model_output.close_ts_file( self, 'Q')
if (self.SAVE_U_PIXELS): model_output.close_ts_file( self, 'u')
if (self.SAVE_D_PIXELS): model_output.close_ts_file( self, 'd')
if (self.SAVE_F_PIXELS): model_output.close_ts_file( self, 'f')
# close_output_files()
#-------------------------------------------------------------------
def save_grids(self):
#-----------------------------------
# Save grid stack to a netCDF file
#---------------------------------------------
# Note that add_grid() methods will convert
# var from scalar to grid now, if necessary.
#---------------------------------------------
if (self.SAVE_Q_GRIDS):
model_output.add_grid( self, self.Q, 'Q', self.time_min )
if (self.SAVE_U_GRIDS):
model_output.add_grid( self, self.u, 'u', self.time_min )
if (self.SAVE_D_GRIDS):
model_output.add_grid( self, self.d, 'd', self.time_min )
if (self.SAVE_F_GRIDS):
model_output.add_grid( self, self.f, 'f', self.time_min )
# save_grids()
#-------------------------------------------------------------------
def save_pixel_values(self): ##### save_time_series_data(self) #######
IDs = self.outlet_IDs
time = self.time_min #####
#-------------
# New method
#-------------
if (self.SAVE_Q_PIXELS):
model_output.add_values_at_IDs( self, time, self.Q, 'Q', IDs )
if (self.SAVE_U_PIXELS):
model_output.add_values_at_IDs( self, time, self.u, 'u', IDs )
if (self.SAVE_D_PIXELS):
model_output.add_values_at_IDs( self, time, self.d, 'd', IDs )
if (self.SAVE_F_PIXELS):
model_output.add_values_at_IDs( self, time, self.f, 'f', IDs )
# save_pixel_values()
#-------------------------------------------------------------------
def manning_formula(self):
#---------------------------------------------------------
# Notes: R = (A/P) = hydraulic radius [m]
# N = Manning's roughness coefficient
# (usually in the range 0.012 to 0.035)
# S = bed slope or free slope
# R,S, and N may be 2D arrays.
# If length units are all *feet*, then an extra
# factor of 1.49 must be applied. If units are
# meters, no such factor is needed.
# Note that Q = Ac * u, where Ac is cross-section
# area. For a trapezoid, Ac does not equal w*d.
#---------------------------------------------------------
if (self.KINEMATIC_WAVE):
S = self.S_bed
else:
S = self.S_free
u = (self.Rh ** self.two_thirds) * np.sqrt(S) / self.nval
#--------------------------------------------------------
# Add a hydraulic jump option for when u gets too big ?
#--------------------------------------------------------
return u
# manning_formula()
#-------------------------------------------------------------------
def law_of_the_wall(self):
#---------------------------------------------------------
# Notes: u = flow velocity [m/s]
# d = flow depth [m]
# z0 = roughness length
# S = bed slope or free slope
# g = 9.81 = gravitation constant [m/s^2]
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# law_const = sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
#########################################################
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
if (self.KINEMATIC_WAVE):
S = self.S_bed
else:
S = self.S_free
smoothness = (self.aval / self.z0val) * self.d
#------------------------------------------------
# Make sure (smoothness > 1) before taking log.
# Should issue a warning if this is used.
#------------------------------------------------
smoothness = np.maximum(smoothness, np.float64(1.1))
u = self.law_const * np.sqrt(self.Rh * S) * np.log(smoothness)
#--------------------------------------------------------
# Add a hydraulic jump option for when u gets too big ?
#--------------------------------------------------------
return u
# law_of_the_wall()
#-------------------------------------------------------------------
def print_status_report(self):
#----------------------------------------------------
# Wherever depth is less than z0, assume that water
# is not flowing and set u and Q to zero.
# However, we also need (d gt 0) to avoid a divide
# by zero problem, even when numerators are zero.
#----------------------------------------------------
# FLOWING = (d > (z0/aval))
#*** FLOWING[noflow_IDs] = False ;******
wflow = np.where( FLOWING != 0 )
n_flow = np.size( wflow[0] )
n_pixels = self.rti.n_pixels
percent = np.float64(100.0) * (np.float64(n_flow) / n_pixels)
fstr = ('%5.1f' % percent) + '%'
# fstr = idl_func.string(percent, format='(F5.1)').strip() + '%'
print ' Percentage of pixels with flow = ' + fstr
print ' '
self.update_mins_and_maxes(REPORT=True)
wmax = np.where(self.Q == self.Q_max)
nwmax = np.size(wmax[0])
print ' Max(Q) occurs at: ' + str( wmax[0] )
#print,' Max attained at ', nwmax, ' pixels.'
print ' '
print '-------------------------------------------------'
# print_status_report()
#-------------------------------------------------------------------
def remove_bad_slopes(self, FLOAT=False):
#------------------------------------------------------------
# Notes: The main purpose of this routine is to find
# pixels that have nonpositive slopes and replace
# then with the smallest value that occurs anywhere
# in the input slope grid. For example, pixels on
# the edges of the DEM will have a slope of zero.
# With the Kinematic Wave option, flow cannot leave
# a pixel that has a slope of zero and the depth
# increases in an unrealistic manner to create a
# spike in the depth grid.
# It would be better, of course, if there were
# no zero-slope pixels in the DEM. We could use
# an "Imposed gradient DEM" to get slopes or some
# method of "profile smoothing".
# It is possible for the flow code to be nonzero
# at a pixel that has NaN for its slope. For these
# pixels, we also set the slope to our min value.
# 7/18/05. Broke this out into separate procedure.
#------------------------------------------------------------
#-----------------------------------
# Are there any "bad" pixels ?
# If not, return with no messages.
#-----------------------------------
wb = np.where(np.logical_or((self.slope <= 0.0), \
np.logical_not(np.isfinite(self.slope))))
nbad = np.size(wb[0])
print 'size(slope) =', np.size(self.slope)
print 'size(wb) =', nbad
wg = np.where(np.invert(np.logical_or((self.slope <= 0.0), \
np.logical_not(np.isfinite(self.slope)))))
ngood = np.size(wg[0])
if (nbad == 0) or (ngood == 0):
return
#---------------------------------------------
# Find smallest positive value in slope grid
# and replace the "bad" values with smin.
#---------------------------------------------
print '-------------------------------------------------'
print 'WARNING: Zero or negative slopes found.'
print ' Replacing them with smallest slope.'
print ' Use "Profile smoothing tool" instead.'
S_min = self.slope[wg].min()
S_max = self.slope[wg].max()
print ' min(S) = ' + str(S_min)
print ' max(S) = ' + str(S_max)
print '-------------------------------------------------'
print ' '
self.slope[wb] = S_min
#--------------------------------
# Convert data type to double ?
#--------------------------------
if (FLOAT):
self.slope = np.float32(self.slope)
else:
self.slope = np.float64(self.slope)
# remove_bad_slopes
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def Trapezoid_Rh(d, wb, theta):
#-------------------------------------------------------------
# Notes: Compute the hydraulic radius of a trapezoid that:
# (1) has a bed width of wb >= 0 (0 for triangular)
# (2) has a bank angle of theta (0 for rectangular)
# (3) is filled with water to a depth of d.
# The units of wb and d are meters. The units of
# theta are assumed to be degrees and are converted.
#-------------------------------------------------------------
# NB! wb should never be zero, so PW can never be 0,
# which would produce a NaN (divide by zero).
#-------------------------------------------------------------
# See Notes for TF_Tan function in utils_TF.pro
# AW = d * (wb + (d * TF_Tan(theta_rad)) )
#-------------------------------------------------------------
theta_rad = (theta * np.pi / 180.0)
AW = d * (wb + (d * np.tan(theta_rad)) )
PW = wb + (np.float64(2) * d / np.cos(theta_rad) )
Rh = (AW / PW)
w = np.where(wb <= 0)
nw = np.size(w[0])
return Rh
# Trapezoid_Rh()
#-------------------------------------------------------------------
def Manning_Formula(Rh, S, nval):
#---------------------------------------------------------
# Notes: R = (A/P) = hydraulic radius [m]
# N = Manning's roughness coefficient
# (usually in the range 0.012 to 0.035)
# S = bed slope (assumed equal to friction slope)
# R,S, and N may be 2D arrays.
# If length units are all *feet*, then an extra
# factor of 1.49 must be applied. If units are
# meters, no such factor is needed.
# Note that Q = Ac * u, where Ac is cross-section
# area. For a trapezoid, Ac does not equal w*d.
#---------------------------------------------------------
## if (N == None): N = np.float64(0.03)
two_thirds = np.float64(2) / 3.0
u = (Rh ** two_thirds) * np.sqrt(S) / nval
#------------------------------
# Add a hydraulic jump option
# for when u gets too big ??
#------------------------------
return u
# Manning_Formula()
#-------------------------------------------------------------------
def Law_of_the_Wall(d, Rh, S, z0val):
#---------------------------------------------------------
# Notes: u = flow velocity [m/s]
# d = flow depth [m]
# z0 = roughness height
# S = bed slope (assumed equal to friction slope)
# g = 9.81 = gravitation constant [m/s^2]
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
## if (self.z0val == None):
## self.z0val = np.float64(0.011417) # (about 1 cm)
#------------------------
# Define some constants
#------------------------
g = np.float64(9.81) # (gravitation const.)
aval = np.float64(0.476) # (integration const.)
kappa = np.float64(0.408) # (von Karman's const.)
law_const = np.sqrt(g) / kappa
smoothness = (aval / z0val) * d
#-----------------------------
# Make sure (smoothness > 1)
#-----------------------------
smoothness = np.maximum(smoothness, np.float64(1.1))
u = law_const * np.sqrt(Rh * S) * np.log(smoothness)
#------------------------------
# Add a hydraulic jump option
# for when u gets too big ??
#------------------------------
return u | mperignon/component_creator | topoflow_creator/topoflow/channels_base.py | Python | gpl-2.0 | 124,876 |
#include <QDebug>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include "monitor.h"
Monitor::Monitor()
{
running = 0;
}
void Monitor::start()
{
int rc;
int s;
fd_set rdfs;
int nbytes;
struct sockaddr_can addr;
struct canfd_frame frame;
struct iovec iov;
char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
struct msghdr msg;
struct ifreq ifr;
char* ifname = "can0";
running = 1;
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (s < 0)
{
qDebug() << "Error opening socket: " << s;
stop();
return;
}
strcpy(ifr.ifr_name, ifname);
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
rc = bind(s, (struct sockaddr*)&addr, sizeof(addr));
if (rc < 0)
{
qDebug() << "Error binding to interface: " << rc;
stop();
return;
}
iov.iov_base = &frame;
msg.msg_name = &addr;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &ctrlmsg;
while (running)
{
FD_ZERO(&rdfs);
FD_SET(s, &rdfs);
rc = select(s, &rdfs, NULL, NULL, NULL);
if (rc < 0)
{
qDebug() << "Error calling select" << rc;
stop();
continue;
}
if (FD_ISSET(s, &rdfs))
{
int maxdlen;
// These can apparently get changed, so set before each read
iov.iov_len = sizeof(frame);
msg.msg_namelen = sizeof(addr);
msg.msg_controllen = sizeof(ctrlmsg);
msg.msg_flags = 0;
nbytes = recvmsg(s, &msg, 0);
if (nbytes < 0)
{
qDebug() << "Error calling recvmsg : " << nbytes;
stop();
continue;
}
if ((size_t)nbytes == CAN_MTU)
maxdlen = CAN_MAX_DLEN;
else if ((size_t)nbytes == CANFD_MTU)
maxdlen = CANFD_MAX_DLEN;
else
{
qDebug() << "Warning: read incomplete CAN frame : " << nbytes;
continue;
}
// TODO get timestamp from message
sendMsg(&frame, maxdlen);
}
}
}
void Monitor::stop()
{
running = 0;
}
void Monitor::sendMsg(struct canfd_frame *frame, int maxdlen)
{
canMessage msg;
char buf[200];
int pBuf = 0;
int i;
int len = (frame->len > maxdlen) ? maxdlen : frame->len;
msg.interface = 1; // TODO set in constructor at some point
msg.identifier = QString("%1:%03X")
.arg(msg.interface)
.arg(frame->can_id & CAN_SFF_MASK);
msg.time = QTime::currentTime();
pBuf += sprintf(buf + pBuf, "[%d]", frame->len);
if (frame->can_id & CAN_RTR_FLAG)
{
pBuf += sprintf(buf + pBuf, " remote request");
emit messageInBuffer(&msg);
return;
}
for (i = 0; i < len; i++)
{
pBuf += sprintf(buf + pBuf, " [%02X]", frame->data[i]);
}
msg.content = QString("%1").arg(buf);
emit messageInBuffer(&msg);
}
| timrule/qt-projects | canmon/monitor.cpp | C++ | gpl-2.0 | 2,638 |
using System;
using Server;
using Server.Gumps;
using Server.Network;
namespace Server.Items
{
public class PowerScroll : Item
{
private SkillName m_Skill;
private double m_Value;
private static SkillName[] m_Skills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking
};
private static SkillName[] m_AOSSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak
};
private static SkillName[] m_SESkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido
};
private static SkillName[] m_MLSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido,
SkillName.Spellweaving
};
public static SkillName[] Skills{ get{ return ( Core.ML ? m_MLSkills : Core.SE ? m_SESkills : Core.AOS ? m_AOSSkills : m_Skills ); } }
public static PowerScroll CreateRandom( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
return new PowerScroll( skills[Utility.Random( skills.Length )], 100 + (Utility.RandomMinMax( min, max ) * 5));
}
public static PowerScroll CreateRandomNoCraft( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
SkillName skillName;
do
{
skillName = skills[Utility.Random( skills.Length )];
} while ( skillName == SkillName.Blacksmith || skillName == SkillName.Tailoring );
return new PowerScroll( skillName, 100 + (Utility.RandomMinMax( min, max ) * 5));
}
[Constructable]
public PowerScroll( SkillName skill, double value ) : base( 0x14F0 )
{
base.Hue = 0x481;
base.Weight = 1.0;
m_Skill = skill;
m_Value = value;
if ( m_Value > 105.0 )
LootType = LootType.Cursed;
}
public PowerScroll( Serial serial ) : base( serial )
{
}
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill
{
get
{
return m_Skill;
}
set
{
m_Skill = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public double Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
}
}
private string GetNameLocalized()
{
return String.Concat( "#", (1044060 + (int)m_Skill).ToString() );
}
private string GetName()
{
int index = (int)m_Skill;
SkillInfo[] table = SkillInfo.Table;
if ( index >= 0 && index < table.Length )
return table[index].Name.ToLower();
else
return "???";
}
public override void AddNameProperty(ObjectPropertyList list)
{
if ( m_Value == 105.0 )
list.Add( 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
list.Add( 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
list.Add( 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
list.Add( 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
list.Add( "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public override void OnSingleClick( Mobile from )
{
if ( m_Value == 105.0 )
base.LabelTo( from, 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
base.LabelTo( from, 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
base.LabelTo( from, 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
base.LabelTo( from, 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
base.LabelTo( from, "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public void Use( Mobile from, bool firstStage )
{
if ( Deleted )
return;
if ( IsChildOf( from.Backpack ) )
{
Skill skill = from.Skills[m_Skill];
if ( skill != null )
{
if ( skill.Cap >= m_Value )
{
from.SendLocalizedMessage( 1049511, GetNameLocalized() ); // Your ~1_type~ is too high for this power scroll.
}
else
{
if ( firstStage )
{
from.CloseGump( typeof( StatCapScroll.InternalGump ) );
from.CloseGump( typeof( PowerScroll.InternalGump ) );
from.SendGump( new InternalGump( from, this ) );
}
else
{
from.SendLocalizedMessage( 1049513, GetNameLocalized() ); // You feel a surge of magic as the scroll enhances your ~1_type~!
skill.Cap = m_Value;
Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 );
Effects.PlaySound( from.Location, from.Map, 0x243 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 4, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 4, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 );
Delete();
}
}
}
}
else
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
}
public override void OnDoubleClick( Mobile from )
{
Use( from, true );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( (int) m_Skill );
writer.Write( (double) m_Value );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Skill = (SkillName)reader.ReadInt();
m_Value = reader.ReadDouble();
break;
}
}
if ( m_Value == 105.0 )
{
LootType = LootType.Regular;
}
else
{
LootType = LootType.Cursed;
if ( Insured )
Insured = false;
}
}
public class InternalGump : Gump
{
private Mobile m_Mobile;
private PowerScroll m_Scroll;
public InternalGump( Mobile mobile, PowerScroll scroll ) : base( 25, 50 )
{
m_Mobile = mobile;
m_Scroll = scroll;
AddPage( 0 );
AddBackground( 25, 10, 420, 200, 5054 );
AddImageTiled( 33, 20, 401, 181, 2624 );
AddAlphaRegion( 33, 20, 401, 181 );
AddHtmlLocalized( 40, 48, 387, 100, 1049469, true, true ); /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics.
* When used, the effect is not immediately seen without a gain of points with that skill or statistics.
* You can view your maximum skill values in your skills window.
* You can view your maximum statistic value in your statistics window.
*/
AddHtmlLocalized( 125, 148, 200, 20, 1049478, 0xFFFFFF, false, false ); // Do you wish to use this scroll?
AddButton( 100, 172, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 135, 172, 120, 20, 1046362, 0xFFFFFF, false, false ); // Yes
AddButton( 275, 172, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 310, 172, 120, 20, 1046363, 0xFFFFFF, false, false ); // No
double value = scroll.m_Value;
if ( value == 105.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049635, 0xFFFFFF, false, false ); // Wonderous Scroll (105 Skill):
else if ( value == 110.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049636, 0xFFFFFF, false, false ); // Exalted Scroll (110 Skill):
else if ( value == 115.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049637, 0xFFFFFF, false, false ); // Mythical Scroll (115 Skill):
else if ( value == 120.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049638, 0xFFFFFF, false, false ); // Legendary Scroll (120 Skill):
else
AddHtml( 40, 20, 260, 20, String.Format( "<basefont color=#FFFFFF>Power Scroll ({0} Skill):</basefont>", value ), false, false );
AddHtmlLocalized( 310, 20, 120, 20, 1044060 + (int)scroll.m_Skill, 0xFFFFFF, false, false );
}
public override void OnResponse( NetState state, RelayInfo info )
{
if ( info.ButtonID == 1 )
m_Scroll.Use( m_Mobile, false );
}
}
}
} | alucardxlx/kaltar | Scripts/Items/Special/Special Scrolls/PowerScroll.cs | C# | gpl-2.0 | 11,516 |
from django.db import models
from django.contrib.auth.models import User
class OrganisationType(models.Model):
type_desc = models.CharField(max_length=200)
def __unicode__(self):
return self.type_desc
class Address(models.Model):
street_address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
pin = models.CharField(max_length=10)
province = models.CharField(max_length=100)
nationality = models.CharField(max_length=100)
def __unicode__(self):
return self.street_address + ',' + self.city
class HattiUser(models.Model):
user = models.OneToOneField(User)
address = models.ForeignKey(Address)
telephone = models.CharField(max_length=500)
date_joined = models.DateTimeField(auto_now_add=True)
fax = models.CharField(max_length=100)
avatar = models.CharField(max_length=100, null=True, blank=True)
tagline = models.CharField(max_length=140)
class Meta:
abstract = True
class AdminOrganisations(HattiUser):
title = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationType)
def __unicode__(self):
return self.title
class Customer(HattiUser):
title = models.CharField(max_length=200, blank=True, null=True)
is_org = models.BooleanField();
org_type = models.ForeignKey(OrganisationType)
company = models.CharField(max_length = 200)
def __unicode__(self, arg):
return unicode(self.user)
| saloni10/librehatti_new | src/authentication/models.py | Python | gpl-2.0 | 1,479 |
/****************************************************************************************
* Copyright (c) 2010 Maximilian Kossick <maximilian.kossick@googlemail.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 "TestUnionJob.h"
#include "core/support/Debug.h"
#include "core/collections/CollectionLocation.h"
#include "synchronization/UnionJob.h"
#include "CollectionTestImpl.h"
#include "mocks/MockTrack.h"
#include "mocks/MockAlbum.h"
#include "mocks/MockArtist.h"
#include <KCmdLineArgs>
#include <KGlobal>
#include <QList>
#include <qtest_kde.h>
#include <gmock/gmock.h>
QTEST_KDEMAIN_CORE( TestUnionJob )
using ::testing::Return;
using ::testing::AnyNumber;
static QList<int> trackCopyCount;
namespace Collections {
class MyCollectionLocation : public CollectionLocation
{
public:
Collections::CollectionTestImpl *coll;
QString prettyLocation() const { return "foo"; }
bool isWritable() const { return true; }
bool remove( const Meta::TrackPtr &track )
{
coll->mc->acquireWriteLock();
//theoretically we should clean up the other maps as well...
TrackMap map = coll->mc->trackMap();
map.remove( track->uidUrl() );
coll->mc->setTrackMap( map );
coll->mc->releaseLock();
return true;
}
void copyUrlsToCollection(const QMap<Meta::TrackPtr, KUrl> &sources, const Transcoding::Configuration& conf)
{
Q_UNUSED( conf )
trackCopyCount << sources.count();
foreach( const Meta::TrackPtr &track, sources.keys() )
{
coll->mc->addTrack( track );
}
}
};
class MyCollectionTestImpl : public CollectionTestImpl
{
public:
MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {}
CollectionLocation* location() const
{
MyCollectionLocation *r = new MyCollectionLocation();
r->coll = const_cast<MyCollectionTestImpl*>( this );
return r;
}
};
} //namespace Collections
void addMockTrack( Collections::CollectionTestImpl *coll, const QString &trackName, const QString &artistName, const QString &albumName )
{
Meta::MockTrack *track = new Meta::MockTrack();
::testing::Mock::AllowLeak( track );
Meta::TrackPtr trackPtr( track );
EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) );
EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + "_" + artistName + "_" + albumName ) );
EXPECT_CALL( *track, isPlayable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) );
EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( KUrl( '/' + track->uidUrl() ) ) );
coll->mc->addTrack( trackPtr );
Meta::AlbumPtr albumPtr = coll->mc->albumMap().value( albumName );
Meta::MockAlbum *album;
Meta::TrackList albumTracks;
if( albumPtr )
{
album = dynamic_cast<Meta::MockAlbum*>( albumPtr.data() );
if( !album )
{
QFAIL( "expected a Meta::MockAlbum" );
return;
}
albumTracks = albumPtr->tracks();
}
else
{
album = new Meta::MockAlbum();
::testing::Mock::AllowLeak( album );
albumPtr = Meta::AlbumPtr( album );
EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) );
EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) );
EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) );
coll->mc->addAlbum( albumPtr );
}
albumTracks << trackPtr;
EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) );
EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) );
Meta::ArtistPtr artistPtr = coll->mc->artistMap().value( artistName );
Meta::MockArtist *artist;
Meta::TrackList artistTracks;
if( artistPtr )
{
artist = dynamic_cast<Meta::MockArtist*>( artistPtr.data() );
if( !artist )
{
QFAIL( "expected a Meta::MockArtist" );
return;
}
artistTracks = artistPtr->tracks();
}
else
{
artist = new Meta::MockArtist();
::testing::Mock::AllowLeak( artist );
artistPtr = Meta::ArtistPtr( artist );
EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) );
coll->mc->addArtist( artistPtr );
}
artistTracks << trackPtr;
EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) );
EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) );
}
TestUnionJob::TestUnionJob() : QObject()
{
KCmdLineArgs::init( KGlobal::activeComponent().aboutData() );
::testing::InitGoogleMock( &KCmdLineArgs::qtArgc(), KCmdLineArgs::qtArgv() );
qRegisterMetaType<Meta::TrackList>();
qRegisterMetaType<Meta::AlbumList>();
qRegisterMetaType<Meta::ArtistList>();
}
void
TestUnionJob::init()
{
trackCopyCount.clear();
}
void
TestUnionJob::testEmptyA()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collB, "track1", "artist1", "album1" );
QCOMPARE( collA->mc->trackMap().count(), 0 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
delete collA;
delete collB;
}
void
TestUnionJob::testEmptyB()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 0 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
delete collA;
delete collB;
}
void
TestUnionJob::testAddTrackToBoth()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
addMockTrack( collB, "track2", "artist2", "album2" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 2 );
QCOMPARE( trackCopyCount.at( 0 ), 1 );
QCOMPARE( trackCopyCount.at( 1 ), 1 );
QCOMPARE( collA->mc->trackMap().count(), 2 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
delete collA;
delete collB;
}
void
TestUnionJob::testTrackAlreadyInBoth()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
addMockTrack( collB, "track1", "artist1", "album1" );
addMockTrack( collB, "track2", "artist2", "album2" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 2 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
delete collA;
delete collB;
}
| kkszysiu/amarok | tests/synchronization/TestUnionJob.cpp | C++ | gpl-2.0 | 9,619 |
/* UOL Messenger
* Copyright (c) 2005 Universo Online S/A
*
* Direitos Autorais Reservados
* All rights reserved
*
* Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo
* sob os termos da Licença Pública Geral GNU conforme publicada pela Free
* Software Foundation; tanto a versão 2 da Licença, como (a seu critério)
* qualquer versão posterior.
* Este programa é distribuído na expectativa de que seja útil, porém,
* SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE
* OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral
* do GNU para mais detalhes.
* Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto
* com este programa; se não, escreva para a Free Software Foundation, Inc.,
* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
*
* 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.
*
* Universo Online S/A - A/C: UOL Messenger 5o. Andar
* Avenida Brigadeiro Faria Lima, 1.384 - Jardim Paulistano
* São Paulo SP - CEP 01452-002 - BRASIL */
#include "StdAfx.h"
#include <commands/ShowFileTransfersDialogcommand.h>
#include "../UIMApplication.h"
CShowFileTransfersDialogCommand::CShowFileTransfersDialogCommand()
{
}
CShowFileTransfersDialogCommand::~CShowFileTransfersDialogCommand(void)
{
}
void CShowFileTransfersDialogCommand::Execute()
{
CUIMApplication::GetApplication()->GetUIManager()->ShowFileTransferDialog(NULL);
}
| gabrieldelsaint/uol-messenger | src/public/uim/controller/commands/ShowFileTransfersDialogCommand.cpp | C++ | gpl-2.0 | 2,122 |
/*
* Copyright (C) 2008-2015 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 "AccountMgr.h"
#include "ArenaTeam.h"
#include "ArenaTeamMgr.h"
#include "Battleground.h"
#include "CalendarMgr.h"
#include "Chat.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Language.h"
#include "Log.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "Pet.h"
#include "PlayerDump.h"
#include "Player.h"
#include "ReputationMgr.h"
#include "ScriptMgr.h"
#include "SharedDefines.h"
#include "SocialMgr.h"
#include "SystemConfig.h"
#include "UpdateMask.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#ifdef ELUNA
#include "LuaEngine.h"
#endif
class LoginQueryHolder : public SQLQueryHolder
{
private:
uint32 m_accountId;
ObjectGuid m_guid;
public:
LoginQueryHolder(uint32 accountId, ObjectGuid guid)
: m_accountId(accountId), m_guid(guid) { }
ObjectGuid GetGuid() const { return m_guid; }
uint32 GetAccountId() const { return m_accountId; }
bool Initialize();
};
bool LoginQueryHolder::Initialize()
{
SetSize(MAX_PLAYER_LOGIN_QUERY);
bool res = true;
uint32 lowGuid = m_guid.GetCounter();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_FROM, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GROUP, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INSTANCE);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AURAS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELL);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_WEEKLY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_MONTHLY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_SEASONAL);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_REPUTATION);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_REPUTATION, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INVENTORY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INVENTORY, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACTIONS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILCOUNT);
stmt->setUInt32(0, lowGuid);
stmt->setUInt64(1, uint64(time(NULL)));
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_COUNT, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILDATE);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_DATE, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SOCIALLIST);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS, stmt);
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES, stmt);
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GUILD, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ARENAINFO);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ARENA_INFO, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BGDATA);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BG_DATA, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GLYPHS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GLYPHS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_TALENTS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_TALENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SKILLS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SKILLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_RANDOMBG);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BANNED);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BANNED, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES);
stmt->setUInt32(0, m_accountId);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES, stmt);
return res;
}
void WorldSession::HandleCharEnum(PreparedQueryResult result)
{
WorldPacket data(SMSG_CHAR_ENUM, 100); // we guess size
uint8 num = 0;
data << num;
_legitCharacters.clear();
if (result)
{
do
{
ObjectGuid guid(HIGHGUID_PLAYER, (*result)[0].GetUInt32());
TC_LOG_INFO("network", "Loading %s from account %u.", guid.ToString().c_str(), GetAccountId());
if (Player::BuildEnumData(result, &data))
{
// Do not allow banned characters to log in
if (!(*result)[20].GetUInt32())
_legitCharacters.insert(guid);
if (!sWorld->HasCharacterNameData(guid)) // This can happen if characters are inserted into the database manually. Core hasn't loaded name data yet.
sWorld->AddCharacterNameData(guid, (*result)[1].GetString(), (*result)[4].GetUInt8(), (*result)[2].GetUInt8(), (*result)[3].GetUInt8(), (*result)[7].GetUInt8());
++num;
}
}
while (result->NextRow());
}
data.put<uint8>(0, num);
SendPacket(&data);
}
void WorldSession::HandleCharEnumOpcode(WorldPacket& /*recvData*/)
{
// remove expired bans
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_BANS);
CharacterDatabase.Execute(stmt);
/// get all the data necessary for loading all characters (along with their pets) on the account
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ENUM_DECLINED_NAME);
else
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ENUM);
stmt->setUInt8(0, PET_SAVE_AS_CURRENT);
stmt->setUInt32(1, GetAccountId());
_charEnumCallback = CharacterDatabase.AsyncQuery(stmt);
}
void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData)
{
CharacterCreateInfo createInfo;
recvData >> createInfo.Name
>> createInfo.Race
>> createInfo.Class
>> createInfo.Gender
>> createInfo.Skin
>> createInfo.Face
>> createInfo.HairStyle
>> createInfo.HairColor
>> createInfo.FacialHair
>> createInfo.OutfitId;
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_TEAMMASK))
{
if (uint32 mask = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED))
{
bool disabled = false;
switch (Player::TeamForRace(createInfo.Race))
{
case ALLIANCE:
disabled = (mask & (1 << 0)) != 0;
break;
case HORDE:
disabled = (mask & (1 << 1)) != 0;
break;
}
if (disabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
}
ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(createInfo.Class);
if (!classEntry)
{
TC_LOG_ERROR("network", "Class (%u) not found in DBC while creating new char for account (ID: %u): wrong DBC files or cheater?", createInfo.Class, GetAccountId());
SendCharCreate(CHAR_CREATE_FAILED);
return;
}
ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(createInfo.Race);
if (!raceEntry)
{
TC_LOG_ERROR("network", "Race (%u) not found in DBC while creating new char for account (ID: %u): wrong DBC files or cheater?", createInfo.Race, GetAccountId());
SendCharCreate(CHAR_CREATE_FAILED);
return;
}
// prevent character creating Expansion race without Expansion account
if (raceEntry->expansion > Expansion())
{
TC_LOG_ERROR("network", "Expansion %u account:[%d] tried to Create character with expansion %u race (%u)", Expansion(), GetAccountId(), raceEntry->expansion, createInfo.Race);
SendCharCreate(CHAR_CREATE_EXPANSION);
return;
}
// prevent character creating Expansion class without Expansion account
if (classEntry->expansion > Expansion())
{
TC_LOG_ERROR("network", "Expansion %u account:[%d] tried to Create character with expansion %u class (%u)", Expansion(), GetAccountId(), classEntry->expansion, createInfo.Class);
SendCharCreate(CHAR_CREATE_EXPANSION_CLASS);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RACEMASK))
{
uint32 raceMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_RACEMASK);
if ((1 << (createInfo.Race - 1)) & raceMaskDisabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_CLASSMASK))
{
uint32 classMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_CLASSMASK);
if ((1 << (createInfo.Class - 1)) & classMaskDisabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
// prevent character creating with invalid name
if (!normalizePlayerName(createInfo.Name))
{
TC_LOG_ERROR("network", "Account:[%d] but tried to Create character with empty [name] ", GetAccountId());
SendCharCreate(CHAR_NAME_NO_NAME);
return;
}
// check name limitations
ResponseCodes res = ObjectMgr::CheckPlayerName(createInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharCreate(res);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(createInfo.Name))
{
SendCharCreate(CHAR_NAME_RESERVED);
return;
}
if (createInfo.Class == CLASS_DEATH_KNIGHT && !HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_HEROIC_CHARACTER))
{
// speedup check for heroic class disabled case
uint32 heroic_free_slots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM);
if (heroic_free_slots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
return;
}
// speedup check for heroic class disabled case
uint32 req_level_for_heroic = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER);
if (req_level_for_heroic > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
SendCharCreate(CHAR_CREATE_LEVEL_REQUIREMENT);
return;
}
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
stmt->setString(0, createInfo.Name);
delete _charCreateCallback.GetParam(); // Delete existing if any, to make the callback chain reset to stage 0
_charCreateCallback.SetParam(new CharacterCreateInfo(std::move(createInfo)));
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
}
void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, CharacterCreateInfo* createInfo)
{
/** This is a series of callbacks executed consecutively as a result from the database becomes available.
This is much more efficient than synchronous requests on packet handler, and much less DoS prone.
It also prevents data syncrhonisation errors.
*/
switch (_charCreateCallback.GetStage())
{
case 0:
{
if (result)
{
SendCharCreate(CHAR_CREATE_NAME_IN_USE);
delete createInfo;
_charCreateCallback.Reset();
return;
}
ASSERT(_charCreateCallback.GetParam() == createInfo);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS);
stmt->setUInt32(0, GetAccountId());
_charCreateCallback.FreeResult();
_charCreateCallback.SetFutureResult(LoginDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
break;
}
case 1:
{
uint16 acctCharCount = 0;
if (result)
{
Field* fields = result->Fetch();
// SELECT SUM(x) is MYSQL_TYPE_NEWDECIMAL - needs to be read as string
const char* ch = fields[0].GetCString();
if (ch)
acctCharCount = atoi(ch);
}
if (acctCharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_ACCOUNT))
{
SendCharCreate(CHAR_CREATE_ACCOUNT_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
ASSERT(_charCreateCallback.GetParam() == createInfo);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS);
stmt->setUInt32(0, GetAccountId());
_charCreateCallback.FreeResult();
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
break;
}
case 2:
{
if (result)
{
Field* fields = result->Fetch();
createInfo->CharCount = uint8(fields[0].GetUInt64()); // SQL's COUNT() returns uint64 but it will always be less than uint8.Max
if (createInfo->CharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_REALM))
{
SendCharCreate(CHAR_CREATE_SERVER_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || HasPermission(rbac::RBAC_PERM_TWO_SIDE_CHARACTER_CREATION);
uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS);
_charCreateCallback.FreeResult();
if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO);
stmt->setUInt32(0, GetAccountId());
stmt->setUInt32(1, (skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) ? 10 : 1);
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
return;
}
_charCreateCallback.NextStage();
HandleCharCreateCallback(PreparedQueryResult(NULL), createInfo); // Will jump to case 3
break;
}
case 3:
{
bool haveSameRace = false;
uint32 heroicReqLevel = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER);
bool hasHeroicReqLevel = (heroicReqLevel == 0);
bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || HasPermission(rbac::RBAC_PERM_TWO_SIDE_CHARACTER_CREATION);
uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS);
bool checkHeroicReqs = createInfo->Class == CLASS_DEATH_KNIGHT && !HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_HEROIC_CHARACTER);
if (result)
{
uint32 team = Player::TeamForRace(createInfo->Race);
uint32 freeHeroicSlots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM);
Field* field = result->Fetch();
uint8 accRace = field[1].GetUInt8();
if (checkHeroicReqs)
{
uint8 accClass = field[2].GetUInt8();
if (accClass == CLASS_DEATH_KNIGHT)
{
if (freeHeroicSlots > 0)
--freeHeroicSlots;
if (freeHeroicSlots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
if (!hasHeroicReqLevel)
{
uint8 accLevel = field[0].GetUInt8();
if (accLevel >= heroicReqLevel)
hasHeroicReqLevel = true;
}
}
// need to check team only for first character
/// @todo what to if account already has characters of both races?
if (!allowTwoSideAccounts)
{
uint32 accTeam = 0;
if (accRace > 0)
accTeam = Player::TeamForRace(accRace);
if (accTeam != team)
{
SendCharCreate(CHAR_CREATE_PVP_TEAMS_VIOLATION);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
// search same race for cinematic or same class if need
/// @todo check if cinematic already shown? (already logged in?; cinematic field)
while ((skipCinematics == 1 && !haveSameRace) || createInfo->Class == CLASS_DEATH_KNIGHT)
{
if (!result->NextRow())
break;
field = result->Fetch();
accRace = field[1].GetUInt8();
if (!haveSameRace)
haveSameRace = createInfo->Race == accRace;
if (checkHeroicReqs)
{
uint8 acc_class = field[2].GetUInt8();
if (acc_class == CLASS_DEATH_KNIGHT)
{
if (freeHeroicSlots > 0)
--freeHeroicSlots;
if (freeHeroicSlots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
if (!hasHeroicReqLevel)
{
uint8 acc_level = field[0].GetUInt8();
if (acc_level >= heroicReqLevel)
hasHeroicReqLevel = true;
}
}
}
}
if (checkHeroicReqs && !hasHeroicReqLevel)
{
SendCharCreate(CHAR_CREATE_LEVEL_REQUIREMENT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
Player newChar(this);
newChar.GetMotionMaster()->Initialize();
if (!newChar.Create(sObjectMgr->GenerateLowGuid(HIGHGUID_PLAYER), createInfo))
{
// Player not create (race/class/etc problem?)
newChar.CleanupsBeforeDelete();
SendCharCreate(CHAR_CREATE_ERROR);
delete createInfo;
_charCreateCallback.Reset();
return;
}
if ((haveSameRace && skipCinematics == 1) || skipCinematics == 2)
newChar.setCinematic(1); // not show intro
newChar.SetAtLoginFlag(AT_LOGIN_FIRST); // First login
// Player created, save it now
newChar.SaveToDB(true);
createInfo->CharCount += 1;
SQLTransaction trans = LoginDatabase.BeginTransaction();
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM);
stmt->setUInt32(0, GetAccountId());
stmt->setUInt32(1, realmID);
trans->Append(stmt);
stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS);
stmt->setUInt32(0, createInfo->CharCount);
stmt->setUInt32(1, GetAccountId());
stmt->setUInt32(2, realmID);
trans->Append(stmt);
LoginDatabase.CommitTransaction(trans);
SendCharCreate(CHAR_CREATE_SUCCESS);
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), GetRemoteAddress().c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow());
sScriptMgr->OnPlayerCreate(&newChar);
sWorld->AddCharacterNameData(newChar.GetGUID(), newChar.GetName(), newChar.getGender(), newChar.getRace(), newChar.getClass(), newChar.getLevel());
newChar.CleanupsBeforeDelete();
delete createInfo;
_charCreateCallback.Reset();
break;
}
}
}
void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData)
{
ObjectGuid guid;
recvData >> guid;
// Initiating
uint32 initAccountId = GetAccountId();
// can't delete loaded character
if (ObjectAccessor::FindPlayer(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
return;
}
uint32 accountId = 0;
uint8 level = 0;
std::string name;
// is guild leader
if (sGuildMgr->GetGuildByLeader(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
SendCharDelete(CHAR_DELETE_FAILED_GUILD_LEADER);
return;
}
// is arena team captain
if (sArenaTeamMgr->GetArenaTeamByCaptain(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
SendCharDelete(CHAR_DELETE_FAILED_ARENA_CAPTAIN);
return;
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DATA_BY_GUID);
stmt->setUInt32(0, guid.GetCounter());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
Field* fields = result->Fetch();
accountId = fields[0].GetUInt32();
name = fields[1].GetString();
level = fields[2].GetUInt8();
}
// prevent deleting other players' characters using cheating tools
if (accountId != initAccountId)
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
return;
}
TC_LOG_INFO("entities.player.character", "Account: %d, IP: %s deleted character: %s, %s, Level: %u", accountId, GetRemoteAddress().c_str(), name.c_str(), guid.ToString().c_str(), level);
// To prevent hook failure, place hook before removing reference from DB
sScriptMgr->OnPlayerDelete(guid, initAccountId); // To prevent race conditioning, but as it also makes sense, we hand the accountId over for successful delete.
// Shouldn't interfere with character deletion though
if (sLog->ShouldLog("entities.player.dump", LOG_LEVEL_INFO)) // optimize GetPlayerDump call
{
std::string dump;
if (PlayerDumpWriter().GetDump(guid.GetCounter(), dump))
sLog->outCharDump(dump.c_str(), accountId, guid.GetRawValue(), name.c_str());
}
sCalendarMgr->RemoveAllPlayerEventsAndInvites(guid);
Player::DeleteFromDB(guid, accountId);
SendCharDelete(CHAR_DELETE_SUCCESS);
}
void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData)
{
if (PlayerLoading() || GetPlayer() != NULL)
{
TC_LOG_ERROR("network", "Player tries to login again, AccountId = %d", GetAccountId());
KickPlayer();
return;
}
m_playerLoading = true;
ObjectGuid playerGuid;
TC_LOG_DEBUG("network", "WORLD: Recvd Player Logon Message");
recvData >> playerGuid;
if (!IsLegitCharacterForAccount(playerGuid))
{
TC_LOG_ERROR("network", "Account (%u) can't login with that character (%s).", GetAccountId(), playerGuid.ToString().c_str());
KickPlayer();
return;
}
LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid);
if (!holder->Initialize())
{
delete holder; // delete all unprocessed queries
m_playerLoading = false;
return;
}
_charLoginCallback = CharacterDatabase.DelayQueryHolder(holder);
}
void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder)
{
ObjectGuid playerGuid = holder->GetGuid();
Player* pCurrChar = new Player(this);
// for send server info and strings (config)
ChatHandler chH = ChatHandler(pCurrChar->GetSession());
// "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
if (!pCurrChar->LoadFromDB(playerGuid, holder))
{
SetPlayer(NULL);
KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick
delete pCurrChar; // delete it manually
delete holder; // delete all unprocessed queries
m_playerLoading = false;
return;
}
pCurrChar->GetMotionMaster()->Initialize();
pCurrChar->SendDungeonDifficulty(false);
WorldPacket data(SMSG_LOGIN_VERIFY_WORLD, 20);
data << pCurrChar->GetMapId();
data << pCurrChar->GetPositionX();
data << pCurrChar->GetPositionY();
data << pCurrChar->GetPositionZ();
data << pCurrChar->GetOrientation();
SendPacket(&data);
// load player specific part before send times
LoadAccountData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA), PER_CHARACTER_CACHE_MASK);
SendAccountDataTimes(PER_CHARACTER_CACHE_MASK);
data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2); // added in 2.2.0
data << uint8(2); // unknown value
data << uint8(0); // enable(1)/disable(0) voice chat interface in client
SendPacket(&data);
// Send MOTD
{
data.Initialize(SMSG_MOTD, 50); // new in 2.0.1
data << (uint32)0;
uint32 linecount=0;
std::string str_motd = sWorld->GetMotd();
std::string::size_type pos, nextpos;
pos = 0;
while ((nextpos= str_motd.find('@', pos)) != std::string::npos)
{
if (nextpos != pos)
{
data << str_motd.substr(pos, nextpos-pos);
++linecount;
}
pos = nextpos+1;
}
if (pos<str_motd.length())
{
data << str_motd.substr(pos);
++linecount;
}
data.put(0, linecount);
SendPacket(&data);
TC_LOG_DEBUG("network", "WORLD: Sent motd (SMSG_MOTD)");
// send server info
if (sWorld->getIntConfig(CONFIG_ENABLE_SINFO_LOGIN) == 1)
chH.PSendSysMessage(_FULLVERSION);
TC_LOG_DEBUG("network", "WORLD: Sent server info");
}
//QueryResult* result = CharacterDatabase.PQuery("SELECT guildid, rank FROM guild_member WHERE guid = '%u'", pCurrChar->GetGUIDLow());
if (PreparedQueryResult resultGuild = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_GUILD))
{
Field* fields = resultGuild->Fetch();
pCurrChar->SetInGuild(fields[0].GetUInt32());
pCurrChar->SetRank(fields[1].GetUInt8());
}
else if (pCurrChar->GetGuildId()) // clear guild related fields in case wrong data about non existed membership
{
pCurrChar->SetInGuild(0);
pCurrChar->SetRank(0);
}
if (pCurrChar->GetGuildId() != 0)
{
if (Guild* guild = sGuildMgr->GetGuildById(pCurrChar->GetGuildId()))
guild->SendLoginInfo(this);
else
{
// remove wrong guild data
TC_LOG_ERROR("network", "Player %s (GUID: %u) marked as member of not existing guild (id: %u), removing guild membership for player.", pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->GetGuildId());
pCurrChar->SetInGuild(0);
}
}
data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4);
data << uint32(0);
data << uint32(0);
SendPacket(&data);
pCurrChar->SendInitialPacketsBeforeAddToMap();
//Show cinematic at the first time that player login
if (!pCurrChar->getCinematic())
{
pCurrChar->setCinematic(1);
if (ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass()))
{
if (cEntry->CinematicSequence)
pCurrChar->SendCinematicStart(cEntry->CinematicSequence);
else if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
// send new char string if not empty
if (!sWorld->GetNewCharString().empty())
chH.PSendSysMessage("%s", sWorld->GetNewCharString().c_str());
}
}
if (!pCurrChar->GetMap()->AddPlayerToMap(pCurrChar) || !pCurrChar->CheckInstanceLoginValid())
{
AreaTrigger const* at = sObjectMgr->GetGoBackTrigger(pCurrChar->GetMapId());
if (at)
pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
else
pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
}
sObjectAccessor->AddObject(pCurrChar);
//TC_LOG_DEBUG("Player %s added to Map.", pCurrChar->GetName().c_str());
pCurrChar->SendInitialPacketsAfterAddToMap();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE);
stmt->setUInt32(0, pCurrChar->GetGUIDLow());
CharacterDatabase.Execute(stmt);
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_ONLINE);
stmt->setUInt32(0, GetAccountId());
LoginDatabase.Execute(stmt);
pCurrChar->SetInGameTime(getMSTime());
// announce group about member online (must be after add to player list to receive announce to self)
if (Group* group = pCurrChar->GetGroup())
{
//pCurrChar->groupInfo.group->SendInit(this); // useless
group->SendUpdate();
group->ResetMaxEnchantingLevel();
}
// friend status
sSocialMgr->SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);
// Place character in world (and load zone) before some object loading
pCurrChar->LoadCorpse();
// setting Ghost+speed if dead
if (pCurrChar->m_deathState != ALIVE)
{
// not blizz like, we must correctly save and load player instead...
if (pCurrChar->getRace() == RACE_NIGHTELF)
pCurrChar->CastSpell(pCurrChar, 20584, true, nullptr);// auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
pCurrChar->CastSpell(pCurrChar, 8326, true, nullptr); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
pCurrChar->SetMovement(MOVE_WATER_WALK);
}
pCurrChar->ContinueTaxiFlight();
// reset for all pets before pet loading
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS))
Pet::resetTalentsForAllPetsOf(pCurrChar);
// Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
pCurrChar->LoadPet();
// Set FFA PvP for non GM in non-rest mode
if (sWorld->IsFFAPvPRealm() && !pCurrChar->IsGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
if (pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
pCurrChar->SetContestedPvP();
// Apply at_login requests
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
{
pCurrChar->ResetSpells();
SendNotification(LANG_RESET_SPELLS);
}
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
{
pCurrChar->ResetTalents(true);
pCurrChar->SendTalentsInfoData(false); // original talents send already in to SendInitialPacketsBeforeAddToMap, resend reset state
SendNotification(LANG_RESET_TALENTS);
}
bool firstLogin = pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST);
if (firstLogin)
pCurrChar->RemoveAtLoginFlag(AT_LOGIN_FIRST);
// show time before shutdown if shutdown planned.
if (sWorld->IsShuttingDown())
sWorld->ShutdownMsg(true, pCurrChar);
if (sWorld->getBoolConfig(CONFIG_ALL_TAXI_PATHS))
pCurrChar->SetTaxiCheater(true);
if (pCurrChar->IsGameMaster())
SendNotification(LANG_GM_ON);
std::string IP_str = GetRemoteAddress();
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Login Character:[%s] (GUID: %u) Level: %d",
GetAccountId(), IP_str.c_str(), pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->getLevel());
if (!pCurrChar->IsStandState() && !pCurrChar->HasUnitState(UNIT_STATE_STUNNED))
pCurrChar->SetStandState(UNIT_STAND_STATE_STAND);
m_playerLoading = false;
// Handle Login-Achievements (should be handled after loading)
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ON_LOGIN, 1);
sScriptMgr->OnPlayerLogin(pCurrChar, firstLogin);
delete holder;
}
void WorldSession::HandleSetFactionAtWar(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_FACTION_ATWAR");
uint32 repListID;
uint8 flag;
recvData >> repListID;
recvData >> flag;
GetPlayer()->GetReputationMgr().SetAtWar(repListID, flag != 0);
}
//I think this function is never used :/ I dunno, but i guess this opcode not exists
void WorldSession::HandleSetFactionCheat(WorldPacket& /*recvData*/)
{
TC_LOG_ERROR("network", "WORLD SESSION: HandleSetFactionCheat, not expected call, please report.");
GetPlayer()->GetReputationMgr().SendStates();
}
void WorldSession::HandleTutorialFlag(WorldPacket& recvData)
{
uint32 data;
recvData >> data;
uint8 index = uint8(data / 32);
if (index >= MAX_ACCOUNT_TUTORIAL_VALUES)
return;
uint32 value = (data % 32);
uint32 flag = GetTutorialInt(index);
flag |= (1 << value);
SetTutorialInt(index, flag);
}
void WorldSession::HandleTutorialClear(WorldPacket& /*recvData*/)
{
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
SetTutorialInt(i, 0xFFFFFFFF);
}
void WorldSession::HandleTutorialReset(WorldPacket& /*recvData*/)
{
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
SetTutorialInt(i, 0x00000000);
}
void WorldSession::HandleSetWatchedFactionOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_WATCHED_FACTION");
uint32 fact;
recvData >> fact;
GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
}
void WorldSession::HandleSetFactionInactiveOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_FACTION_INACTIVE");
uint32 replistid;
uint8 inactive;
recvData >> replistid >> inactive;
_player->GetReputationMgr().SetInactive(replistid, inactive != 0);
}
void WorldSession::HandleShowingHelmOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_SHOWING_HELM for %s", _player->GetName().c_str());
recvData.read_skip<uint8>(); // unknown, bool?
_player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
}
void WorldSession::HandleShowingCloakOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_SHOWING_CLOAK for %s", _player->GetName().c_str());
recvData.read_skip<uint8>(); // unknown, bool?
_player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
}
void WorldSession::HandleCharRenameOpcode(WorldPacket& recvData)
{
CharacterRenameInfo renameInfo;
recvData >> renameInfo.Guid
>> renameInfo.Name;
// prevent character rename to invalid name
if (!normalizePlayerName(renameInfo.Name))
{
SendCharRename(CHAR_NAME_NO_NAME, renameInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(renameInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharRename(res, renameInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(renameInfo.Name))
{
SendCharRename(CHAR_NAME_RESERVED, renameInfo);
return;
}
// Ensure that the character belongs to the current account, that rename at login is enabled
// and that there is no character with the desired new name
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_FREE_NAME);
stmt->setUInt32(0, renameInfo.Guid.GetCounter());
stmt->setUInt32(1, GetAccountId());
stmt->setUInt16(2, AT_LOGIN_RENAME);
stmt->setUInt16(3, AT_LOGIN_RENAME);
stmt->setString(4, renameInfo.Name);
delete _charRenameCallback.GetParam();
_charRenameCallback.SetParam(new CharacterRenameInfo(std::move(renameInfo)));
_charRenameCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
}
void WorldSession::HandleChangePlayerNameOpcodeCallBack(PreparedQueryResult result, CharacterRenameInfo const* renameInfo)
{
if (!result)
{
SendCharRename(CHAR_CREATE_ERROR, *renameInfo);
return;
}
Field* fields = result->Fetch();
uint32 guidLow = fields[0].GetUInt32();
std::string oldName = fields[1].GetString();
// Update name and at_login flag in the db
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_NAME);
stmt->setString(0, renameInfo->Name);
stmt->setUInt16(1, AT_LOGIN_RENAME);
stmt->setUInt32(2, guidLow);
CharacterDatabase.Execute(stmt);
// Removed declined name from db
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_DECLINED_NAME);
stmt->setUInt32(0, guidLow);
CharacterDatabase.Execute(stmt);
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Character:[%s] (%s) Changed name to: %s", GetAccountId(), GetRemoteAddress().c_str(), oldName.c_str(), renameInfo->Guid.ToString().c_str(), renameInfo->Name.c_str());
SendCharRename(RESPONSE_SUCCESS, *renameInfo);
sWorld->UpdateCharacterNameData(renameInfo->Guid, renameInfo->Name);
}
void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData)
{
ObjectGuid guid;
recvData >> guid;
// not accept declined names for unsupported languages
std::string name;
if (!sObjectMgr->GetPlayerNameByGUID(guid, name))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
std::wstring wname;
if (!Utf8toWStr(name, wname))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
if (!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
std::string name2;
DeclinedName declinedname;
recvData >> name2;
if (name2 != name) // character have different name
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
for (int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
{
recvData >> declinedname.name[i];
if (!normalizePlayerName(declinedname.name[i]))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
}
if (!ObjectMgr::CheckDeclinedNames(wname, declinedname))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
for (int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
CharacterDatabase.EscapeString(declinedname.name[i]);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
stmt->setUInt32(0, guid.GetCounter());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_DECLINED_NAME);
stmt->setUInt32(0, guid.GetCounter());
for (uint8 i = 0; i < 5; i++)
stmt->setString(i+1, declinedname.name[i]);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_SUCCESS, guid);
}
void WorldSession::HandleAlterAppearance(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_ALTER_APPEARANCE");
uint32 Hair, Color, FacialHair, SkinColor;
recvData >> Hair >> Color >> FacialHair >> SkinColor;
BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair);
if (!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->getGender())
return;
BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair);
if (!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->getGender())
return;
BarberShopStyleEntry const* bs_skinColor = sBarberShopStyleStore.LookupEntry(SkinColor);
if (bs_skinColor && (bs_skinColor->type != 3 || bs_skinColor->race != _player->getRace() || bs_skinColor->gender != _player->getGender()))
return;
if (!Player::ValidateAppearance(_player->getRace(), _player->getClass(), _player->getGender(), bs_hair->hair_id, Color, uint8(_player->GetUInt32Value(PLAYER_FLAGS) >> 8), bs_facialHair->hair_id, bs_skinColor ? bs_skinColor->hair_id : 0))
return;
GameObject* go = _player->FindNearestGameObjectOfType(GAMEOBJECT_TYPE_BARBER_CHAIR, 5.0f);
if (!go)
{
SendBarberShopResult(BARBER_SHOP_RESULT_NOT_ON_CHAIR);
return;
}
if (_player->getStandState() != UNIT_STAND_STATE_SIT_LOW_CHAIR + go->GetGOInfo()->barberChair.chairheight)
{
SendBarberShopResult(BARBER_SHOP_RESULT_NOT_ON_CHAIR);
return;
}
uint32 cost = _player->GetBarberShopCost(bs_hair->hair_id, Color, bs_facialHair->hair_id, bs_skinColor);
// 0 - ok
// 1, 3 - not enough money
// 2 - you have to seat on barber chair
if (!_player->HasEnoughMoney(cost))
{
SendBarberShopResult(BARBER_SHOP_RESULT_NO_MONEY);
return;
}
SendBarberShopResult(BARBER_SHOP_RESULT_SUCCESS);
_player->ModifyMoney(-int32(cost)); // it isn't free
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, cost);
_player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id));
_player->SetByteValue(PLAYER_BYTES, 3, uint8(Color));
_player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id));
if (bs_skinColor)
_player->SetByteValue(PLAYER_BYTES, 0, uint8(bs_skinColor->hair_id));
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1);
_player->SetStandState(0); // stand up
}
void WorldSession::HandleRemoveGlyph(WorldPacket& recvData)
{
uint32 slot;
recvData >> slot;
if (slot >= MAX_GLYPH_SLOT_INDEX)
{
TC_LOG_DEBUG("network", "Client sent wrong glyph slot number in opcode CMSG_REMOVE_GLYPH %u", slot);
return;
}
if (uint32 glyph = _player->GetGlyph(slot))
{
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
_player->RemoveAurasDueToSpell(gp->SpellId);
_player->SetGlyph(slot, 0);
_player->SendTalentsInfoData(false);
}
}
}
void WorldSession::HandleCharCustomize(WorldPacket& recvData)
{
CharacterCustomizeInfo customizeInfo;
recvData >> customizeInfo.Guid;
if (!IsLegitCharacterForAccount(customizeInfo.Guid))
{
TC_LOG_ERROR("network", "Account %u, IP: %s tried to customise %s, but it does not belong to their account!",
GetAccountId(), GetRemoteAddress().c_str(), customizeInfo.Guid.ToString().c_str());
recvData.rfinish();
KickPlayer();
return;
}
recvData >> customizeInfo.Name
>> customizeInfo.Gender
>> customizeInfo.Skin
>> customizeInfo.HairColor
>> customizeInfo.HairStyle
>> customizeInfo.FacialHair
>> customizeInfo.Face;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME_DATA);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
Field* fields = result->Fetch();
uint8 plrRace = fields[0].GetUInt8();
uint8 plrClass = fields[1].GetUInt8();
uint8 plrGender = fields[2].GetUInt8();
if (!Player::ValidateAppearance(plrRace, plrClass, plrGender, customizeInfo.HairStyle, customizeInfo.HairColor, customizeInfo.Face, customizeInfo.FacialHair, customizeInfo.Skin, true))
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AT_LOGIN);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
// TODO: Make async with callback
result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
fields = result->Fetch();
uint32 at_loginFlags = fields[0].GetUInt16();
if (!(at_loginFlags & AT_LOGIN_CUSTOMIZE))
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
// prevent character rename to invalid name
if (!normalizePlayerName(customizeInfo.Name))
{
SendCharCustomize(CHAR_NAME_NO_NAME, customizeInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(customizeInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharCustomize(res, customizeInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(customizeInfo.Name))
{
SendCharCustomize(CHAR_NAME_RESERVED, customizeInfo);
return;
}
// character with this name already exist
if (ObjectGuid newGuid = sObjectMgr->GetPlayerGUIDByName(customizeInfo.Name))
{
if (newGuid != customizeInfo.Guid)
{
SendCharCustomize(CHAR_CREATE_NAME_IN_USE, customizeInfo);
return;
}
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
result = CharacterDatabase.Query(stmt);
if (result)
{
std::string oldname = result->Fetch()[0].GetString();
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s), Character[%s] (%s) Customized to: %s",
GetAccountId(), GetRemoteAddress().c_str(), oldname.c_str(), customizeInfo.Guid.ToString().c_str(), customizeInfo.Name.c_str());
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
Player::Customize(&customizeInfo, trans);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN);
stmt->setString(0, customizeInfo.Name);
stmt->setUInt16(1, uint16(AT_LOGIN_CUSTOMIZE));
stmt->setUInt32(2, customizeInfo.Guid.GetCounter());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_DECLINED_NAME);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
sWorld->UpdateCharacterNameData(customizeInfo.Guid, customizeInfo.Name, customizeInfo.Gender);
SendCharCustomize(RESPONSE_SUCCESS, customizeInfo);
}
void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_SAVE");
uint64 setGuid;
recvData.readPackGUID(setGuid);
uint32 index;
recvData >> index;
if (index >= MAX_EQUIPMENT_SET_INDEX) // client set slots amount
return;
std::string name;
recvData >> name;
std::string iconName;
recvData >> iconName;
EquipmentSet eqSet;
eqSet.Guid = setGuid;
eqSet.Name = name;
eqSet.IconName = iconName;
eqSet.state = EQUIPMENT_SET_NEW;
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
ObjectGuid itemGuid;
recvData >> itemGuid.ReadAsPacked();
// equipment manager sends "1" (as raw GUID) for slots set to "ignore" (don't touch slot at equip set)
if (itemGuid.GetRawValue() == 1)
{
// ignored slots saved as bit mask because we have no free special values for Items[i]
eqSet.IgnoreMask |= 1 << i;
continue;
}
Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!item && itemGuid) // cheating check 1
return;
if (item && item->GetGUID() != itemGuid) // cheating check 2
return;
eqSet.Items[i] = itemGuid.GetCounter();
}
_player->SetEquipmentSet(index, eqSet);
}
void WorldSession::HandleEquipmentSetDelete(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_DELETE");
uint64 setGuid;
recvData.readPackGUID(setGuid);
_player->DeleteEquipmentSet(setGuid);
}
void WorldSession::HandleEquipmentSetUse(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_USE");
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
ObjectGuid itemGuid;
recvData >> itemGuid.ReadAsPacked();
uint8 srcbag, srcslot;
recvData >> srcbag >> srcslot;
TC_LOG_DEBUG("entities.player.items", "%s: srcbag %u, srcslot %u", itemGuid.ToString().c_str(), srcbag, srcslot);
// check if item slot is set to "ignored" (raw value == 1), must not be unequipped then
if (itemGuid.GetRawValue() == 1)
continue;
// Only equip weapons in combat
if (_player->IsInCombat() && i != EQUIPMENT_SLOT_MAINHAND && i != EQUIPMENT_SLOT_OFFHAND && i != EQUIPMENT_SLOT_RANGED)
continue;
Item* item = _player->GetItemByGuid(itemGuid);
uint16 dstpos = i | (INVENTORY_SLOT_BAG_0 << 8);
if (!item)
{
Item* uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!uItem)
continue;
ItemPosCountVec sDest;
InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sDest, uItem, false);
if (msg == EQUIP_ERR_OK)
{
_player->RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
_player->StoreItem(sDest, uItem, true);
}
else
_player->SendEquipError(msg, uItem, NULL);
continue;
}
if (item->GetPos() == dstpos)
continue;
_player->SwapItem(item->GetPos(), dstpos);
}
WorldPacket data(SMSG_EQUIPMENT_SET_USE_RESULT, 1);
data << uint8(0); // 4 - equipment swap failed - inventory is full
SendPacket(&data);
}
void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData)
{
CharacterFactionChangeInfo factionChangeInfo;
recvData >> factionChangeInfo.Guid;
if (!IsLegitCharacterForAccount(factionChangeInfo.Guid))
{
TC_LOG_ERROR("network", "Account %u, IP: %s tried to factionchange character %s, but it does not belong to their account!",
GetAccountId(), GetRemoteAddress().c_str(), factionChangeInfo.Guid.ToString().c_str());
recvData.rfinish();
KickPlayer();
return;
}
recvData >> factionChangeInfo.Name
>> factionChangeInfo.Gender
>> factionChangeInfo.Skin
>> factionChangeInfo.HairColor
>> factionChangeInfo.HairStyle
>> factionChangeInfo.FacialHair
>> factionChangeInfo.Face
>> factionChangeInfo.Race;
uint32 lowGuid = factionChangeInfo.Guid.GetCounter();
// get the players old (at this moment current) race
CharacterNameData const* nameData = sWorld->GetCharacterNameData(factionChangeInfo.Guid);
if (!nameData)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
uint8 oldRace = nameData->m_race;
uint8 playerClass = nameData->m_class;
uint8 level = nameData->m_level;
// TO Do: Make async
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_AT_LOGIN_TITLES);
stmt->setUInt32(0, lowGuid);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
Field* fields = result->Fetch();
uint32 at_loginFlags = fields[0].GetUInt16();
std::string knownTitlesStr = fields[1].GetString();
uint32 used_loginFlag = ((recvData.GetOpcode() == CMSG_CHAR_RACE_CHANGE) ? AT_LOGIN_CHANGE_RACE : AT_LOGIN_CHANGE_FACTION);
if (!sObjectMgr->GetPlayerInfo(factionChangeInfo.Race, playerClass))
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
if (!(at_loginFlags & used_loginFlag))
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RACEMASK))
{
uint32 raceMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_RACEMASK);
if ((1 << (factionChangeInfo.Race - 1)) & raceMaskDisabled)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
}
// prevent character rename to invalid name
if (!normalizePlayerName(factionChangeInfo.Name))
{
SendCharFactionChange(CHAR_NAME_NO_NAME, factionChangeInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(factionChangeInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharFactionChange(res, factionChangeInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(factionChangeInfo.Name))
{
SendCharFactionChange(CHAR_NAME_RESERVED, factionChangeInfo);
return;
}
// character with this name already exist
if (ObjectGuid newGuid = sObjectMgr->GetPlayerGUIDByName(factionChangeInfo.Name))
{
if (newGuid != factionChangeInfo.Guid)
{
SendCharFactionChange(CHAR_CREATE_NAME_IN_USE, factionChangeInfo);
return;
}
}
// resurrect the character in case he's dead
sObjectAccessor->ConvertCorpseForPlayer(factionChangeInfo.Guid);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
CharacterDatabase.EscapeString(factionChangeInfo.Name);
Player::Customize(&factionChangeInfo, trans);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_FACTION_OR_RACE);
stmt->setString(0, factionChangeInfo.Name);
stmt->setUInt8(1, factionChangeInfo.Race);
stmt->setUInt16(2, used_loginFlag);
stmt->setUInt32(3, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
sWorld->UpdateCharacterNameData(factionChangeInfo.Guid, factionChangeInfo.Name, factionChangeInfo.Gender, factionChangeInfo.Race);
if (oldRace != factionChangeInfo.Race)
{
TeamId team = TEAM_ALLIANCE;
// Search each faction is targeted
switch (factionChangeInfo.Race)
{
case RACE_ORC:
case RACE_TAUREN:
case RACE_UNDEAD_PLAYER:
case RACE_TROLL:
case RACE_BLOODELF:
team = TEAM_HORDE;
break;
default:
break;
}
// Switch Languages
// delete all languages first
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_LANGUAGES);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Now add them back
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILL_LANGUAGE);
stmt->setUInt32(0, lowGuid);
// Faction specific languages
if (team == TEAM_HORDE)
stmt->setUInt16(1, 109);
else
stmt->setUInt16(1, 98);
trans->Append(stmt);
// Race specific languages
if (factionChangeInfo.Race != RACE_ORC && factionChangeInfo.Race != RACE_HUMAN)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILL_LANGUAGE);
stmt->setUInt32(0, lowGuid);
switch (factionChangeInfo.Race)
{
case RACE_DWARF:
stmt->setUInt16(1, 111);
break;
case RACE_DRAENEI:
stmt->setUInt16(1, 759);
break;
case RACE_GNOME:
stmt->setUInt16(1, 313);
break;
case RACE_NIGHTELF:
stmt->setUInt16(1, 113);
break;
case RACE_UNDEAD_PLAYER:
stmt->setUInt16(1, 673);
break;
case RACE_TAUREN:
stmt->setUInt16(1, 115);
break;
case RACE_TROLL:
stmt->setUInt16(1, 315);
break;
case RACE_BLOODELF:
stmt->setUInt16(1, 137);
break;
}
trans->Append(stmt);
}
if (recvData.GetOpcode() == CMSG_CHAR_FACTION_CHANGE)
{
// Delete all Flypaths
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TAXI_PATH);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
if (level > 7)
{
// Update Taxi path
// this doesn't seem to be 100% blizzlike... but it can't really be helped.
std::ostringstream taximaskstream;
uint32 numFullTaximasks = level / 7;
if (numFullTaximasks > 11)
numFullTaximasks = 11;
if (team == TEAM_ALLIANCE)
{
if (playerClass != CLASS_DEATH_KNIGHT)
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sAllianceTaxiNodesMask[i]) << ' ';
}
else
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sAllianceTaxiNodesMask[i] | sDeathKnightTaxiNodesMask[i]) << ' ';
}
}
else
{
if (playerClass != CLASS_DEATH_KNIGHT)
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sHordeTaxiNodesMask[i]) << ' ';
}
else
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sHordeTaxiNodesMask[i] | sDeathKnightTaxiNodesMask[i]) << ' ';
}
}
uint32 numEmptyTaximasks = 11 - numFullTaximasks;
for (uint8 i = 0; i < numEmptyTaximasks; ++i)
taximaskstream << "0 ";
taximaskstream << '0';
std::string taximask = taximaskstream.str();
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TAXIMASK);
stmt->setString(0, taximask);
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
}
if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD))
{
// Reset guild
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, lowGuid);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
if (Guild* guild = sGuildMgr->GetGuildById((result->Fetch()[0]).GetUInt32()))
guild->DeleteMember(factionChangeInfo.Guid, false, false, true);
Player::LeaveAllArenaTeams(factionChangeInfo.Guid);
}
if (!HasPermission(rbac::RBAC_PERM_TWO_SIDE_ADD_FRIEND))
{
// Delete Friend List
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
}
// Reset homebind and position
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
WorldLocation loc;
uint16 zoneId = 0;
if (team == TEAM_ALLIANCE)
{
loc.WorldRelocate(0, -8867.68f, 673.373f, 97.9034f, 0.0f);
zoneId = 1519;
}
else
{
loc.WorldRelocate(1, 1633.33f, -4439.11f, 15.7588f, 0.0f);
zoneId = 1637;
}
stmt->setUInt16(1, loc.GetMapId());
stmt->setUInt16(2, zoneId);
stmt->setFloat(3, loc.GetPositionX());
stmt->setFloat(4, loc.GetPositionY());
stmt->setFloat(5, loc.GetPositionZ());
trans->Append(stmt);
Player::SavePositionInDB(loc, zoneId, factionChangeInfo.Guid, trans);
// Achievement conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeAchievements.begin(); it != sObjectMgr->FactionChangeAchievements.end(); ++it)
{
uint32 achiev_alliance = it->first;
uint32 achiev_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT);
stmt->setUInt16(0, uint16(team == TEAM_ALLIANCE ? achiev_alliance : achiev_horde));
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACHIEVEMENT);
stmt->setUInt16(0, uint16(team == TEAM_ALLIANCE ? achiev_alliance : achiev_horde));
stmt->setUInt16(1, uint16(team == TEAM_ALLIANCE ? achiev_horde : achiev_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Item conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeItems.begin(); it != sObjectMgr->FactionChangeItems.end(); ++it)
{
uint32 item_alliance = it->first;
uint32 item_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? item_alliance : item_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? item_horde : item_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Delete all current quests
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Quest conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeQuests.begin(); it != sObjectMgr->FactionChangeQuests.end(); ++it)
{
uint32 quest_alliance = it->first;
uint32 quest_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
stmt->setUInt32(0, lowGuid);
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? quest_alliance : quest_horde));
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? quest_alliance : quest_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? quest_horde : quest_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Mark all rewarded quests as "active" (will count for completed quests achievements)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Disable all old-faction specific quests
{
ObjectMgr::QuestMap const& questTemplates = sObjectMgr->GetQuestTemplates();
for (ObjectMgr::QuestMap::const_iterator iter = questTemplates.begin(); iter != questTemplates.end(); ++iter)
{
Quest const* quest = iter->second;
uint32 newRaceMask = (team == TEAM_ALLIANCE) ? RACEMASK_ALLIANCE : RACEMASK_HORDE;
if (!(quest->GetRequiredRaces() & newRaceMask))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE_BY_QUEST);
stmt->setUInt32(0, lowGuid);
stmt->setUInt32(1, quest->GetQuestId());
trans->Append(stmt);
}
}
}
// Spell conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeSpells.begin(); it != sObjectMgr->FactionChangeSpells.end(); ++it)
{
uint32 spell_alliance = it->first;
uint32 spell_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? spell_alliance : spell_horde));
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_SPELL_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? spell_alliance : spell_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? spell_horde : spell_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Reputation conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeReputation.begin(); it != sObjectMgr->FactionChangeReputation.end(); ++it)
{
uint32 reputation_alliance = it->first;
uint32 reputation_horde = it->second;
uint32 newReputation = (team == TEAM_ALLIANCE) ? reputation_alliance : reputation_horde;
uint32 oldReputation = (team == TEAM_ALLIANCE) ? reputation_horde : reputation_alliance;
// select old standing set in db
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_REP_BY_FACTION);
stmt->setUInt32(0, oldReputation);
stmt->setUInt32(1, lowGuid);
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
Field* fields = result->Fetch();
int32 oldDBRep = fields[0].GetInt32();
FactionEntry const* factionEntry = sFactionStore.LookupEntry(oldReputation);
// old base reputation
int32 oldBaseRep = sObjectMgr->GetBaseReputationOf(factionEntry, oldRace, playerClass);
// new base reputation
int32 newBaseRep = sObjectMgr->GetBaseReputationOf(sFactionStore.LookupEntry(newReputation), factionChangeInfo.Race, playerClass);
// final reputation shouldnt change
int32 FinalRep = oldDBRep + oldBaseRep;
int32 newDBRep = FinalRep - newBaseRep;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REP_BY_FACTION);
stmt->setUInt32(0, newReputation);
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_REP_FACTION_CHANGE);
stmt->setUInt16(0, uint16(newReputation));
stmt->setInt32(1, newDBRep);
stmt->setUInt16(2, uint16(oldReputation));
stmt->setUInt32(3, lowGuid);
trans->Append(stmt);
}
}
// Title conversion
if (!knownTitlesStr.empty())
{
const uint32 ktcount = KNOWN_TITLES_SIZE * 2;
uint32 knownTitles[ktcount];
Tokenizer tokens(knownTitlesStr, ' ', ktcount);
if (tokens.size() != ktcount)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
for (uint32 index = 0; index < ktcount; ++index)
knownTitles[index] = atoul(tokens[index]);
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeTitles.begin(); it != sObjectMgr->FactionChangeTitles.end(); ++it)
{
uint32 title_alliance = it->first;
uint32 title_horde = it->second;
CharTitlesEntry const* atitleInfo = sCharTitlesStore.LookupEntry(title_alliance);
CharTitlesEntry const* htitleInfo = sCharTitlesStore.LookupEntry(title_horde);
// new team
if (team == TEAM_ALLIANCE)
{
uint32 bitIndex = htitleInfo->bit_index;
uint32 index = bitIndex / 32;
uint32 old_flag = 1 << (bitIndex % 32);
uint32 new_flag = 1 << (atitleInfo->bit_index % 32);
if (knownTitles[index] & old_flag)
{
knownTitles[index] &= ~old_flag;
// use index of the new title
knownTitles[atitleInfo->bit_index / 32] |= new_flag;
}
}
else
{
uint32 bitIndex = atitleInfo->bit_index;
uint32 index = bitIndex / 32;
uint32 old_flag = 1 << (bitIndex % 32);
uint32 new_flag = 1 << (htitleInfo->bit_index % 32);
if (knownTitles[index] & old_flag)
{
knownTitles[index] &= ~old_flag;
// use index of the new title
knownTitles[htitleInfo->bit_index / 32] |= new_flag;
}
}
std::ostringstream ss;
for (uint32 index = 0; index < ktcount; ++index)
ss << knownTitles[index] << ' ';
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TITLES_FACTION_CHANGE);
stmt->setString(0, ss.str().c_str());
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
// unset any currently chosen title
stmt = CharacterDatabase.GetPreparedStatement(CHAR_RES_CHAR_TITLES_FACTION_CHANGE);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
}
}
}
}
CharacterDatabase.CommitTransaction(trans);
TC_LOG_DEBUG("entities.player", "%s (IP: %s) changed race from %u to %u", GetPlayerInfo().c_str(), GetRemoteAddress().c_str(), oldRace, factionChangeInfo.Race);
SendCharFactionChange(RESPONSE_SUCCESS, factionChangeInfo);
}
void WorldSession::SendCharCreate(ResponseCodes result)
{
WorldPacket data(SMSG_CHAR_CREATE, 1);
data << uint8(result);
SendPacket(&data);
}
void WorldSession::SendCharDelete(ResponseCodes result)
{
WorldPacket data(SMSG_CHAR_DELETE, 1);
data << uint8(result);
SendPacket(&data);
}
void WorldSession::SendCharRename(ResponseCodes result, CharacterRenameInfo const& renameInfo)
{
WorldPacket data(SMSG_CHAR_RENAME, 1 + 8 + renameInfo.Name.size() + 1);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << renameInfo.Guid;
data << renameInfo.Name;
}
SendPacket(&data);
}
void WorldSession::SendCharCustomize(ResponseCodes result, CharacterCustomizeInfo const& customizeInfo)
{
WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1 + 8 + customizeInfo.Name.size() + 1 + 6);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << customizeInfo.Guid;
data << customizeInfo.Name;
data << uint8(customizeInfo.Gender);
data << uint8(customizeInfo.Skin);
data << uint8(customizeInfo.Face);
data << uint8(customizeInfo.HairStyle);
data << uint8(customizeInfo.HairColor);
data << uint8(customizeInfo.FacialHair);
}
SendPacket(&data);
}
void WorldSession::SendCharFactionChange(ResponseCodes result, CharacterFactionChangeInfo const& factionChangeInfo)
{
WorldPacket data(SMSG_CHAR_FACTION_CHANGE, 1 + 8 + factionChangeInfo.Name.size() + 1 + 7);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << factionChangeInfo.Guid;
data << factionChangeInfo.Name;
data << uint8(factionChangeInfo.Gender);
data << uint8(factionChangeInfo.Skin);
data << uint8(factionChangeInfo.Face);
data << uint8(factionChangeInfo.HairStyle);
data << uint8(factionChangeInfo.HairColor);
data << uint8(factionChangeInfo.FacialHair);
data << uint8(factionChangeInfo.Race);
}
SendPacket(&data);
}
void WorldSession::SendSetPlayerDeclinedNamesResult(DeclinedNameResult result, ObjectGuid guid)
{
WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8);
data << uint32(result);
data << guid;
SendPacket(&data);
}
void WorldSession::SendBarberShopResult(BarberShopResult result)
{
WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
data << uint32(result);
SendPacket(&data);
}
| Rastrian/ElunaTrinityWotlk | src/server/game/Handlers/CharacterHandler.cpp | C++ | gpl-2.0 | 80,672 |
/*
* 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 "Log.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "ObjectMgr.h"
#include "TemporarySummon.h"
TempSummon::TempSummon(SummonPropertiesEntry const *properties, Unit *owner) :
Creature(), m_Properties(properties), m_type(TEMPSUMMON_MANUAL_DESPAWN),
m_timer(0), m_lifetime(0)
{
m_summonerGUID = owner ? owner->GetGUID() : 0;
m_unitTypeMask |= UNIT_MASK_SUMMON;
}
Unit* TempSummon::GetSummoner() const
{
return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : NULL;
}
void TempSummon::Update(uint32 diff)
{
Creature::Update(diff);
if (m_deathState == DEAD)
{
UnSummon();
return;
}
switch(m_type)
{
case TEMPSUMMON_MANUAL_DESPAWN:
break;
case TEMPSUMMON_TIMED_DESPAWN:
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
break;
}
case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT:
{
if (!isInCombat())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
case TEMPSUMMON_CORPSE_TIMED_DESPAWN:
{
if (m_deathState == CORPSE)
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
}
break;
}
case TEMPSUMMON_CORPSE_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == CORPSE || m_deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_DEAD_DESPAWN:
{
if (m_deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == CORPSE || m_deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
else
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
case TEMPSUMMON_TIMED_OR_DEAD_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat() && isAlive())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
else
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
default:
UnSummon();
sLog->outError("Temporary summoned creature (entry: %u) have unknown type %u of ", GetEntry(), m_type);
break;
}
}
void TempSummon::InitStats(uint32 duration)
{
ASSERT(!isPet());
m_timer = duration;
m_lifetime = duration;
if (m_type == TEMPSUMMON_MANUAL_DESPAWN)
m_type = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN;
Unit *owner = GetSummoner();
if (owner && isTrigger() && m_spells[0])
{
setFaction(owner->getFaction());
SetLevel(owner->getLevel());
if (owner->GetTypeId() == TYPEID_PLAYER)
m_ControlledByPlayer = true;
}
if (!m_Properties)
return;
if (owner)
{
if (uint32 slot = m_Properties->Slot)
{
if (owner->m_SummonSlot[slot] && owner->m_SummonSlot[slot] != GetGUID())
{
Creature *oldSummon = GetMap()->GetCreature(owner->m_SummonSlot[slot]);
if (oldSummon && oldSummon->isSummon())
oldSummon->ToTempSummon()->UnSummon();
}
owner->m_SummonSlot[slot] = GetGUID();
}
}
if (m_Properties->Faction)
setFaction(m_Properties->Faction);
else if (IsVehicle()) // properties should be vehicle
setFaction(owner->getFaction());
}
void TempSummon::InitSummon()
{
Unit* owner = GetSummoner();
if (owner)
{
if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->JustSummoned(this);
if (IsAIEnabled)
AI()->IsSummonedBy(owner);
}
}
void TempSummon::SetTempSummonType(TempSummonType type)
{
m_type = type;
}
void TempSummon::UnSummon(uint32 msTime)
{
if (msTime)
{
ForcedUnsummonDelayEvent *pEvent = new ForcedUnsummonDelayEvent(*this);
m_Events.AddEvent(pEvent, m_Events.CalculateTime(msTime));
return;
}
//ASSERT(!isPet());
if (isPet())
{
((Pet*)this)->Remove(PET_SAVE_NOT_IN_SLOT);
ASSERT(!IsInWorld());
return;
}
Unit* owner = GetSummoner();
if (owner && owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->SummonedCreatureDespawn(this);
if (owner &&
owner->GetTypeId() == TYPEID_PLAYER &&
((Player*)owner)->HaveBot() &&
((Player*)owner)->GetBot()->GetGUID()==this->GetGUID() &&
this->isDead()) { // dont unsummon corpse if a bot
return;
}
AddObjectToRemoveList();
}
bool ForcedUnsummonDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
m_owner.UnSummon();
return true;
}
void TempSummon::RemoveFromWorld()
{
if (!IsInWorld())
return;
if (m_Properties)
if (uint32 slot = m_Properties->Slot)
if (Unit* owner = GetSummoner())
if (owner->m_SummonSlot[slot] == GetGUID())
owner->m_SummonSlot[slot] = 0;
//if (GetOwnerGUID())
// sLog->outError("Unit %u has owner guid when removed from world", GetEntry());
Creature::RemoveFromWorld();
}
Minion::Minion(SummonPropertiesEntry const *properties, Unit *owner) : TempSummon(properties, owner)
, m_owner(owner)
{
ASSERT(m_owner);
m_unitTypeMask |= UNIT_MASK_MINION;
m_followAngle = PET_FOLLOW_ANGLE;
}
void Minion::InitStats(uint32 duration)
{
TempSummon::InitStats(duration);
SetReactState(REACT_PASSIVE);
SetCreatorGUID(m_owner->GetGUID());
setFaction(m_owner->getFaction());
m_owner->SetMinion(this, true);
}
void Minion::RemoveFromWorld()
{
if (!IsInWorld())
return;
m_owner->SetMinion(this, false);
TempSummon::RemoveFromWorld();
}
bool Minion::IsGuardianPet() const
{
return isPet() || (m_Properties && m_Properties->Category == SUMMON_CATEGORY_PET);
}
Guardian::Guardian(SummonPropertiesEntry const *properties, Unit *owner) : Minion(properties, owner)
, m_bonusSpellDamage(0)
{
memset(m_statFromOwner, 0, sizeof(float)*MAX_STATS);
m_unitTypeMask |= UNIT_MASK_GUARDIAN;
if (properties && properties->Type == SUMMON_TYPE_PET)
{
m_unitTypeMask |= UNIT_MASK_CONTROLABLE_GUARDIAN;
InitCharmInfo();
}
}
void Guardian::InitStats(uint32 duration)
{
Minion::InitStats(duration);
InitStatsForLevel(m_owner->getLevel());
if (m_owner->GetTypeId() == TYPEID_PLAYER && HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
m_charmInfo->InitCharmCreateSpells();
SetReactState(REACT_AGGRESSIVE);
}
void Guardian::InitSummon()
{
TempSummon::InitSummon();
if (m_owner->GetTypeId() == TYPEID_PLAYER
&& m_owner->GetMinionGUID() == GetGUID()
&& !m_owner->GetCharmGUID())
m_owner->ToPlayer()->CharmSpellInitialize();
}
Puppet::Puppet(SummonPropertiesEntry const *properties, Unit *owner) : Minion(properties, owner)
{
ASSERT(owner->GetTypeId() == TYPEID_PLAYER);
m_owner = (Player*)owner;
m_unitTypeMask |= UNIT_MASK_PUPPET;
}
void Puppet::InitStats(uint32 duration)
{
Minion::InitStats(duration);
SetLevel(m_owner->getLevel());
SetReactState(REACT_PASSIVE);
}
void Puppet::InitSummon()
{
Minion::InitSummon();
if (!SetCharmedBy(m_owner, CHARM_TYPE_POSSESS))
ASSERT(false);
}
void Puppet::Update(uint32 time)
{
Minion::Update(time);
//check if caster is channelling?
if (IsInWorld())
{
if (!isAlive())
{
UnSummon();
// TODO: why long distance .die does not remove it
}
}
}
void Puppet::RemoveFromWorld()
{
if (!IsInWorld())
return;
RemoveCharmedBy(NULL);
Minion::RemoveFromWorld();
}
| sucofog/chaoscore | src/server/game/Entities/Creature/TemporarySummon.cpp | C++ | gpl-2.0 | 9,947 |
package com.orange.documentare.core.comp.clustering.tasksservice;
/*
* Copyright (c) 2016 Orange
*
* Authors: Christophe Maldivi & Joel Gardes
*
* 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.
*/
import com.orange.documentare.core.comp.clustering.graph.ClusteringParameters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.fest.assertions.Assertions;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@Slf4j
public class ClusteringTasksServiceTest {
private static final int NB_TASKS = 4 * 10;
private static final String CLUSTERING_TASK_FILE_PREFIX = "clustering_tasks_";
private static final String STRIPPED_CLUSTERING_JSON = "stripped_clustering.json";
private static final String NOT_STRIPPED_CLUSTERING_JSON = "not_stripped_clustering.json";
private final ClusteringTasksService tasksHandler = ClusteringTasksService.instance();
private final ClusteringParameters parameters = ClusteringParameters.builder().acut().qcut().build();
@After
public void cleanup() {
FileUtils.deleteQuietly(new File(STRIPPED_CLUSTERING_JSON));
FileUtils.deleteQuietly(new File(NOT_STRIPPED_CLUSTERING_JSON));
}
@Test
public void runSeveralDistinctTasks() throws IOException, InterruptedException {
// given
String refJson1 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin1_clustering.ref.json").getFile()));
String refJson2 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin2_clustering.ref.json").getFile()));
String refJson3 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin3_clustering.ref.json").getFile()));
String refJson4 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin4_clustering.ref.json").getFile()));
File segFile1 = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
File segFile2 = new File(getClass().getResource("/clusteringtasks/latin2_segmentation.json").getFile());
File segFile3 = new File(getClass().getResource("/clusteringtasks/latin3_segmentation.json").getFile());
File segFile4 = new File(getClass().getResource("/clusteringtasks/latin4_segmentation.json").getFile());
String[] outputFilenames = new String[NB_TASKS];
ClusteringTask[] clusteringTasks = new ClusteringTask[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputFilenames[i] = CLUSTERING_TASK_FILE_PREFIX + i + ".json";
}
for (int i = 0; i < NB_TASKS/4; i++) {
clusteringTasks[i * 4] = ClusteringTask.builder()
.inputFilename(segFile1.getAbsolutePath())
.outputFilename(outputFilenames[i * 4])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 1] = ClusteringTask.builder()
.inputFilename(segFile2.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 1])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 2] = ClusteringTask.builder()
.inputFilename(segFile3.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 2])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 3] = ClusteringTask.builder()
.inputFilename(segFile4.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 3])
.clusteringParameters(parameters)
.build();
}
// when
for (int i = 0; i < NB_TASKS; i++) {
tasksHandler.addNewTask(clusteringTasks[i]);
Thread.sleep(200);
log.info(tasksHandler.tasksDescription().toString());
}
tasksHandler.waitForAllTasksDone();
String[] outputJsons = new String[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputJsons[i] = FileUtils.readFileToString(new File(outputFilenames[i]));
}
// then
for (int i = 0; i < NB_TASKS/4; i++) {
Assertions.assertThat(outputJsons[i * 4]).isEqualTo(refJson1);
Assertions.assertThat(outputJsons[i * 4 + 1]).isEqualTo(refJson2);
Assertions.assertThat(outputJsons[i * 4 + 2]).isEqualTo(refJson3);
Assertions.assertThat(outputJsons[i * 4 + 3]).isEqualTo(refJson4);
}
Arrays.stream(outputFilenames)
.forEach(f -> FileUtils.deleteQuietly(new File(f)));
}
@Test
public void saveStrippedOutput() throws IOException, InterruptedException {
// given
File ref = new File(getClass().getResource("/clusteringtasks/stripped_clustering.ref.json").getFile());
String jsonRef = FileUtils.readFileToString(ref);
String strippedFilename = STRIPPED_CLUSTERING_JSON;
File strippedFile = new File(strippedFilename);
strippedFile.delete();
File segFile = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
String outputFilename = NOT_STRIPPED_CLUSTERING_JSON;
ClusteringTask task = ClusteringTask.builder()
.inputFilename(segFile.getAbsolutePath())
.outputFilename(outputFilename)
.clusteringParameters(parameters)
.strippedOutputFilename(strippedFilename)
.build();
// when
tasksHandler.addNewTask(task);
tasksHandler.waitForAllTasksDone();
// then
String strippedJson = FileUtils.readFileToString(strippedFile);
Assertions.assertThat(strippedFile).exists();
Assertions.assertThat(strippedJson).isEqualTo(jsonRef);
}
}
| Orange-OpenSource/documentare-simdoc | simdoc/core/java/Comp/src/test/java/com/orange/documentare/core/comp/clustering/tasksservice/ClusteringTasksServiceTest.java | Java | gpl-2.0 | 5,621 |
<?php
/**
* DmUserGroupTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class DmUserGroupTable extends PluginDmUserGroupTable
{
/**
* Returns an instance of this class.
*
* @return DmUserGroupTable The table object
*/
public static function getInstance()
{
return Doctrine_Core::getTable('DmUserGroup');
}
} | Teplitsa/bquest.ru | lib/model/doctrine/dmUserPlugin/DmUserGroupTable.class.php | PHP | gpl-2.0 | 386 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database.parse.util;
import almonds.Parse;
import almonds.ParseObject;
import database.parse.tables.ParsePhenomena;
import database.parse.tables.ParseSensor;
import java.net.URI;
/**
*
* @author jried31
*/
public class DBGlobals {
static public String TABLE_PHENOMENA="tester";
static public String TABLE_SENSOR="Sensor";
public static String URL_GOOGLE_SEARCH="http://suggestqueries.google.com/complete/search?client=firefox&hl=en&q=WORD";
//http://clients1.google.com/complete/search?noLabels=t&client=web&q=WORD";
public static void InitializeParse(){
//App Ids for Connecting to the Parse DB
Parse.initialize("jEciFYpTp2b1XxHuIkmAs3yaP70INpkBDg9WdTl9", //Application ID
"aPEXcVv80kHwfVJK1WEKWckePkWxYNEXBovIR6d5"); //Rest API Key
}
}
| jried31/SSKB | sensite/src/main/java/database/parse/util/DBGlobals.java | Java | gpl-2.0 | 1,007 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008,2009 IITP RAS
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Kirill Andreev <andreev@iitp.ru>
*/
#include "hwmp-protocol.h"
#include "hwmp-protocol-mac.h"
#include "hwmp-tag.h"
#include "hwmp-rtable.h"
#include "ns3/log.h"
#include "ns3/simulator.h"
#include "ns3/packet.h"
#include "ns3/mesh-point-device.h"
#include "ns3/wifi-net-device.h"
#include "ns3/mesh-point-device.h"
#include "ns3/mesh-wifi-interface-mac.h"
#include "ns3/random-variable-stream.h"
#include "airtime-metric.h"
#include "ie-dot11s-preq.h"
#include "ie-dot11s-prep.h"
#include "ns3/trace-source-accessor.h"
#include "ie-dot11s-perr.h"
#include "ns3/arp-l3-protocol.h"
#include "ns3/ipv4-l3-protocol.h"
#include "ns3/udp-l4-protocol.h"
#include "ns3/tcp-l4-protocol.h"
#include "ns3/arp-header.h"
#include "ns3/ipv4-header.h"
#include "ns3/tcp-header.h"
#include "ns3/udp-header.h"
#include "ns3/rhoSigma-tag.h"
#include "ns3/llc-snap-header.h"
#include "ns3/wifi-mac-trailer.h"
#include "dot11s-mac-header.h"
NS_LOG_COMPONENT_DEFINE ("HwmpProtocol");
namespace ns3 {
namespace dot11s {
NS_OBJECT_ENSURE_REGISTERED (HwmpProtocol)
;
/* integration/qng.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//#include <config.h>
#include <math.h>
#include <float.h>
TypeId
HwmpProtocol::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::dot11s::HwmpProtocol")
.SetParent<MeshL2RoutingProtocol> ()
.AddConstructor<HwmpProtocol> ()
.AddAttribute ( "RandomStart",
"Random delay at first proactive PREQ",
TimeValue (Seconds (0.1)),
MakeTimeAccessor (
&HwmpProtocol::m_randomStart),
MakeTimeChecker ()
)
.AddAttribute ( "MaxQueueSize",
"Maximum number of packets we can store when resolving route",
UintegerValue (255),
MakeUintegerAccessor (
&HwmpProtocol::m_maxQueueSize),
MakeUintegerChecker<uint16_t> (1)
)
.AddAttribute ( "Dot11MeshHWMPmaxPREQretries",
"Maximum number of retries before we suppose the destination to be unreachable",
UintegerValue (3),
MakeUintegerAccessor (
&HwmpProtocol::m_dot11MeshHWMPmaxPREQretries),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "Dot11MeshHWMPnetDiameterTraversalTime",
"Time we suppose the packet to go from one edge of the network to another",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPnetDiameterTraversalTime),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPpreqMinInterval",
"Minimal interval between to successive PREQs",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPpreqMinInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPperrMinInterval",
"Minimal interval between to successive PREQs",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (&HwmpProtocol::m_dot11MeshHWMPperrMinInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPactiveRootTimeout",
"Lifetime of poractive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPactiveRootTimeout),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPactivePathTimeout",
"Lifetime of reactive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPactivePathTimeout),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPpathToRootInterval",
"Interval between two successive proactive PREQs",
TimeValue (MicroSeconds (1024*2000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPpathToRootInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPrannInterval",
"Lifetime of poractive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPrannInterval),
MakeTimeChecker ()
)
.AddAttribute ( "MaxTtl",
"Initial value of Time To Live field",
UintegerValue (32),
MakeUintegerAccessor (
&HwmpProtocol::m_maxTtl),
MakeUintegerChecker<uint8_t> (2)
)
.AddAttribute ( "UnicastPerrThreshold",
"Maximum number of PERR receivers, when we send a PERR as a chain of unicasts",
UintegerValue (32),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastPerrThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "UnicastPreqThreshold",
"Maximum number of PREQ receivers, when we send a PREQ as a chain of unicasts",
UintegerValue (1),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastPreqThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "UnicastDataThreshold",
"Maximum number ofbroadcast receivers, when we send a broadcast as a chain of unicasts",
UintegerValue (1),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastDataThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "DoFlag",
"Destination only HWMP flag",
BooleanValue (true),
MakeBooleanAccessor (
&HwmpProtocol::m_doFlag),
MakeBooleanChecker ()
)
.AddAttribute ( "RfFlag",
"Reply and forward flag",
BooleanValue (false),
MakeBooleanAccessor (
&HwmpProtocol::m_rfFlag),
MakeBooleanChecker ()
)
.AddTraceSource ( "RouteDiscoveryTime",
"The time of route discovery procedure",
MakeTraceSourceAccessor (
&HwmpProtocol::m_routeDiscoveryTimeCallback)
)
//by hadi
.AddAttribute ( "VBMetricMargin",
"VBMetricMargin",
UintegerValue (2),
MakeUintegerAccessor (
&HwmpProtocol::m_VBMetricMargin),
MakeUintegerChecker<uint32_t> (1)
)
.AddAttribute ( "Gppm",
"G Packets Per Minutes",
UintegerValue (3600),
MakeUintegerAccessor (
&HwmpProtocol::m_Gppm),
MakeUintegerChecker<uint32_t> (1)
)
.AddTraceSource ( "TransmittingFromSource",
"",
MakeTraceSourceAccessor (
&HwmpProtocol::m_txed4mSourceCallback)
)
.AddTraceSource ( "WannaTransmittingFromSource",
"",
MakeTraceSourceAccessor (
&HwmpProtocol::m_wannaTx4mSourceCallback)
)
.AddTraceSource( "CbrCnnStateChanged",
"",
MakeTraceSourceAccessor(
&HwmpProtocol::m_CbrCnnStateChanged))
.AddTraceSource( "PacketBufferredAtSource",
"",
MakeTraceSourceAccessor(
&HwmpProtocol::m_packetBufferredAtSource))
;
return tid;
}
HwmpProtocol::HwmpProtocol () :
m_dataSeqno (1),
m_hwmpSeqno (1),
m_preqId (0),
m_rtable (CreateObject<HwmpRtable> ()),
m_randomStart (Seconds (0.1)),
m_maxQueueSize (255),
m_dot11MeshHWMPmaxPREQretries (3),
m_dot11MeshHWMPnetDiameterTraversalTime (MicroSeconds (1024*100)),
m_dot11MeshHWMPpreqMinInterval (MicroSeconds (1024*100)),
m_dot11MeshHWMPperrMinInterval (MicroSeconds (1024*100)),
m_dot11MeshHWMPactiveRootTimeout (MicroSeconds (1024*5000)),
m_dot11MeshHWMPactivePathTimeout (MicroSeconds (1024*5000)),
m_dot11MeshHWMPpathToRootInterval (MicroSeconds (1024*2000)),
m_dot11MeshHWMPrannInterval (MicroSeconds (1024*5000)),
m_isRoot (false),
m_maxTtl (32),
m_unicastPerrThreshold (32),
m_unicastPreqThreshold (1),
m_unicastDataThreshold (1),
m_doFlag (true),
m_rfFlag (false),
m_VBMetricMargin(2)
{
NS_LOG_FUNCTION_NOARGS ();
m_noDataPacketYet=true;
m_energyPerByte=0;
m_coefficient = CreateObject<UniformRandomVariable> ();
}
HwmpProtocol::~HwmpProtocol ()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
HwmpProtocol::DoInitialize ()
{
m_coefficient->SetAttribute ("Max", DoubleValue (m_randomStart.GetSeconds ()));
if (m_isRoot)
{
SetRoot ();
}
Simulator::Schedule(Seconds(0.5),&HwmpProtocol::CheckCbrRoutes4Expiration,this);//hadi eo94
m_interfaces.begin ()->second->SetEnergyChangeCallback (MakeCallback(&HwmpProtocol::EnergyChange,this));
m_interfaces.begin ()->second->SetGammaChangeCallback (MakeCallback(&HwmpProtocol::GammaChange,this));
m_rtable->setSystemB (m_interfaces.begin ()->second->GetEres ());
m_rtable->setBPrim (m_rtable->systemB ());
m_rtable->setSystemBMax (m_interfaces.begin ()->second->GetBatteryCapacity ());
m_rtable->setBPrimMax (m_rtable->systemBMax ());
m_rtable->setAssignedGamma (0);
m_rtable->setGppm (m_Gppm);
GammaChange (m_rtable->systemGamma (),m_totalSimulationTime);
m_rtable->UpdateToken ();
}
void
HwmpProtocol::DoDispose ()
{
NS_LOG_FUNCTION_NOARGS ();
for (std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.begin (); i != m_preqTimeouts.end (); i++)
{
i->second.preqTimeout.Cancel ();
}
m_proactivePreqTimer.Cancel ();
m_preqTimeouts.clear ();
m_lastDataSeqno.clear ();
m_hwmpSeqnoMetricDatabase.clear ();
for (std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
cbpei->preqTimeout.Cancel();
}
m_cnnBasedPreqTimeouts.clear();
for(std::vector<DelayedPrepStruct>::iterator dpsi=m_delayedPrepStruct.begin ();dpsi!=m_delayedPrepStruct.end ();dpsi++)
{
dpsi->prepTimeout.Cancel ();
}
m_delayedPrepStruct.clear ();
m_interfaces.clear ();
m_rqueue.clear ();
m_rtable = 0;
m_mp = 0;
}
bool
HwmpProtocol::RequestRoute (
uint32_t sourceIface,
const Mac48Address source,
const Mac48Address destination,
Ptr<const Packet> constPacket,
uint16_t protocolType, //ethrnet 'Protocol' field
MeshL2RoutingProtocol::RouteReplyCallback routeReply
)
{
Ptr <Packet> packet = constPacket->Copy ();
HwmpTag tag;
if (sourceIface == GetMeshPoint ()->GetIfIndex ())
{
// packet from level 3
if (packet->PeekPacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag has come with a packet from upper layer. This must not occur...");
}
//Filling TAG:
if (destination == Mac48Address::GetBroadcast ())
{
tag.SetSeqno (m_dataSeqno++);
}
tag.SetTtl (m_maxTtl);
}
else
{
if (!packet->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag is supposed to be here at this point.");
}
tag.DecrementTtl ();
if (tag.GetTtl () == 0)
{
m_stats.droppedTtl++;
return false;
}
}
if (destination == Mac48Address::GetBroadcast ())
{
m_stats.txBroadcast++;
m_stats.txBytes += packet->GetSize ();
//channel IDs where we have already sent broadcast:
std::vector<uint16_t> channels;
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
bool shouldSend = true;
for (std::vector<uint16_t>::const_iterator chan = channels.begin (); chan != channels.end (); chan++)
{
if ((*chan) == plugin->second->GetChannelId ())
{
shouldSend = false;
}
}
if (!shouldSend)
{
continue;
}
channels.push_back (plugin->second->GetChannelId ());
std::vector<Mac48Address> receivers = GetBroadcastReceivers (plugin->first);
for (std::vector<Mac48Address>::const_iterator i = receivers.begin (); i != receivers.end (); i++)
{
Ptr<Packet> packetCopy = packet->Copy ();
//
// 64-bit Intel valgrind complains about tag.SetAddress (*i). It
// likes this just fine.
//
Mac48Address address = *i;
tag.SetAddress (address);
packetCopy->AddPacketTag (tag);
routeReply (true, packetCopy, source, destination, protocolType, plugin->first);
}
}
}
else
{
return ForwardUnicast (sourceIface, source, destination, packet, protocolType, routeReply, tag.GetTtl ());
}
return true;
}
bool
HwmpProtocol::RemoveRoutingStuff (uint32_t fromIface, const Mac48Address source,
const Mac48Address destination, Ptr<Packet> packet, uint16_t& protocolType)
{
HwmpTag tag;
if (!packet->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag must exist when packet received from the network");
}
return true;
}
bool
HwmpProtocol::ForwardUnicast (uint32_t sourceIface, const Mac48Address source, const Mac48Address destination,
Ptr<Packet> packet, uint16_t protocolType, RouteReplyCallback routeReply, uint32_t ttl)
{
RhoSigmaTag rsTag;
packet->RemovePacketTag (rsTag);
Ptr<Packet> pCopy=packet->Copy();
uint8_t cnnType;//1:mac only, 2:ip only , 3:ip port
Ipv4Address srcIpv4Addr;
Ipv4Address dstIpv4Addr;
uint16_t srcPort;
uint16_t dstPort;
if(protocolType==ArpL3Protocol::PROT_NUMBER)
{
ArpHeader arpHdr;
pCopy->RemoveHeader(arpHdr);
srcIpv4Addr = arpHdr.GetSourceIpv4Address();
dstIpv4Addr = arpHdr.GetDestinationIpv4Address();
cnnType=HwmpRtable::CNN_TYPE_IP_ONLY;
// NS_LOG_HADI(m_address << " ARP packet have seen");
NS_ASSERT(true);
}
else if(protocolType==Ipv4L3Protocol::PROT_NUMBER)
{
Ipv4Header ipv4Hdr;
pCopy->RemoveHeader(ipv4Hdr);
srcIpv4Addr = ipv4Hdr.GetSource();
dstIpv4Addr = ipv4Hdr.GetDestination();
uint8_t protocol = ipv4Hdr.GetProtocol();
if(protocol==TcpL4Protocol::PROT_NUMBER)
{
TcpHeader tcpHdr;
pCopy->RemoveHeader (tcpHdr);
srcPort=tcpHdr.GetSourcePort ();
dstPort=tcpHdr.GetDestinationPort ();
cnnType=HwmpRtable::CNN_TYPE_PKT_BASED;
}
else if(protocol==UdpL4Protocol::PROT_NUMBER)
{
UdpHeader udpHdr;
pCopy->RemoveHeader(udpHdr);
srcPort=udpHdr.GetSourcePort();
dstPort=udpHdr.GetDestinationPort();
cnnType=HwmpRtable::CNN_TYPE_IP_PORT;
// NS_LOG_HADI(m_address << " UDP packet have seen " << source << "->" << destination << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
else
{
cnnType=HwmpRtable::CNN_TYPE_IP_ONLY;
// NS_LOG_HADI(m_address << " non TCP or UDP packet have seen");
NS_ASSERT(true);
}
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
// NS_LOG_HADI(m_address << " non IP packet have seen");
NS_ASSERT(true);
}
if((source==GetAddress())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)){
NS_LOG_ROUTING("hwmp forwardUnicast4mSource " << (int)packet->GetUid() << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " " << (int)rsTag.GetRho () << " " << (int)rsTag.GetSigma () << " " << rsTag.GetStopTime ());
m_wannaTx4mSourceCallback();
}
NS_ASSERT (destination != Mac48Address::GetBroadcast ());
NS_ASSERT(cnnType==HwmpRtable::CNN_TYPE_IP_PORT);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT){
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi!=m_notRoutedCbrConnections.end()){
if(source==GetAddress()){
NS_LOG_ROUTING("hwmp cnnRejectedDrop " << (int)packet->GetUid() << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
return false;
}
}
HwmpRtable::CnnBasedLookupResult cnnBasedResult = m_rtable->LookupCnnBasedReactive(destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
NS_LOG_DEBUG ("Requested src = "<<source<<", dst = "<<destination<<", I am "<<GetAddress ()<<", RA = "<<cnnBasedResult.retransmitter);
HwmpTag tag;
tag.SetAddress (cnnBasedResult.retransmitter);
tag.SetTtl (ttl);
//seqno and metric is not used;
packet->AddPacketTag (tag);
if (cnnBasedResult.retransmitter != Mac48Address::GetBroadcast ())
{
if(source==GetAddress())
{
NS_LOG_ROUTING("tx4mSource " << (int)packet->GetUid());
NS_LOG_CAC("tx4mSource " << srcIpv4Addr << ":" << srcPort << "=>" << dstIpv4Addr << ":" << dstPort << " " << (int)packet->GetUid());
m_txed4mSourceCallback();
SourceCbrRouteExtend (destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
else
{
NS_LOG_CAC("forwardViaIntermediate " << srcIpv4Addr << ":" << srcPort << "=>" << dstIpv4Addr << ":" << dstPort << " " << (int)packet->GetUid());
CbrRouteExtend(destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
//reply immediately:
//routeReply (true, packet, source, destination, protocolType, cnnBasedResult.ifIndex);
NS_LOG_TB("queuing packet in TBVB queue for send " << (int)packet->GetUid ());
m_rtable->QueueCnnBasedPacket (destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,packet,protocolType,cnnBasedResult.ifIndex,routeReply);
m_stats.txUnicast++;
m_stats.txBytes += packet->GetSize ();
return true;
}
if (sourceIface != GetMeshPoint ()->GetIfIndex ())
{
//Start path error procedure:
NS_LOG_DEBUG ("Must Send PERR");
m_stats.totalDropped++;
return false;
}
//Request a destination:
if (CnnBasedShouldSendPreq (rsTag, destination, source, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort))
{
NS_LOG_ROUTING("sendingPathRequest " << source << " " << destination);
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = 0;
m_stats.initiatedPreq++;
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
if(m_routingType==2)
i->second->RequestDestination (destination, originator_seqno, dst_seqno, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort,rsTag.GetRho (), rsTag.GetSigma (), rsTag.GetStopTime (), rsTag.delayBound (), rsTag.maxPktSize (), 0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (destination, originator_seqno, dst_seqno, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort,rsTag.GetRho (), rsTag.GetSigma (), rsTag.GetStopTime (),rsTag.delayBound (), rsTag.maxPktSize (), 0,0,0);
}
}
QueuedPacket pkt;
pkt.pkt = packet;
pkt.dst = destination;
pkt.src = source;
pkt.protocol = protocolType;
pkt.reply = routeReply;
pkt.inInterface = sourceIface;
pkt.cnnType=cnnType;
pkt.srcIpv4Addr=srcIpv4Addr;
pkt.dstIpv4Addr=dstIpv4Addr;
pkt.srcPort=srcPort;
pkt.dstPort=dstPort;
if (QueuePacket (pkt))
{
if((source==GetAddress ())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT))
m_packetBufferredAtSource(packet);
m_stats.totalQueued++;
return true;
}
else
{
m_stats.totalDropped++;
return false;
}
}
void
HwmpProtocol::ReceivePreq (IePreq preq, Mac48Address from, uint32_t interface, Mac48Address fromMp, uint32_t metric)
{
preq.IncrementMetric (metric);
NS_LOG_ROUTING("receivePreq " << from << " " << (int)preq.GetGammaPrim () << " " << (int)preq.GetBPrim () << " " << (int)preq.GetTotalE () << " " << (int)preq.GetMetric ());
//acceptance cretirea:
// bool duplicatePreq=false;
//bool freshInfo (true);
for(std::vector<CnnBasedSeqnoMetricDatabase>::iterator i=m_hwmpSeqnoMetricDatabase.begin();i!=m_hwmpSeqnoMetricDatabase.end();i++)
{
if(
(i->originatorAddress==preq.GetOriginatorAddress()) &&
(i->cnnType==preq.GetCnnType()) &&
(i->srcIpv4Addr==preq.GetSrcIpv4Addr()) &&
(i->srcPort==preq.GetSrcPort()) &&
(i->dstIpv4Addr==preq.GetDstIpv4Addr()) &&
(i->dstPort==preq.GetDstPort())
)
{
// duplicatePreq=true;
NS_LOG_ROUTING("duplicatePreq " << (int)i->originatorSeqNumber << " " << (int)preq.GetOriginatorSeqNumber ());
if ((int32_t)(i->originatorSeqNumber - preq.GetOriginatorSeqNumber ()) > 0)
{
return;
}
if (i->originatorSeqNumber == preq.GetOriginatorSeqNumber ())
{
//freshInfo = false;
if((m_routingType==1)||(m_routingType==2))
{
NS_LOG_ROUTING("checking prev " << i->bPrim << " " << i->gammaPrim << " " << i->totalE << " " << preq.GetBPrim () << " " << preq.GetGammaPrim () << " " << (int)preq.GetTotalE () << " " << (int)m_VBMetricMargin);
if((i->totalE+m_VBMetricMargin >= preq.GetTotalE ())&&(i->totalE <= preq.GetTotalE ()+m_VBMetricMargin))
{
if((i->metric+m_VBMetricMargin*10 >= preq.GetMetric ())&&(i->metric <= preq.GetMetric ()+m_VBMetricMargin*10))
{
if(m_routingType==1)
{
if(i->bPrim<=preq.GetBPrim ())
{
NS_LOG_ROUTING("b1 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else
{
if(i->bPrim>=preq.GetBPrim ())
{
NS_LOG_ROUTING("b2 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
}
else if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}
}
else
if(m_routingType==1)
{
if(i->totalE<=preq.GetTotalE ())
{
NS_LOG_ROUTING("totalE1 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else
{
if(i->totalE>=preq.GetTotalE ())
{
NS_LOG_ROUTING("totalE2 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
/*NS_LOG_ROUTING("checking prev " << (int)i->metric << " " << (int)preq.GetMetric () << " " << (int)m_VBMetricMargin);
if ((i->metric+m_VBMetricMargin >= preq.GetMetric ())&&(i->metric <= preq.GetMetric ()+m_VBMetricMargin))
{
// check energy metric
NS_LOG_ROUTING("in margin with one prev preq " << (int)i->metric << " " << (int)preq.GetMetric () << " " << (int)m_VBMetricMargin);
if((i->bPrim+i->gammaPrim*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ())>=(preq.GetBPrim ()+preq.GetGammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()))
{
NS_LOG_ROUTING("bgamma rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}*/
}
else
{
if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}
}
}
m_hwmpSeqnoMetricDatabase.erase (i);
break;
}
}
CnnBasedSeqnoMetricDatabase newDb;
newDb.originatorAddress=preq.GetOriginatorAddress();
newDb.originatorSeqNumber=preq.GetOriginatorSeqNumber();
newDb.metric=preq.GetMetric();
newDb.cnnType=preq.GetCnnType();
newDb.srcIpv4Addr=preq.GetSrcIpv4Addr();
newDb.dstIpv4Addr=preq.GetDstIpv4Addr();
newDb.srcPort=preq.GetSrcPort();
newDb.dstPort=preq.GetDstPort();
newDb.gammaPrim=preq.GetGammaPrim ();
newDb.bPrim=preq.GetBPrim ();
newDb.totalE=preq.GetTotalE ();
m_hwmpSeqnoMetricDatabase.push_back(newDb);
std::vector<Ptr<DestinationAddressUnit> > destinations = preq.GetDestinationList ();
//Add reverse path to originator:
m_rtable->AddCnnBasedReversePath (preq.GetOriginatorAddress(),from,interface,preq.GetCnnType(),preq.GetSrcIpv4Addr(),preq.GetDstIpv4Addr(),preq.GetSrcPort(),preq.GetDstPort(),Seconds(1),preq.GetOriginatorSeqNumber());
//Add reactive path to originator:
for (std::vector<Ptr<DestinationAddressUnit> >::const_iterator i = destinations.begin (); i != destinations.end (); i++)
{
NS_LOG_ROUTING("receivePReq " << preq.GetOriginatorAddress() << " " << from << " " << (*i)->GetDestinationAddress ());
std::vector<Ptr<DestinationAddressUnit> > preqDestinations = preq.GetDestinationList ();
Mac48Address preqDstMac;
if(preqDestinations.size ()==1){
std::vector<Ptr<DestinationAddressUnit> >::const_iterator preqDstMacIt =preqDestinations.begin ();
preqDstMac=(*preqDstMacIt)->GetDestinationAddress();
}else{
preqDstMac=GetAddress ();
}
if ((*i)->GetDestinationAddress () == GetAddress ())
{
// if(!duplicatePreq)
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(preq.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*preq.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceivePreqCACdestination " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)preq.GetRho () << " " << (int)preq.GetSigma () << " " << preq.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim ()< burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin()->second->HasEnoughCapacity4NewConnection(preq.GetOriginatorAddress (),preqDstMac,preq.GetHopCount (),from,preq.GetRho ()) ) )// CAC check
{
NS_LOG_ROUTING("cac rejected the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
return;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0_1 rejected the connection " << m_rtable->bPrim ());
return;
}
}
}
NS_LOG_ROUTING("schedule2sendPrep");
Schedule2sendPrep (
GetAddress (),
preq.GetOriginatorAddress (),
preq.GetMetric(),
preq.GetCnnType(),
preq.GetSrcIpv4Addr(),
preq.GetDstIpv4Addr(),
preq.GetSrcPort(),
preq.GetDstPort(),
preq.GetRho (),
preq.GetSigma (),
preq.GetStopTime (),
preq.GetDelayBound (),
preq.GetMaxPktSize (),
preq.GetOriginatorSeqNumber (),
GetNextHwmpSeqno (),
preq.GetLifetime (),
interface
);
//NS_ASSERT (m_rtable->LookupReactive (preq.GetOriginatorAddress ()).retransmitter != Mac48Address::GetBroadcast ());
preq.DelDestinationAddressElement ((*i)->GetDestinationAddress ());
continue;
}
else
{
// if(!duplicatePreq)
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = 2 * (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(preq.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = 2 * (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*preq.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceivePreqCACintermediate " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)preq.GetRho () << " " << (int)preq.GetSigma () << " " << preq.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim ()< burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin()->second->HasEnoughCapacity4NewConnection(preq.GetOriginatorAddress (),preqDstMac,preq.GetHopCount (),from,preq.GetRho ()) ) )// CAC check
{
NS_LOG_ROUTING("cac rejected the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
return;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0_2 rejected the connection " << m_rtable->bPrim ());
return;
}
}
}
if(m_routingType==1)
preq.UpdateVBMetricSum (m_rtable->gammaPrim (),m_rtable->bPrim ());
else if(m_routingType==2)
preq.UpdateVBMetricMin (m_rtable->gammaPrim (),m_rtable->bPrim ());
}
}
NS_LOG_DEBUG ("I am " << GetAddress () << "Accepted preq from address" << from << ", preq:" << preq);
//check if must retransmit:
if (preq.GetDestCount () == 0)
{
return;
}
//Forward PREQ to all interfaces:
NS_LOG_DEBUG ("I am " << GetAddress () << "retransmitting PREQ:" << preq);
NS_LOG_ROUTING("forwardPreq");
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
i->second->SendPreq (preq);
}
}
void
HwmpProtocol::Schedule2sendPrep(
Mac48Address src,
Mac48Address dst,
uint32_t initMetric,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
uint16_t rho,
uint16_t sigma,
Time stopTime,
Time delayBound,
uint16_t maxPktSize,
uint32_t originatorDsn,
uint32_t destinationSN,
uint32_t lifetime,
uint32_t interface)
{
for(std::vector<DelayedPrepStruct>::iterator dpsi=m_delayedPrepStruct.begin ();dpsi!=m_delayedPrepStruct.end ();dpsi++)
{
if(
(dpsi->destination==dst) &&
(dpsi->source==src) &&
(dpsi->cnnType==cnnType) &&
(dpsi->srcIpv4Addr==srcIpv4Addr) &&
(dpsi->dstIpv4Addr==dstIpv4Addr) &&
(dpsi->srcPort==srcPort) &&
(dpsi->dstPort==dstPort)
)
{
NS_LOG_ROUTING("scheduledBefore");
return;
}
}
DelayedPrepStruct dps;
dps.destination=dst;
dps.source=src;
dps.cnnType=cnnType;
dps.srcIpv4Addr=srcIpv4Addr;
dps.dstIpv4Addr=dstIpv4Addr;
dps.srcPort=srcPort;
dps.dstPort=dstPort;
dps.rho=rho;
dps.sigma=sigma;
dps.stopTime=stopTime;
dps.delayBound=delayBound;
dps.maxPktSize=maxPktSize;
dps.initMetric=initMetric;
dps.originatorDsn=originatorDsn;
dps.destinationSN=destinationSN;
dps.lifetime=lifetime;
dps.interface=interface;
dps.whenScheduled=Simulator::Now();
dps.prepTimeout=Simulator::Schedule(Seconds (0.1),&HwmpProtocol::SendDelayedPrep,this,dps);
NS_LOG_ROUTING("scheduled for " << "1" << " seconds");
m_delayedPrepStruct.push_back (dps);
}
void
HwmpProtocol::SendDelayedPrep(DelayedPrepStruct dps)
{
NS_LOG_ROUTING("trying to send prep to " << dps.destination);
HwmpRtable::CnnBasedLookupResult result=m_rtable->LookupCnnBasedReverse(dps.destination,dps.cnnType,dps.srcIpv4Addr,dps.dstIpv4Addr,dps.srcPort,dps.dstPort);
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
NS_LOG_ROUTING("cant find reverse path");
return;
}
//this is only for assigning a VB for this connection
if(!m_rtable->AddCnnBasedReactivePath (
dps.destination,
GetAddress (),
dps.source,
result.retransmitter,
dps.interface,
dps.cnnType,
dps.srcIpv4Addr,
dps.dstIpv4Addr,
dps.srcPort,
dps.dstPort,
dps.rho,
dps.sigma,
dps.stopTime,
dps.delayBound,
dps.maxPktSize,
Seconds (dps.lifetime),
dps.originatorDsn,
false,
m_doCAC))
{
return;
}
SendPrep (
GetAddress (),
dps.destination,
result.retransmitter,
dps.initMetric,
dps.cnnType,
dps.srcIpv4Addr,
dps.dstIpv4Addr,
dps.srcPort,
dps.dstPort,
dps.rho,
dps.sigma,
dps.stopTime,
dps.delayBound,
dps.maxPktSize,
dps.originatorDsn,
dps.destinationSN,
dps.lifetime,
dps.interface
);
NS_LOG_ROUTING("prep sent and AddCnnBasedReactivePath");
//std::vector<DelayedPrepStruct>::iterator it=std::find(m_delayedPrepStruct.begin (),m_delayedPrepStruct.end (),dps);
//if(it!=m_delayedPrepStruct.end ())
// m_delayedPrepStruct.erase (it); // we dont erase the entry from the vector cause of preventing to send prep twice
}
void
HwmpProtocol::ReceivePrep (IePrep prep, Mac48Address from, uint32_t interface, Mac48Address fromMp, uint32_t metric)
{
NS_LOG_UNCOND( Simulator::Now ().GetSeconds () << " " << (int)Simulator::GetContext () << " prep received " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort());
NS_LOG_ROUTING("prep received");
if(prep.GetDestinationAddress () == GetAddress ()){
NS_LOG_ROUTING("prep received for me");
CbrConnection connection;
connection.cnnType=prep.GetCnnType ();
connection.dstIpv4Addr=prep.GetDstIpv4Addr ();
connection.srcIpv4Addr=prep.GetSrcIpv4Addr ();
connection.dstPort=prep.GetDstPort ();
connection.srcPort=prep.GetSrcPort ();
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi!=m_notRoutedCbrConnections.end()){
NS_LOG_ROUTING("sourceCnnHasDropped " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
return;
}
}
prep.IncrementMetric (metric);
//acceptance cretirea:
bool freshInfo (true);
std::vector<CnnBasedSeqnoMetricDatabase>::iterator dbit;
for(std::vector<CnnBasedSeqnoMetricDatabase>::iterator i=m_hwmpSeqnoMetricDatabase.begin();i!=m_hwmpSeqnoMetricDatabase.end();i++)
{
if(
(i->originatorAddress==prep.GetOriginatorAddress()) &&
(i->cnnType==prep.GetCnnType()) &&
(i->srcIpv4Addr==prep.GetSrcIpv4Addr()) &&
(i->srcPort==prep.GetSrcPort()) &&
(i->dstIpv4Addr==prep.GetDstIpv4Addr()) &&
(i->dstPort==prep.GetDstPort())
)
{
if ((int32_t)(i->destinationSeqNumber - prep.GetDestinationSeqNumber()) > 0)
{
/*BarghiTest 1392/08/02 add for get result start*/
//commented for hadireports std::cout << "t:" << Simulator::Now() << " ,Im " << m_address << " returning because of older preq" << std::endl;
/*BarghiTest 1392/08/02 add for get result end*/
NS_LOG_ROUTING("hwmp droppedCPREP seqnum " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
return;
}
dbit=i;
freshInfo=false;
break;
}
}
if(freshInfo)
{
CnnBasedSeqnoMetricDatabase newDb;
newDb.originatorAddress=prep.GetOriginatorAddress();
newDb.originatorSeqNumber=prep.GetOriginatorSeqNumber();
newDb.destinationAddress=prep.GetDestinationAddress();
newDb.destinationSeqNumber=prep.GetDestinationSeqNumber();
newDb.metric=prep.GetMetric();
newDb.cnnType=prep.GetCnnType();
newDb.srcIpv4Addr=prep.GetSrcIpv4Addr();
newDb.dstIpv4Addr=prep.GetDstIpv4Addr();
newDb.srcPort=prep.GetSrcPort();
newDb.dstPort=prep.GetDstPort();
m_hwmpSeqnoMetricDatabase.push_back(newDb);
if (prep.GetDestinationAddress () == GetAddress ())
{
if(!m_rtable->AddCnnBasedReactivePath (
prep.GetOriginatorAddress (),
from,
GetAddress (),
GetAddress (),
interface,
prep.GetCnnType (),
prep.GetSrcIpv4Addr (),
prep.GetDstIpv4Addr (),
prep.GetSrcPort (),
prep.GetDstPort (),
prep.GetRho (),
prep.GetSigma (),
prep.GetStopTime (),
prep.GetDelayBound (),
prep.GetMaxPktSize (),
Seconds (10000),
prep.GetOriginatorSeqNumber (),
false,
m_doCAC))
{
NS_LOG_ROUTING("cac rejected at sourceWhenPrepReceived the connection ");
CbrConnection connection;
connection.destination=prep.GetOriginatorAddress ();
connection.source=GetAddress ();
connection.cnnType=prep.GetCnnType ();
connection.dstIpv4Addr=prep.GetDstIpv4Addr ();
connection.srcIpv4Addr=prep.GetSrcIpv4Addr ();
connection.dstPort=prep.GetDstPort ();
connection.srcPort=prep.GetSrcPort ();
m_notRoutedCbrConnections.push_back (connection);
return;
}
m_rtable->AddPrecursor (prep.GetDestinationAddress (), interface, from,
MicroSeconds (prep.GetLifetime () * 1024));
/*if (result.retransmitter != Mac48Address::GetBroadcast ())
{
m_rtable->AddPrecursor (prep.GetOriginatorAddress (), interface, result.retransmitter,
result.lifetime);
}*/
//ReactivePathResolved (prep.GetOriginatorAddress ());
NS_LOG_ROUTING("hwmp routing pathResolved and AddCnnBasedReactivePath " << prep.GetOriginatorAddress ()<< " " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
CnnBasedReactivePathResolved(prep.GetOriginatorAddress (),GetAddress (),prep.GetCnnType (),prep.GetSrcIpv4Addr (),prep.GetDstIpv4Addr (),prep.GetSrcPort (),prep.GetDstPort ());
m_CbrCnnStateChanged(prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),true);
InsertCbrCnnAtSourceIntoSourceCbrCnnsVector(prep.GetOriginatorAddress(),GetAddress (),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),GetAddress(),from);
NS_LOG_DEBUG ("I am "<<GetAddress ()<<", resolved "<<prep.GetOriginatorAddress ());
return;
}
}else
{
NS_LOG_ROUTING("duplicate prep not allowed!");
NS_ASSERT(false);
}
//update routing info
//Now add a path to destination and add precursor to source
NS_LOG_DEBUG ("I am " << GetAddress () << ", received prep from " << prep.GetOriginatorAddress () << ", receiver was:" << from);
HwmpRtable::CnnBasedLookupResult result=m_rtable->LookupCnnBasedReverse(prep.GetDestinationAddress(),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort());
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
NS_LOG_ROUTING("cant find reverse path 2");
return;
}
if(!m_rtable->AddCnnBasedReactivePath ( prep.GetOriginatorAddress (),
from,
prep.GetDestinationAddress (),
result.retransmitter,
interface,
prep.GetCnnType (),
prep.GetSrcIpv4Addr (),
prep.GetDstIpv4Addr (),
prep.GetSrcPort (),
prep.GetDstPort (),
prep.GetRho (),
prep.GetSigma (),
prep.GetStopTime (),
prep.GetDelayBound (),
prep.GetMaxPktSize (),
Seconds (10000),
prep.GetOriginatorSeqNumber (),
true,
m_doCAC))
{
NS_LOG_ROUTING("cnnRejectedAtPrep " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort());
return;
}
InsertCbrCnnIntoCbrCnnsVector(prep.GetOriginatorAddress(),prep.GetDestinationAddress(),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),result.retransmitter,from);
//Forward PREP
NS_LOG_ROUTING("hwmp routing pathSaved and AddCnnBasedReactivePath and SendPrep " << prep.GetOriginatorAddress () << " " << result.retransmitter << " " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from << " " << result.retransmitter);
HwmpProtocolMacMap::const_iterator prep_sender = m_interfaces.find (result.ifIndex);
NS_ASSERT (prep_sender != m_interfaces.end ());
prep_sender->second->SendPrep (prep, result.retransmitter);
}
void
HwmpProtocol::InsertCbrCnnAtSourceIntoSourceCbrCnnsVector(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
Mac48Address prevHop,
Mac48Address nextHop
){
NS_LOG_ROUTING("hwmp inserting cnn into cnnsvector at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
connection.prevMac=prevHop;
connection.nextMac=nextHop;
connection.whenExpires=Simulator::Now()+MilliSeconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
CbrConnectionsVector::iterator ccvi=std::find(m_sourceCbrConnections.begin(),m_sourceCbrConnections.end(),connection);
if(ccvi==m_sourceCbrConnections.end()){
NS_LOG_ROUTING("hwmp new, inserted at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
m_sourceCbrConnections.push_back(connection);
}else{
NS_LOG_ROUTING("hwmp exist, expiration extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
ccvi->whenExpires=Simulator::Now()+Seconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
}
}
void
HwmpProtocol::SourceCbrRouteExtend(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
){
NS_LOG_ROUTING("hwmp cbr route extend at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
CbrConnectionsVector::iterator ccvi=std::find(m_sourceCbrConnections.begin(),m_sourceCbrConnections.end(),connection);
if(ccvi!=m_sourceCbrConnections.end()){
NS_LOG_ROUTING("hwmp cbr route really found and extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
ccvi->whenExpires=Simulator::Now()+MilliSeconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
}else{
NS_LOG_ROUTING("hwmp cbr route not found and not extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
}
void
HwmpProtocol::InsertCbrCnnIntoCbrCnnsVector(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
Mac48Address prevHop,
Mac48Address nextHop
){
NS_LOG_ROUTING("hwmp inserting cnn into cnnsvector " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
connection.prevMac=prevHop;
connection.nextMac=nextHop;
connection.whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
//connection.routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),connection);
if(ccvi==m_cbrConnections.end()){
NS_LOG_ROUTING("hwmp new, inserted " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
m_cbrConnections.push_back(connection);
}else{
NS_LOG_ROUTING("hwmp exist, expiration extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
ccvi->whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
ccvi->nextMac=nextHop;
ccvi->prevMac=prevHop;
//m_cbrConnections.erase(ccvi);
//m_cbrConnections.push_back(connection);
//ccvi->routeExpireEvent.Cancel();
//ccvi->routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
}
}
void
HwmpProtocol::CbrRouteExtend(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
){
NS_LOG_ROUTING("hwmp cbr route extend " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),connection);
if(ccvi!=m_cbrConnections.end()){
NS_LOG_ROUTING("hwmp cbr route really found and extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
ccvi->whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
//ccvi->routeExpireEvent.Cancel();
//ccvi->routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
}else{
NS_LOG_ROUTING("hwmp cbr route not found and not extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
}
void
HwmpProtocol::CbrRouteExpire(CbrConnection cbrCnn){
NS_LOG_ROUTING("hwmp cbr route expired " << cbrCnn.srcIpv4Addr << ":" << (int)cbrCnn.srcPort << "=>" << cbrCnn.dstIpv4Addr << ":" << (int)cbrCnn.dstPort << " n " << cbrCnn.nextMac << " p " << cbrCnn.prevMac);
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),cbrCnn);
if(ccvi!=m_cbrConnections.end()){
m_cbrConnections.erase(ccvi);
m_rtable->DeleteCnnBasedReactivePath(cbrCnn.destination,cbrCnn.source,cbrCnn.cnnType,cbrCnn.srcIpv4Addr,cbrCnn.dstIpv4Addr,cbrCnn.srcPort,cbrCnn.dstPort);
NS_LOG_ROUTING("hwmp cbr route deleted " << cbrCnn.srcIpv4Addr << ":" << (int)cbrCnn.srcPort << "=>" << cbrCnn.dstIpv4Addr << ":" << (int)cbrCnn.dstPort << " n " << cbrCnn.nextMac << " p " << cbrCnn.prevMac);
}
}
void
HwmpProtocol::CheckCbrRoutes4Expiration(){
CbrConnectionsVector tempvector;
bool changed=false;
for(CbrConnectionsVector::iterator ccvi=m_cbrConnections.begin();ccvi!=m_cbrConnections.end();ccvi++){
if(Simulator::Now()<ccvi->whenExpires){
tempvector.push_back(*ccvi);
}else{
changed = true;
m_rtable->DeleteCnnBasedReactivePath(ccvi->destination,ccvi->source,ccvi->cnnType,ccvi->srcIpv4Addr,ccvi->dstIpv4Addr,ccvi->srcPort,ccvi->dstPort);
NS_LOG_ROUTING("hwmp cbr route expired and deleted " << ccvi->srcIpv4Addr << ":" << (int)ccvi->srcPort << "=>" << ccvi->dstIpv4Addr << ":" << (int)ccvi->dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
}
}
if(changed){
m_cbrConnections.clear();
m_cbrConnections=tempvector;
NS_LOG_ROUTING("hwmp num connections " << m_cbrConnections.size());
}
tempvector.clear();
for(CbrConnectionsVector::iterator ccvi=m_sourceCbrConnections.begin();ccvi!=m_sourceCbrConnections.end();ccvi++){
if(Simulator::Now()<ccvi->whenExpires){
tempvector.push_back(*ccvi);
}else{
changed = true;
m_CbrCnnStateChanged(ccvi->srcIpv4Addr,ccvi->dstIpv4Addr,ccvi->srcPort,ccvi->dstPort,false);
}
}
if(changed){
m_sourceCbrConnections.clear();
m_sourceCbrConnections=tempvector;
}
Simulator::Schedule(MilliSeconds(50),&HwmpProtocol::CheckCbrRoutes4Expiration,this);
}
void
HwmpProtocol::ReceivePerr (std::vector<FailedDestination> destinations, Mac48Address from, uint32_t interface, Mac48Address fromMp)
{
//Acceptance cretirea:
NS_LOG_DEBUG ("I am "<<GetAddress ()<<", received PERR from "<<from);
std::vector<FailedDestination> retval;
HwmpRtable::LookupResult result;
for (unsigned int i = 0; i < destinations.size (); i++)
{
result = m_rtable->LookupReactiveExpired (destinations[i].destination);
if (!(
(result.retransmitter != from) ||
(result.ifIndex != interface) ||
((int32_t)(result.seqnum - destinations[i].seqnum) > 0)
))
{
retval.push_back (destinations[i]);
}
}
if (retval.size () == 0)
{
return;
}
ForwardPathError (MakePathError (retval));
}
void
HwmpProtocol::SendPrep (Mac48Address src,
Mac48Address dst,
Mac48Address retransmitter,
uint32_t initMetric,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
uint16_t rho,
uint16_t sigma,
Time stopTime, Time delayBound, uint16_t maxPktSize,
uint32_t originatorDsn,
uint32_t destinationSN,
uint32_t lifetime,
uint32_t interface)
{
IePrep prep;
prep.SetHopcount (0);
prep.SetTtl (m_maxTtl);
prep.SetDestinationAddress (dst);
prep.SetDestinationSeqNumber (destinationSN);
prep.SetLifetime (lifetime);
prep.SetMetric (initMetric);
prep.SetCnnParams(cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
prep.SetRho (rho);
prep.SetSigma (sigma);
prep.SetStopTime (stopTime);
prep.SetDelayBound (delayBound);
prep.SetMaxPktSize (maxPktSize);
prep.SetOriginatorAddress (src);
prep.SetOriginatorSeqNumber (originatorDsn);
HwmpProtocolMacMap::const_iterator prep_sender = m_interfaces.find (interface);
NS_ASSERT (prep_sender != m_interfaces.end ());
prep_sender->second->SendPrep (prep, retransmitter);
m_stats.initiatedPrep++;
}
bool
HwmpProtocol::Install (Ptr<MeshPointDevice> mp)
{
m_mp = mp;
std::vector<Ptr<NetDevice> > interfaces = mp->GetInterfaces ();
for (std::vector<Ptr<NetDevice> >::const_iterator i = interfaces.begin (); i != interfaces.end (); i++)
{
// Checking for compatible net device
Ptr<WifiNetDevice> wifiNetDev = (*i)->GetObject<WifiNetDevice> ();
if (wifiNetDev == 0)
{
return false;
}
Ptr<MeshWifiInterfaceMac> mac = wifiNetDev->GetMac ()->GetObject<MeshWifiInterfaceMac> ();
if (mac == 0)
{
return false;
}
// Installing plugins:
Ptr<HwmpProtocolMac> hwmpMac = Create<HwmpProtocolMac> (wifiNetDev->GetIfIndex (), this);
m_interfaces[wifiNetDev->GetIfIndex ()] = hwmpMac;
mac->InstallPlugin (hwmpMac);
//Installing airtime link metric:
Ptr<AirtimeLinkMetricCalculator> metric = CreateObject <AirtimeLinkMetricCalculator> ();
mac->SetLinkMetricCallback (MakeCallback (&AirtimeLinkMetricCalculator::CalculateMetric, metric));
}
mp->SetRoutingProtocol (this);
// Mesh point aggregates all installed protocols
mp->AggregateObject (this);
m_address = Mac48Address::ConvertFrom (mp->GetAddress ()); // address;
return true;
}
void
HwmpProtocol::PeerLinkStatus (Mac48Address meshPointAddress, Mac48Address peerAddress, uint32_t interface, bool status)
{
if (status)
{
return;
}
std::vector<FailedDestination> destinations = m_rtable->GetUnreachableDestinations (peerAddress);
InitiatePathError (MakePathError (destinations));
}
void
HwmpProtocol::SetNeighboursCallback (Callback<std::vector<Mac48Address>, uint32_t> cb)
{
m_neighboursCallback = cb;
}
bool
HwmpProtocol::DropDataFrame (uint32_t seqno, Mac48Address source)
{
if (source == GetAddress ())
{
return true;
}
std::map<Mac48Address, uint32_t,std::less<Mac48Address> >::const_iterator i = m_lastDataSeqno.find (source);
if (i == m_lastDataSeqno.end ())
{
m_lastDataSeqno[source] = seqno;
}
else
{
if ((int32_t)(i->second - seqno) >= 0)
{
return true;
}
m_lastDataSeqno[source] = seqno;
}
return false;
}
HwmpProtocol::PathError
HwmpProtocol::MakePathError (std::vector<FailedDestination> destinations)
{
PathError retval;
//HwmpRtable increments a sequence number as written in 11B.9.7.2
retval.receivers = GetPerrReceivers (destinations);
if (retval.receivers.size () == 0)
{
return retval;
}
m_stats.initiatedPerr++;
for (unsigned int i = 0; i < destinations.size (); i++)
{
retval.destinations.push_back (destinations[i]);
m_rtable->DeleteReactivePath (destinations[i].destination);
}
return retval;
}
void
HwmpProtocol::InitiatePathError (PathError perr)
{
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
std::vector<Mac48Address> receivers_for_interface;
for (unsigned int j = 0; j < perr.receivers.size (); j++)
{
if (i->first == perr.receivers[j].first)
{
receivers_for_interface.push_back (perr.receivers[j].second);
}
}
i->second->InitiatePerr (perr.destinations, receivers_for_interface);
}
}
void
HwmpProtocol::ForwardPathError (PathError perr)
{
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
std::vector<Mac48Address> receivers_for_interface;
for (unsigned int j = 0; j < perr.receivers.size (); j++)
{
if (i->first == perr.receivers[j].first)
{
receivers_for_interface.push_back (perr.receivers[j].second);
}
}
i->second->ForwardPerr (perr.destinations, receivers_for_interface);
}
}
std::vector<std::pair<uint32_t, Mac48Address> >
HwmpProtocol::GetPerrReceivers (std::vector<FailedDestination> failedDest)
{
HwmpRtable::PrecursorList retval;
for (unsigned int i = 0; i < failedDest.size (); i++)
{
HwmpRtable::PrecursorList precursors = m_rtable->GetPrecursors (failedDest[i].destination);
m_rtable->DeleteReactivePath (failedDest[i].destination);
m_rtable->DeleteProactivePath (failedDest[i].destination);
for (unsigned int j = 0; j < precursors.size (); j++)
{
retval.push_back (precursors[j]);
}
}
//Check if we have dublicates in retval and precursors:
for (unsigned int i = 0; i < retval.size (); i++)
{
for (unsigned int j = i+1; j < retval.size (); j++)
{
if (retval[i].second == retval[j].second)
{
retval.erase (retval.begin () + j);
}
}
}
return retval;
}
std::vector<Mac48Address>
HwmpProtocol::GetPreqReceivers (uint32_t interface)
{
std::vector<Mac48Address> retval;
if (!m_neighboursCallback.IsNull ())
{
retval = m_neighboursCallback (interface);
}
if ((retval.size () >= m_unicastPreqThreshold) || (retval.size () == 0))
{
retval.clear ();
retval.push_back (Mac48Address::GetBroadcast ());
}
return retval;
}
std::vector<Mac48Address>
HwmpProtocol::GetBroadcastReceivers (uint32_t interface)
{
std::vector<Mac48Address> retval;
if (!m_neighboursCallback.IsNull ())
{
retval = m_neighboursCallback (interface);
}
if ((retval.size () >= m_unicastDataThreshold) || (retval.size () == 0))
{
retval.clear ();
retval.push_back (Mac48Address::GetBroadcast ());
}
return retval;
}
bool
HwmpProtocol::QueuePacket (QueuedPacket packet)
{
if (m_rqueue.size () >= m_maxQueueSize)
{
NS_LOG_CAC("packetDroppedAtHwmp " << (int)packet.pkt->GetUid () << " " << m_rqueue.size ());
return false;
}
m_rqueue.push_back (packet);
return true;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacketByCnnParams (
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
QueuedPacket retval;
retval.pkt = 0;
NS_LOG_ROUTING("hwmp DequeueFirstPacketByCnnParams " << (int)m_rqueue.size());
for (std::vector<QueuedPacket>::iterator i = m_rqueue.begin (); i != m_rqueue.end (); i++)
{
if (
((*i).dst == dst) &&
((*i).src == src) &&
((*i).cnnType == cnnType) &&
((*i).srcIpv4Addr == srcIpv4Addr) &&
((*i).dstIpv4Addr == dstIpv4Addr) &&
((*i).srcPort == srcPort) &&
((*i).dstPort == dstPort)
)
{
retval = (*i);
m_rqueue.erase (i);
break;
}
}
//std::cout << Simulator::Now().GetSeconds() << " " << m_address << " SourceQueueSize " << m_rqueue.size() << std::endl;
return retval;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacketByDst (Mac48Address dst)
{
QueuedPacket retval;
retval.pkt = 0;
for (std::vector<QueuedPacket>::iterator i = m_rqueue.begin (); i != m_rqueue.end (); i++)
{
if ((*i).dst == dst)
{
retval = (*i);
m_rqueue.erase (i);
break;
}
}
return retval;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacket ()
{
QueuedPacket retval;
retval.pkt = 0;
if (m_rqueue.size () != 0)
{
retval = m_rqueue[0];
m_rqueue.erase (m_rqueue.begin ());
}
return retval;
}
void
HwmpProtocol::ReactivePathResolved (Mac48Address dst)
{
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
if (i != m_preqTimeouts.end ())
{
m_routeDiscoveryTimeCallback (Simulator::Now () - i->second.whenScheduled);
}
HwmpRtable::LookupResult result = m_rtable->LookupReactive (dst);
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
//Send all packets stored for this destination
QueuedPacket packet = DequeueFirstPacketByDst (dst);
while (packet.pkt != 0)
{
if(packet.src==GetAddress()){
NS_LOG_ROUTING("tx4mSource2 " << (int)packet.pkt->GetUid());
}
//set RA tag for retransmitter:
HwmpTag tag;
packet.pkt->RemovePacketTag (tag);
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
packet = DequeueFirstPacketByDst (dst);
}
}
void
HwmpProtocol::CnnBasedReactivePathResolved (
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
HwmpRtable::CnnBasedLookupResult result = m_rtable->LookupCnnBasedReactive(dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
//Send all packets stored for this destination
QueuedPacket packet = DequeueFirstPacketByCnnParams (dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
while (packet.pkt != 0)
{
if((packet.src==GetAddress())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)){
NS_LOG_ROUTING("tx4mSource2 " << (int)packet.pkt->GetUid());
NS_LOG_CAC("tx4mSource2 " << (int)packet.pkt->GetUid());
m_txed4mSourceCallback();
}
//set RA tag for retransmitter:
HwmpTag tag;
packet.pkt->RemovePacketTag (tag);
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
//packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
// m_rtable->QueueCnnBasedPacket (packet.dst,packet.src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,packet.pkt,packet.protocol,result.ifIndex,packet.reply);
packet = DequeueFirstPacketByCnnParams (dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
}
void
HwmpProtocol::ProactivePathResolved ()
{
//send all packets to root
HwmpRtable::LookupResult result = m_rtable->LookupProactive ();
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
QueuedPacket packet = DequeueFirstPacket ();
while (packet.pkt != 0)
{
//set RA tag for retransmitter:
HwmpTag tag;
if (!packet.pkt->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag must be present at this point");
}
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
packet = DequeueFirstPacket ();
}
}
bool
HwmpProtocol::ShouldSendPreq (Mac48Address dst)
{
std::map<Mac48Address, PreqEvent>::const_iterator i = m_preqTimeouts.find (dst);
if (i == m_preqTimeouts.end ())
{
m_preqTimeouts[dst].preqTimeout = Simulator::Schedule (
Time (m_dot11MeshHWMPnetDiameterTraversalTime * 2),
&HwmpProtocol::RetryPathDiscovery, this, dst, 1);
m_preqTimeouts[dst].whenScheduled = Simulator::Now ();
return true;
}
return false;
}
bool
HwmpProtocol::CnnBasedShouldSendPreq (
RhoSigmaTag rsTag,
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==dst) &&
(cbpei->source==src) &&
(cbpei->cnnType==cnnType) &&
(cbpei->srcIpv4Addr==srcIpv4Addr) &&
(cbpei->dstIpv4Addr==dstIpv4Addr) &&
(cbpei->srcPort==srcPort) &&
(cbpei->dstPort==dstPort)
)
{
return false;
}
}
if(src==GetAddress ())
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(rsTag.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(rsTag.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*rsTag.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(rsTag.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceiveFirstPacketCACCheck " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)rsTag.GetRho () << " " << (int)rsTag.GetSigma () << " " << rsTag.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim () < burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin ()->second->HasEnoughCapacity4NewConnection (GetAddress (),dst,0,GetAddress (),rsTag.GetRho ())) )// CAC check
{
NS_LOG_ROUTING("cac rejected at source the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
CbrConnection connection;
connection.destination=dst;
connection.source=src;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
m_notRoutedCbrConnections.push_back (connection);
return false;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0 rejected at source the connection " << m_rtable->bPrim ());
CbrConnection connection;
connection.destination=dst;
connection.source=src;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
m_notRoutedCbrConnections.push_back (connection);
return false;
}
}
}
CnnBasedPreqEvent cbpe;
cbpe.destination=dst;
cbpe.source=src;
cbpe.cnnType=cnnType;
cbpe.srcIpv4Addr=srcIpv4Addr;
cbpe.dstIpv4Addr=dstIpv4Addr;
cbpe.srcPort=srcPort;
cbpe.dstPort=dstPort;
cbpe.rho=rsTag.GetRho ();
cbpe.sigma=rsTag.GetSigma ();
cbpe.stopTime=rsTag.GetStopTime ();
cbpe.delayBound=rsTag.delayBound ();
cbpe.maxPktSize=rsTag.maxPktSize ();
cbpe.whenScheduled=Simulator::Now();
cbpe.preqTimeout=Simulator::Schedule(
Time (m_dot11MeshHWMPnetDiameterTraversalTime * 2),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,cbpe,1);
m_cnnBasedPreqTimeouts.push_back(cbpe);
NS_LOG_ROUTING("need to send preq");
return true;
}
void
HwmpProtocol::RetryPathDiscovery (Mac48Address dst, uint8_t numOfRetry)
{
HwmpRtable::LookupResult result = m_rtable->LookupReactive (dst);
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
result = m_rtable->LookupProactive ();
}
if (result.retransmitter != Mac48Address::GetBroadcast ())
{
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
NS_ASSERT (i != m_preqTimeouts.end ());
m_preqTimeouts.erase (i);
return;
}
if (numOfRetry > m_dot11MeshHWMPmaxPREQretries)
{
NS_LOG_ROUTING("givingUpPathRequest " << dst);
QueuedPacket packet = DequeueFirstPacketByDst (dst);
//purge queue and delete entry from retryDatabase
while (packet.pkt != 0)
{
m_stats.totalDropped++;
packet.reply (false, packet.pkt, packet.src, packet.dst, packet.protocol, HwmpRtable::MAX_METRIC);
packet = DequeueFirstPacketByDst (dst);
}
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
NS_ASSERT (i != m_preqTimeouts.end ());
m_routeDiscoveryTimeCallback (Simulator::Now () - i->second.whenScheduled);
m_preqTimeouts.erase (i);
return;
}
numOfRetry++;
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = m_rtable->LookupReactiveExpired (dst).seqnum;
NS_LOG_ROUTING("retryPathRequest " << dst);
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
Ipv4Address tempadd;
if(m_routingType==2)
i->second->RequestDestination (dst, originator_seqno, dst_seqno,HwmpRtable::CNN_TYPE_PKT_BASED,tempadd,tempadd,0,0,0,0,Seconds (0),Seconds (0),0,0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (dst, originator_seqno, dst_seqno,HwmpRtable::CNN_TYPE_PKT_BASED,tempadd,tempadd,0,0,0,0,Seconds (0),Seconds (0),0,0,0,0);
}
m_preqTimeouts[dst].preqTimeout = Simulator::Schedule (
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::RetryPathDiscovery, this, dst, numOfRetry);
}
void
HwmpProtocol::CnnBasedRetryPathDiscovery (
CnnBasedPreqEvent preqEvent,
uint8_t numOfRetry
)
{
HwmpRtable::CnnBasedLookupResult result = m_rtable->LookupCnnBasedReactive(preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
if (result.retransmitter != Mac48Address::GetBroadcast ())
{
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->source==preqEvent.source) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
m_cnnBasedPreqTimeouts.erase(cbpei);
return;
}
}
NS_ASSERT (false);
return;
}
if (numOfRetry > m_dot11MeshHWMPmaxPREQretries)
{
//hadireport reject connection
NS_LOG_ROUTING("hwmp connectionRejected " << preqEvent.destination << " " << preqEvent.srcIpv4Addr << ":" << (int)preqEvent.srcPort << "=>" << preqEvent.dstIpv4Addr << ":" << (int)preqEvent.dstPort);
QueuedPacket packet = DequeueFirstPacketByCnnParams (preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
CbrConnection connection;
connection.destination=preqEvent.destination;
connection.source=preqEvent.source;
connection.cnnType=preqEvent.cnnType;
connection.dstIpv4Addr=preqEvent.dstIpv4Addr;
connection.srcIpv4Addr=preqEvent.srcIpv4Addr;
connection.dstPort=preqEvent.dstPort;
connection.srcPort=preqEvent.srcPort;
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi==m_notRoutedCbrConnections.end()){
m_notRoutedCbrConnections.push_back(connection);
}
//purge queue and delete entry from retryDatabase
while (packet.pkt != 0)
{
if(packet.src==GetAddress()){
NS_LOG_ROUTING("hwmp noRouteDrop2 " << (int)packet.pkt->GetUid() << " " << preqEvent.srcIpv4Addr << ":" << (int)preqEvent.srcPort << "=>" << preqEvent.dstIpv4Addr << ":" << (int)preqEvent.dstPort);
}
m_stats.totalDropped++;
packet.reply (false, packet.pkt, packet.src, packet.dst, packet.protocol, HwmpRtable::MAX_METRIC);
packet = DequeueFirstPacketByCnnParams (preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
}
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
m_cnnBasedPreqTimeouts.erase(cbpei);
return;
}
}
NS_ASSERT (false);
return;
}
numOfRetry++;
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = 0;
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
if(m_routingType==2)
i->second->RequestDestination (preqEvent.destination, originator_seqno, dst_seqno, preqEvent.cnnType, preqEvent.srcIpv4Addr, preqEvent.dstIpv4Addr, preqEvent.srcPort, preqEvent.dstPort,preqEvent.rho,preqEvent.sigma,preqEvent.stopTime,preqEvent.delayBound,preqEvent.maxPktSize, 0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (preqEvent.destination, originator_seqno, dst_seqno, preqEvent.cnnType, preqEvent.srcIpv4Addr, preqEvent.dstIpv4Addr, preqEvent.srcPort, preqEvent.dstPort,preqEvent.rho,preqEvent.sigma,preqEvent.stopTime,preqEvent.delayBound,preqEvent.maxPktSize, 0,0,0);
}
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
cbpei->preqTimeout=Simulator::Schedule(
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,(*cbpei),numOfRetry);
cbpei->whenScheduled=Simulator::Now();
return;
}
}
CnnBasedPreqEvent cbpe;
cbpe.destination=preqEvent.destination;
cbpe.cnnType=preqEvent.cnnType;
cbpe.srcIpv4Addr=preqEvent.srcIpv4Addr;
cbpe.dstIpv4Addr=preqEvent.dstIpv4Addr;
cbpe.srcPort=preqEvent.srcPort;
cbpe.dstPort=preqEvent.dstPort;
cbpe.whenScheduled=Simulator::Now();
cbpe.preqTimeout=Simulator::Schedule(
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,cbpe,numOfRetry);
m_cnnBasedPreqTimeouts.push_back(cbpe);
}
//Proactive PREQ routines:
void
HwmpProtocol::SetRoot ()
{
Time randomStart = Seconds (m_coefficient->GetValue ());
m_proactivePreqTimer = Simulator::Schedule (randomStart, &HwmpProtocol::SendProactivePreq, this);
NS_LOG_DEBUG ("ROOT IS: " << m_address);
m_isRoot = true;
}
void
HwmpProtocol::UnsetRoot ()
{
m_proactivePreqTimer.Cancel ();
}
void
HwmpProtocol::SendProactivePreq ()
{
IePreq preq;
//By default: must answer
preq.SetHopcount (0);
preq.SetTTL (m_maxTtl);
preq.SetLifetime (m_dot11MeshHWMPactiveRootTimeout.GetMicroSeconds () /1024);
//\attention: do not forget to set originator address, sequence
//number and preq ID in HWMP-MAC plugin
preq.AddDestinationAddressElement (true, true, Mac48Address::GetBroadcast (), 0);
preq.SetOriginatorAddress (GetAddress ());
preq.SetPreqID (GetNextPreqId ());
preq.SetOriginatorSeqNumber (GetNextHwmpSeqno ());
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
i->second->SendPreq (preq);
}
m_proactivePreqTimer = Simulator::Schedule (m_dot11MeshHWMPpathToRootInterval, &HwmpProtocol::SendProactivePreq, this);
}
bool
HwmpProtocol::GetDoFlag ()
{
return m_doFlag;
}
bool
HwmpProtocol::GetRfFlag ()
{
return m_rfFlag;
}
Time
HwmpProtocol::GetPreqMinInterval ()
{
return m_dot11MeshHWMPpreqMinInterval;
}
Time
HwmpProtocol::GetPerrMinInterval ()
{
return m_dot11MeshHWMPperrMinInterval;
}
uint8_t
HwmpProtocol::GetMaxTtl ()
{
return m_maxTtl;
}
uint32_t
HwmpProtocol::GetNextPreqId ()
{
m_preqId++;
return m_preqId;
}
uint32_t
HwmpProtocol::GetNextHwmpSeqno ()
{
m_hwmpSeqno++;
return m_hwmpSeqno;
}
uint32_t
HwmpProtocol::GetActivePathLifetime ()
{
return m_dot11MeshHWMPactivePathTimeout.GetMicroSeconds () / 1024;
}
uint8_t
HwmpProtocol::GetUnicastPerrThreshold ()
{
return m_unicastPerrThreshold;
}
Mac48Address
HwmpProtocol::GetAddress ()
{
return m_address;
}
void
HwmpProtocol::EnergyChange (Ptr<Packet> packet,bool isAck, bool incDec, double energy, double remainedEnergy,uint32_t packetSize)
{
uint8_t cnnType;//1:mac only, 2:ip only , 3:ip port
Ipv4Address srcIpv4Addr;
Ipv4Address dstIpv4Addr;
uint16_t srcPort;
uint16_t dstPort;
if(packet!=0)
{
WifiMacHeader wmhdr;
packet->RemoveHeader (wmhdr);
WifiMacTrailer fcs;
packet->RemoveTrailer (fcs);
MeshHeader meshHdr;
packet->RemoveHeader (meshHdr);
LlcSnapHeader llc;
packet->RemoveHeader (llc);
NS_LOG_VB("rxtx packet llc protocol type " << llc.GetType ());
if(llc.GetType ()==Ipv4L3Protocol::PROT_NUMBER)
{
Ipv4Header ipv4Hdr;
packet->RemoveHeader(ipv4Hdr);
srcIpv4Addr = ipv4Hdr.GetSource();
dstIpv4Addr = ipv4Hdr.GetDestination();
uint8_t protocol = ipv4Hdr.GetProtocol();
if(protocol==TcpL4Protocol::PROT_NUMBER)
{
TcpHeader tcpHdr;
packet->RemoveHeader (tcpHdr);
srcPort=tcpHdr.GetSourcePort ();
dstPort=tcpHdr.GetDestinationPort ();
cnnType=HwmpRtable::CNN_TYPE_PKT_BASED;
}
else if(protocol==UdpL4Protocol::PROT_NUMBER)
{
UdpHeader udpHdr;
packet->RemoveHeader(udpHdr);
srcPort=udpHdr.GetSourcePort();
dstPort=udpHdr.GetDestinationPort();
cnnType=HwmpRtable::CNN_TYPE_IP_PORT;
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
}
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
}
}
double systemB=m_rtable->systemB ();
if(incDec)//increased
{
systemB+=energy;
if(systemB>m_rtable->systemBMax ())
systemB=m_rtable->systemBMax ();
if(packet==0)//increased by gamma or energyback
{
if(packetSize==0)//increased by gamma
{
m_rtable->TotalEnergyIncreasedByGamma (energy);
}
else//increased by collision energy back of other packets
{
m_rtable->ControlEnergyIncreasedByCollisionEnergyBack (energy);
}
}else//increased by collision energy back
{
m_rtable->ChangeEnergy4aConnection (cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,energy,true);
}
}else//decreased
{
systemB-=energy;
if(systemB<0)
systemB=0;
if(packet==0)
{
if(packetSize!=0)//decreased by other types of packets
{
if(m_noDataPacketYet)
{
m_energyPerByte = 0.7 * m_energyPerByte + 0.3 * energy/packetSize;
m_rtable->SetMaxEnergyPerAckPacket (m_energyPerByte*14);
m_rtable->SetMaxEnergyPerDataPacket (m_energyPerByte*260);
//NS_LOG_VB("energyPerAckByte " << m_energyPerByte*14);
//NS_LOG_VB("energyPerDataByte " << m_energyPerByte*260);
}
}
m_rtable->ControlPacketsEnergyDecreased (energy);
}
else//decreased by data or ack for data packets
{
m_noDataPacketYet=false;
if(isAck )
{
if(energy > m_rtable->GetMaxEnergyPerAckPacket ())
m_rtable->SetMaxEnergyPerAckPacket (energy);
//NS_LOG_VB("energyPerAck " << energy);
}
else if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)
{
if(energy > m_rtable->GetMaxEnergyPerDataPacket ())
m_rtable->SetMaxEnergyPerDataPacket (energy);
//NS_LOG_VB("energyPerData " << energy);
}
if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)
{
m_rtable->ChangeEnergy4aConnection (cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,energy,false);
}
else
{
m_rtable->ControlPacketsEnergyDecreased (energy);
}
}
}
if(std::abs(systemB-remainedEnergy)>1)
{
NS_LOG_VB("remainedEnergyError " << systemB << " " << remainedEnergy);
}
else
{
//NS_LOG_VB("remainedEnergy " << systemB << " " << remainedEnergy);
}
m_rtable->setSystemB (remainedEnergy);
}
void
HwmpProtocol::GammaChange(double gamma, double totalSimmTime)
{
m_totalSimulationTime=totalSimmTime;
double remainedSimulationTimeSeconds=m_totalSimulationTime-Simulator::Now ().GetSeconds ();
double remainedControlEnergyNeeded=remainedSimulationTimeSeconds*0.035;
//double remainedControlEnergyNeeded=remainedSimulationTimeSeconds*0;
double bPrim=m_rtable->bPrim ()+m_rtable->controlB ();
double gammaPrim=m_rtable->gammaPrim ()+m_rtable->controlGamma ();
double assignedGamma=m_rtable->assignedGamma ()-m_rtable->controlGamma ();
if(bPrim>=remainedControlEnergyNeeded)
{
m_rtable->setControlB (remainedControlEnergyNeeded);
m_rtable->setControlBMax (remainedControlEnergyNeeded);
m_rtable->setControlGamma (0);
bPrim-=remainedControlEnergyNeeded;
}
else
{
m_rtable->setControlB (bPrim);
m_rtable->setControlBMax (remainedControlEnergyNeeded);
bPrim=0;
double neededControlGamma=(remainedControlEnergyNeeded-bPrim)/remainedSimulationTimeSeconds;
if(gammaPrim>=neededControlGamma)
{
m_rtable->setControlGamma (neededControlGamma);
gammaPrim-=neededControlGamma;
assignedGamma+=neededControlGamma;
}
else
{
m_rtable->setControlGamma (gammaPrim);
assignedGamma+=gammaPrim;
gammaPrim=0;
}
}
m_rtable->setSystemGamma (gamma);
m_rtable->setBPrim (bPrim);
m_rtable->setGammaPrim (gammaPrim);
m_rtable->setAssignedGamma (assignedGamma);
NS_LOG_VB("GammaChange " << gamma << " " << totalSimmTime << " | " << m_rtable->systemGamma () << " " << m_rtable->bPrim () << " " << m_rtable->gammaPrim () << " " << m_rtable->assignedGamma () << " * " << m_rtable->controlGamma () << " " << m_rtable->controlB ());
}
//Statistics:
HwmpProtocol::Statistics::Statistics () :
txUnicast (0),
txBroadcast (0),
txBytes (0),
droppedTtl (0),
totalQueued (0),
totalDropped (0),
initiatedPreq (0),
initiatedPrep (0),
initiatedPerr (0)
{
}
void HwmpProtocol::Statistics::Print (std::ostream & os) const
{
os << "<Statistics "
"txUnicast=\"" << txUnicast << "\" "
"txBroadcast=\"" << txBroadcast << "\" "
"txBytes=\"" << txBytes << "\" "
"droppedTtl=\"" << droppedTtl << "\" "
"totalQueued=\"" << totalQueued << "\" "
"totalDropped=\"" << totalDropped << "\" "
"initiatedPreq=\"" << initiatedPreq << "\" "
"initiatedPrep=\"" << initiatedPrep << "\" "
"initiatedPerr=\"" << initiatedPerr << "\"/>" << std::endl;
}
void
HwmpProtocol::Report (std::ostream & os) const
{
os << "<Hwmp "
"address=\"" << m_address << "\"" << std::endl <<
"maxQueueSize=\"" << m_maxQueueSize << "\"" << std::endl <<
"Dot11MeshHWMPmaxPREQretries=\"" << (uint16_t)m_dot11MeshHWMPmaxPREQretries << "\"" << std::endl <<
"Dot11MeshHWMPnetDiameterTraversalTime=\"" << m_dot11MeshHWMPnetDiameterTraversalTime.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPpreqMinInterval=\"" << m_dot11MeshHWMPpreqMinInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPperrMinInterval=\"" << m_dot11MeshHWMPperrMinInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPactiveRootTimeout=\"" << m_dot11MeshHWMPactiveRootTimeout.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPactivePathTimeout=\"" << m_dot11MeshHWMPactivePathTimeout.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPpathToRootInterval=\"" << m_dot11MeshHWMPpathToRootInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPrannInterval=\"" << m_dot11MeshHWMPrannInterval.GetSeconds () << "\"" << std::endl <<
"isRoot=\"" << m_isRoot << "\"" << std::endl <<
"maxTtl=\"" << (uint16_t)m_maxTtl << "\"" << std::endl <<
"unicastPerrThreshold=\"" << (uint16_t)m_unicastPerrThreshold << "\"" << std::endl <<
"unicastPreqThreshold=\"" << (uint16_t)m_unicastPreqThreshold << "\"" << std::endl <<
"unicastDataThreshold=\"" << (uint16_t)m_unicastDataThreshold << "\"" << std::endl <<
"doFlag=\"" << m_doFlag << "\"" << std::endl <<
"rfFlag=\"" << m_rfFlag << "\">" << std::endl;
m_stats.Print (os);
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
plugin->second->Report (os);
}
os << "</Hwmp>" << std::endl;
}
void
HwmpProtocol::ResetStats ()
{
m_stats = Statistics ();
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
plugin->second->ResetStats ();
}
}
int64_t
HwmpProtocol::AssignStreams (int64_t stream)
{
NS_LOG_FUNCTION (this << stream);
m_coefficient->SetStream (stream);
return 1;
}
double HwmpProtocol::GetSumRhoPps()
{
return m_rtable->GetSumRhoPps ();
}
double HwmpProtocol::GetSumGPps()
{
return m_rtable->GetSumGPps ();
}
HwmpProtocol::QueuedPacket::QueuedPacket () :
pkt (0),
protocol (0),
inInterface (0)
{
}
} // namespace dot11s
} // namespace ns3
| hbarghi/VirtualBattery1 | src/mesh/model/dot11s/hwmp-protocol.cc | C++ | gpl-2.0 | 94,361 |
## Copyright (C) 2007-2012 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.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, write to the Free Software
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class SysVIPC(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin):
"""SysV IPC related information
"""
plugin_name = "sysvipc"
def setup(self):
self.add_copy_specs([
"/proc/sysvipc/msg",
"/proc/sysvipc/sem",
"/proc/sysvipc/shm"
])
self.add_cmd_output("ipcs")
# vim: et ts=4 sw=4
| portante/sosreport | sos/plugins/sysvipc.py | Python | gpl-2.0 | 1,199 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
import se.sics.kola.analysis.*;
@SuppressWarnings("nls")
public final class AClassFieldAccess extends PFieldAccess
{
private PClassName _className_;
private TIdentifier _identifier_;
public AClassFieldAccess()
{
// Constructor
}
public AClassFieldAccess(
@SuppressWarnings("hiding") PClassName _className_,
@SuppressWarnings("hiding") TIdentifier _identifier_)
{
// Constructor
setClassName(_className_);
setIdentifier(_identifier_);
}
@Override
public Object clone()
{
return new AClassFieldAccess(
cloneNode(this._className_),
cloneNode(this._identifier_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseAClassFieldAccess(this);
}
public PClassName getClassName()
{
return this._className_;
}
public void setClassName(PClassName node)
{
if(this._className_ != null)
{
this._className_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._className_ = node;
}
public TIdentifier getIdentifier()
{
return this._identifier_;
}
public void setIdentifier(TIdentifier node)
{
if(this._identifier_ != null)
{
this._identifier_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._identifier_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._className_)
+ toString(this._identifier_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._className_ == child)
{
this._className_ = null;
return;
}
if(this._identifier_ == child)
{
this._identifier_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._className_ == oldChild)
{
setClassName((PClassName) newChild);
return;
}
if(this._identifier_ == oldChild)
{
setIdentifier((TIdentifier) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| kompics/kola | src/main/java/se/sics/kola/node/AClassFieldAccess.java | Java | gpl-2.0 | 2,887 |
package org.zanata.dao;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.model.HAccount;
import org.zanata.model.HAccountRole;
import org.zanata.model.HProject;
@Name("accountRoleDAO")
@AutoCreate
@Scope(ScopeType.STATELESS)
public class AccountRoleDAO extends AbstractDAOImpl<HAccountRole, Integer> {
public AccountRoleDAO() {
super(HAccountRole.class);
}
public AccountRoleDAO(Session session) {
super(HAccountRole.class, session);
}
public boolean roleExists(String role) {
return findByName(role) != null;
}
public HAccountRole findByName(String roleName) {
Criteria cr = getSession().createCriteria(HAccountRole.class);
cr.add(Restrictions.eq("name", roleName));
cr.setCacheable(true).setComment("AccountRoleDAO.findByName");
return (HAccountRole) cr.uniqueResult();
}
public HAccountRole create(String roleName, HAccountRole.RoleType type,
String... includesRoles) {
HAccountRole role = new HAccountRole();
role.setName(roleName);
role.setRoleType(type);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public HAccountRole updateIncludeRoles(String roleName,
String... includesRoles) {
HAccountRole role = findByName(roleName);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public List<HAccount> listMembers(String roleName) {
HAccountRole role = findByName(roleName);
return listMembers(role);
}
@SuppressWarnings("unchecked")
public List<HAccount> listMembers(HAccountRole role) {
Query query =
getSession()
.createQuery(
"from HAccount account where :role member of account.roles");
query.setParameter("role", role);
query.setComment("AccountRoleDAO.listMembers");
return query.list();
}
public Collection<HAccountRole> getByProject(HProject project) {
return getSession()
.createQuery(
"select p.allowedRoles from HProject p where p = :project")
.setParameter("project", project)
.setComment("AccountRoleDAO.getByProject").list();
}
}
| itsazzad/zanata-server | zanata-war/src/main/java/org/zanata/dao/AccountRoleDAO.java | Java | gpl-2.0 | 3,235 |
/*
Copyright (C) 2009 - 2015 by Yurii Chernyi <terraninfo@terraninfo.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
/**
* @file
* Formula debugger - implementation
* */
#include "formula_debugger.hpp"
#include "formula.hpp"
#include "formula_function.hpp"
#include "game_display.hpp"
#include "log.hpp"
#include "resources.hpp"
#include "gui/dialogs/formula_debugger.hpp"
#include "gui/widgets/settings.hpp"
#include <boost/lexical_cast.hpp>
static lg::log_domain log_formula_debugger("ai/debug/formula");
#define DBG_FDB LOG_STREAM(debug, log_formula_debugger)
#define LOG_FDB LOG_STREAM(info, log_formula_debugger)
#define WRN_FDB LOG_STREAM(warn, log_formula_debugger)
#define ERR_FDB LOG_STREAM(err, log_formula_debugger)
namespace game_logic {
debug_info::debug_info(int arg_number, int counter, int level, const std::string &name, const std::string &str, const variant &value, bool evaluated)
: arg_number_(arg_number), counter_(counter), level_(level), name_(name), str_(str), value_(value), evaluated_(evaluated)
{
}
debug_info::~debug_info()
{
}
int debug_info::level() const
{
return level_;
}
const std::string& debug_info::name() const
{
return name_;
}
int debug_info::counter() const
{
return counter_;
}
const variant& debug_info::value() const
{
return value_;
}
void debug_info::set_value(const variant &value)
{
value_ = value;
}
bool debug_info::evaluated() const
{
return evaluated_;
}
void debug_info::set_evaluated(bool evaluated)
{
evaluated_ = evaluated;
}
const std::string& debug_info::str() const
{
return str_;
}
formula_debugger::formula_debugger()
: call_stack_(), counter_(0), current_breakpoint_(), breakpoints_(), execution_trace_(),arg_number_extra_debug_info(-1), f_name_extra_debug_info("")
{
add_breakpoint_step_into();
add_breakpoint_continue_to_end();
}
formula_debugger::~formula_debugger()
{
}
static void msg(const char *act, debug_info &i, const char *to="", const char *result = "")
{
DBG_FDB << "#" << i.counter() << act << std::endl <<" \""<< i.name().c_str() << "\"='" << i.str().c_str() << "' " << to << result << std::endl;
}
void formula_debugger::add_debug_info(int arg_number, const char *f_name)
{
arg_number_extra_debug_info = arg_number;
f_name_extra_debug_info = f_name;
}
const std::deque<debug_info>& formula_debugger::get_call_stack() const
{
return call_stack_;
}
const breakpoint_ptr formula_debugger::get_current_breakpoint() const
{
return current_breakpoint_;
}
const std::deque<debug_info>& formula_debugger::get_execution_trace() const
{
return execution_trace_;
}
void formula_debugger::check_breakpoints()
{
for( std::deque< breakpoint_ptr >::iterator b = breakpoints_.begin(); b!= breakpoints_.end(); ++b) {
if ((*b)->is_break_now()){
current_breakpoint_ = (*b);
show_gui();
current_breakpoint_ = breakpoint_ptr();
if ((*b)->is_one_time_only()) {
breakpoints_.erase(b);
}
break;
}
}
}
void formula_debugger::show_gui()
{
if (resources::screen == NULL) {
WRN_FDB << "do not showing debug window due to NULL gui" << std::endl;
return;
}
if (gui2::new_widgets) {
gui2::tformula_debugger debug_dialog(*this);
debug_dialog.show(resources::screen->video());
} else {
WRN_FDB << "do not showing debug window due to disabled --new-widgets"<< std::endl;
}
}
void formula_debugger::call_stack_push(const std::string &str)
{
call_stack_.push_back(debug_info(arg_number_extra_debug_info,counter_++,call_stack_.size(),f_name_extra_debug_info,str,variant(),false));
arg_number_extra_debug_info = -1;
f_name_extra_debug_info = "";
execution_trace_.push_back(call_stack_.back());
}
void formula_debugger::call_stack_pop()
{
execution_trace_.push_back(call_stack_.back());
call_stack_.pop_back();
}
void formula_debugger::call_stack_set_evaluated(bool evaluated)
{
call_stack_.back().set_evaluated(evaluated);
}
void formula_debugger::call_stack_set_value(const variant &v)
{
call_stack_.back().set_value(v);
}
variant formula_debugger::evaluate_arg_callback(const formula_expression &expression, const formula_callable &variables)
{
call_stack_push(expression.str());
check_breakpoints();
msg(" evaluating expression: ",call_stack_.back());
variant v = expression.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated expression: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f, const formula_callable &variables)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula: ",call_stack_.back());
variant v = f.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula without variables: ",call_stack_.back());
variant v = f.execute(this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula without variables: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
base_breakpoint::base_breakpoint(formula_debugger &fdb, const std::string &name, bool one_time_only)
: fdb_(fdb), name_(name), one_time_only_(one_time_only)
{
}
base_breakpoint::~base_breakpoint()
{
}
bool base_breakpoint::is_one_time_only() const
{
return one_time_only_;
}
const std::string& base_breakpoint::name() const
{
return name_;
}
class end_breakpoint : public base_breakpoint {
public:
end_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"End", true)
{
}
virtual ~end_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if ((call_stack.size() == 1) && (call_stack[0].evaluated()) ) {
return true;
}
return false;
}
};
class step_in_breakpoint : public base_breakpoint {
public:
step_in_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step",true)
{
}
virtual ~step_in_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
return true;
}
};
class step_out_breakpoint : public base_breakpoint {
public:
step_out_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step out",true), level_(fdb.get_call_stack().size()-1)
{
}
virtual ~step_out_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
class next_breakpoint : public base_breakpoint {
public:
next_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Next",true), level_(fdb.get_call_stack().size())
{
}
virtual ~next_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
void formula_debugger::add_breakpoint_continue_to_end()
{
breakpoints_.push_back(breakpoint_ptr(new end_breakpoint(*this)));
LOG_FDB << "added 'end' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_into()
{
breakpoints_.push_back(breakpoint_ptr(new step_in_breakpoint(*this)));
LOG_FDB << "added 'step into' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_out()
{
breakpoints_.push_back(breakpoint_ptr(new step_out_breakpoint(*this)));
LOG_FDB << "added 'step out' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_next()
{
breakpoints_.push_back(breakpoint_ptr(new next_breakpoint(*this)));
LOG_FDB << "added 'next' breakpoint"<< std::endl;
}
} // end of namespace game_logic
| techtonik/wesnoth | src/formula_debugger.cpp | C++ | gpl-2.0 | 8,738 |
#include "botpch.h"
#include "../../playerbot.h"
#include "BuyAction.h"
#include "../ItemVisitors.h"
#include "../values/ItemCountValue.h"
using namespace ai;
bool BuyAction::Execute(Event event)
{
string link = event.getParam();
ItemIds itemIds = chat->parseItems(link);
if (itemIds.empty())
return false;
Player* master = GetMaster();
if (!master)
return false;
ObjectGuid vendorguid = master->GetSelectionGuid();
if (!vendorguid)
return false;
Creature *pCreature = bot->GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
if (!pCreature)
{
ai->TellMaster("Cannot talk to vendor");
return false;
}
VendorItemData const* tItems = pCreature->GetVendorItems();
if (!tItems)
{
ai->TellMaster("This vendor has no items");
return false;
}
for (ItemIds::iterator i = itemIds.begin(); i != itemIds.end(); i++)
{
for (uint32 slot = 0; slot < tItems->GetItemCount(); slot++)
{
if (tItems->GetItem(slot)->item == *i)
{
bot->BuyItemFromVendor(vendorguid, *i, 1, NULL_BAG, NULL_SLOT);
ai->TellMaster("Bought item");
}
}
}
return true;
}
| H0zen/M0-server | src/modules/Bots/playerbot/strategy/actions/BuyAction.cpp | C++ | gpl-2.0 | 1,267 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language;?>" >
<?php
/* @package mx_joomla121 Template
* @author mixwebtemplates http://www.mixwebtemplates.com
* @copyright Copyright (c) 2006 - 2012 mixwebtemplates. All rights reserved
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
if(!defined('DS')){define('DS',DIRECTORY_SEPARATOR);}
$tcParams = '';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'head.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'settings.php');
$tcParams .= '<body id="tc">';
$tcParams .= TCShowModule('adverts', 'mx_xhtml', 'container');
$tcParams .= '<div id="mx_wrapper" class="mx_wrapper">';
$tcParams .= TCShowModule('header', 'mx_xhtml', 'container');
$tcParams .= '<jdoc:include type="modules" name="sign_in" />';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'slider.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'social.php');
$tcParams .= TCShowModule('slider', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('top', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('info', 'mx_xhtml', 'container');
$tcParams .= '<section class="mx_wrapper_info mx_section">'
.'<div class="container mx_group"><jdoc:include type="modules" name="search_jobs_box" />'
// .'<div><jdoc:include type="modules" name="test1" /></div>'
.'</div></section>';
//Latest Jobs blocks
$tcParams .= '<div class="row"><jdoc:include type="modules" name="latest_jobs" /></div>'
;
//Slide top
$tcParams .= '<section class="mx_wrapper_top mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_slide" />'
.'</div></section>';
//very maintop content block
$tcParams .= '<section class="mx_wrapper_maintop mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_block" />'
.'</div></section>';
$tcParams .= TCShowModule('maintop', 'mx_xhtml', 'container');
$tcParams .= '<main class="mx_main container clearfix">'.$component.'</main>';
$tcParams .= TCShowModule('mainbottom', 'mx_xhtml', 'container').
TCShowModule('feature', 'mx_xhtml', 'container').
TCShowModule('bottom', 'mx_xhtml', 'container').
TCShowModule('footer', 'mx_xhtml', 'container');
//Advise widget
$tcParams .= '<div class="row">'
.'<jdoc:include type="modules" name="advise-widget" />'
.'</div>';
//Resume nav bar
$tcParams .= '<div class="mod-content clearfix">'
.'<jdoc:include type="modules" name="Create_ResumeNavBar" />'
.'</div>';
//Feature blocks
$tcParams .= '<section class="mx_wrapper_feature mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="feature-1" />'
.'</div></section>';
//Footer blocks
$tcParams .= '<section class="mx_wrapper_bottom mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="footer_block" />'
.'</div></section>';
$tcParams .= '<footer class="mx_wrapper_copyright mx_section">'.
'<div class="container clearfix">'.
'<div class="col-md-12">'.($copyright ? '<div style="padding:10px;">'.$cpright.' </div>' : ''). /* You CAN NOT remove (or unreadable) this without mixwebtemplates.com permission */ //'<div style="padding-bottom:10px; text-align:right; ">Designed by <a href="http://www.mixwebtemplates.com/" title="Visit mixwebtemplates.com!" target="blank">mixwebtemplates.com</a></div>'.
'</div>'.
'</div>'.
'</footer>';
$tcParams .='</div>';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'debug.php');
$tcParams .='</body>';
$tcParams .='</html>';
echo $tcParams;
?> | sondang86/hasico | templates/temp_template/index.php | PHP | gpl-2.0 | 3,934 |
/*
* main.cpp
*
* Created on: 30 Xan, 2015
* Author: marcos
*/
#include "common.h"
extern "C" {
#include "perm.h"
}
/**
* \brief Print application help
*/
void printHelp() {
cout << "diffExprpermutation: Find differentially expressed genes from a set of control and cases samples using a permutation strategy." << endl;
cout << "diffExprPermutation -f input [--c1 condition1 --c2 condition2 -n permutations -H stopHits -s statistic] -o outFile" << endl;
cout << "Inputs:" << endl;
cout << " -f input Space separated table. Format: sampleName group lib.size norm.factors gene1 gene2 ... geneN" << endl;
cout << "Outputs:" << endl;
cout << " -o outFile Output file name" << endl;
cout << "Options:" << endl;
cout << " --c1 condition1 Condition that determine one of two groups [default: case]" << endl;
cout << " --c2 condition2 Condition that determine other group [default: control]" << endl;
cout << " -s statistic Statistic to compute pvalue median|perc25|perc75|x [default: median]" << endl;
cout << " -p percentile mode Mode for selection of percentile auto|linear|nearest [default: auto]" << endl;
cout << " -t n_threads Number of threads [default: 1]" << endl;
}
/**
* \brief Check Arguments
* \param string fileInput - Name input file
* \param string outFile - Name output file
* \param unsigned int chunks - Number of chunks to create
* \param string condition1 - First condition group. Usually case.
* \param string condition1 - Second condition group. Usually control.
*/
inline bool argumentChecking(const string &fileInput,
const string &outFile,
const string &condition1,
const string &condition2)
{
bool bWrong = false;
if (fileInput.empty())
{
cout << "Sorry!! No input file was specified!!" << endl;
return true;
}
if (outFile.empty())
{
cout << "Sorry!! No output file was specified!!" << endl;
return true;
}
if (condition1.empty())
{
cout << "Sorry!! Condition group 1 is empty!!" << endl;
return true;
}
if (condition2.empty())
{
cout << "Sorry!! Condition group 2 is empty!!" << endl;
return true;
}
return bWrong;
}
int main(int argc, char **argv)
{
string fileInput = "";
string outFile = "";
string condition1 = "case";
string condition2 = "control";
string percentile_mode = "auto";
cp_mode pc_mode = AUTO;
int n_threads = 1;
string statistic = "median";
double fStatisticValue = 0;
bool doMedian = true;
vector<Gene> vGenes; // vector of genes where each gene has a vector of sampleGenes, each sampleGene contains sample name expression value and group
/**
* BRACA1 -> A,true,0.75
* -> B,false,0.85
* ...
* BRACA2 -> A,true,0.15
* -> B,false,0.20
* ...
*/
// 1.Process parameters
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-f") == 0)
{
fileInput = argv[++i];
}
else if (strcmp(argv[i], "-o") == 0)
{
outFile = argv[++i];
}
else if (strcmp(argv[i], "--c1") == 0)
{
condition1 = argv[++i];
}
else if (strcmp(argv[i], "--c2") == 0)
{
condition2 = argv[++i];
}
else if (strcmp(argv[i], "-s") == 0)
{
statistic = argv[++i];
}
else if (strcmp(argv[i], "-p") == 0)
{
percentile_mode = argv[++i];
}
else if (strcmp(argv[i], "-t") == 0)
{
n_threads = atoi(argv[++i]);
if (n_threads < 1) n_threads = 1;
}
else if (strcmp(argv[i],"-h") == 0)
{
printHelp();
return 0;
}
}
// Check Arguments
if(argumentChecking(fileInput, outFile, condition1, condition2))
{
return -1;
}
// Updates statistic
string headerOutput = "gene\tdiff_median\tmedianCase\tmedianControl\tfold_change\tmedian_pv\tmedian_pv_fdr";
if (statistic.compare("perc25") == 0)
{
fStatisticValue = 25.0;
doMedian = false;
headerOutput = "gene\tdiff_lowerq\tlowerqCase\tlowerqControl\tfold_change\tlowerq_pv\tlowerq_pv_fdr";
}
else if (statistic.compare("perc75") == 0)
{
fStatisticValue = 75.0;
doMedian = false;
headerOutput = "gene\tdiff_UpQ\tupperqCase\tupperqControl\tfold_change\tupperq_pv\tupper_pv_fdr";
}
else
{
char *p;
double x = strtod(statistic.c_str(), &p);
if (x > 0.0 && x < 100.0)
{
fStatisticValue = x;
doMedian = false;
ostringstream s;
s << "gene\tdiff_" << x << "%\t" << x << "\%_Case\t" << x << "\%_Control\tfold_change\t" << x << "\%_pv\t" << x << "\%_pv_fdr";
headerOutput = s.str();
}
}
if (percentile_mode.compare("auto") == 0) pc_mode = AUTO;
else if (percentile_mode.compare("linear") == 0) pc_mode = LINEAR_INTERPOLATION;
else if (percentile_mode.compare("nearest") == 0) pc_mode = NEAREST_RANK;
else
{
cerr << "Percentile mode '" << percentile_mode << "' not recognized" << endl;
return -1;
}
// Parsing Input file
if (!loadFileInfo(fileInput, vGenes, condition1, condition2))
{
cerr << "Sorry!! Can not open file " << fileInput << endl;
return -1;
}
// Allocate and make C structure for permutation routine
struct perm_data pdata;
pdata.n_cases = vGenes.begin()->nCases;
pdata.n_controls = vGenes.begin()->nControls;
int n_samples = pdata.n_cases + pdata.n_controls;
pdata.n_var = vGenes.size();
pdata.data = (float *)malloc(sizeof(float) * pdata.n_var * (4 + n_samples));
pdata.fold_change = pdata.data + pdata.n_var * n_samples;
pdata.pc_cases = pdata.fold_change + pdata.n_var;
pdata.pc_controls = pdata.pc_cases + pdata.n_var;
pdata.pc_diff = pdata.pc_controls + pdata.n_var;
pdata.grp = (group *)malloc(sizeof(group) * n_samples);
pdata.p_values = (double *)malloc(sizeof(double) * pdata.n_var);
// Copy expression data
float *tp = pdata.data;
for (vector<Gene>::iterator gene_it = vGenes.begin(); gene_it != vGenes.end(); ++gene_it)
{
for (vector<SampleGene>::const_iterator iter = gene_it->vGeneValues.begin();iter != gene_it->vGeneValues.end(); ++iter)
{
(*tp++) = (float)iter->expressionValue;
}
}
// Copy group information
int ix = 0;
for (vector<bool>::const_iterator iter = vGenes.begin()->vGroup.begin(); iter != vGenes.begin()->vGroup.end(); ++iter)
{
pdata.grp[ix++] = *iter ? CASE : CONTROL;
}
// Calculate exact permutation p-values
check_percentile(doMedian ? 50.0 : fStatisticValue, pc_mode, n_threads,&pdata);
vector<double> vPvalues;
int i = 0;
for (vector<Gene>::iterator iter = vGenes.begin(); iter != vGenes.end(); ++iter)
{
// Copy results from pdata struture
(*iter).originalDiff = (double)pdata.pc_diff[i];
(*iter).originalMedianCases = (double)pdata.pc_cases[i];
(*iter).originalMedianControl = (double)pdata.pc_controls[i];
(*iter).foldChange = pdata.fold_change[i];
(*iter).pValue = pdata.p_values[i];
// Add pvalue to a vector of pvalues for being correcte by FDR
vPvalues.push_back((*iter).pValue);
i++;
}
vector<double> correctedPvalues;
correct_pvalues_fdr(vPvalues, correctedPvalues);
// Print to file
std::ofstream outfile(outFile.c_str(), std::ofstream::out);
// Header File
outfile << headerOutput << endl;
vector<double>::const_iterator iterCorrected = correctedPvalues.begin();
outfile.precision(15);
for (vector<Gene>::const_iterator iter = vGenes.begin(); iter != vGenes.end();++iter)
{
outfile << (*iter).geneName << "\t" << (*iter).originalDiff << "\t" << (*iter).originalMedianCases;
outfile << "\t" << (*iter).originalMedianControl << "\t" << (*iter).foldChange << "\t" << (*iter).pValue << "\t" << (*iterCorrected) << endl;
++iterCorrected;
}
free(pdata.grp);
free(pdata.data);
free(pdata.p_values);
outfile.close();
return 0;
}
| MarcosFernandez/diffExprPermutation | main.cpp | C++ | gpl-2.0 | 8,112 |
<?php
include_once '../libs/Connection.php';
include_once '../libs/tree_editor.php';
class tree_performance extends tree_editor{
public function __construct(){
parent::__construct();
if(!isset($_POST['action'])){
header("content-type:text/xml;charset=UTF-8");
if(isset($_GET['refresh'])){
$refresh = $_GET['refresh'];
}else{
$refresh = false;
}
echo ($this->getXml($_GET['id'],$_GET['autoload'],$refresh));
}else{
$this->db->query("START TRANSACTION");
$response = "";
$response = $this->parseRequest();
$this->db->query("COMMIT");
echo json_encode($response);
}
}
public function getXmlTree($id=0,$rf,$autoload = true){
$xml = '<tree id="'.$id.'">';
$xml .= $this->getXmlMyPerformanceAuto($id,$rf,$autoload);
$xml .= '</tree>';
return $xml;
}
/********* Top level *****************/
protected function getXmlMyPerformanceAuto($id,$rf,$autoload){
if($autoload=='false'){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
$xml .= $this->getItemLoad(0,"mystg",$rf,false);
$xml .= '</item>';
}else{
if($id == "0"){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
}else{
$xml .= $this->getItemLoad(0,$id,$rf,true);
$xml .= '</item>';
}
}
return $xml;
}
protected function getChildItems($type){
$items = array();
switch ($type) {
case 'studygroup':
$items[] = array('table' => 'performance',
'id' => 'performance',
'pid' => 'studygroup_id',
);
break;
case 'mystg':
$items[] = array('table' => 'studygroups',
'id' => 'studygroup',
'pid' => 'mystg',
);
break;
default:
break;
}
return $items;
}
public function getTableInfoFromType($type){
switch ($type) {
case 'studygroup':
$table = "studygroups";
$id_name = "studygroup";
break;
case 'mystg':
$table = "mystg";
$id_name = "mystg";
break;
case 'performance':
$table = "performance";
$id_name = "performance";
break;
default:
break;
}
return array('table' => $table, 'id_name' => $id_name);
}
public function addPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 1
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function addNotPublicPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 0
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function deletePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->removeItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function sharePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->shareItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function privatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->privateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function duplicatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->duplicateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function movePerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "performance":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->setParent($sid,$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function moveDublPerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "assignment":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->duplicatePerformanceItem($sid,$item);
$response = $this->setParent($response['id'],$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function getPerformanceInfo($id){
$result = $this->db->query("
SELECT perf.title_en as title_p, stg.title_en as title_g
FROM performance perf
inner join studygroups stg on perf.studygroup_id=stg.studygroup_id
where perf.performance_id=$id
");
while($row = mysql_fetch_assoc($result)){
$name = $row['title_p'];
$studygroup = $row['title_g'];
}
return array(
"name" => $name,
"studygroup" => $studygroup
);
}
public function getPerformanceDescroption($id){
$description = "";
$notes = "";
$result = $this->db->query("SELECT content_en,owner_notes FROM performance WHERE performance_id=$id LIMIT 1");
while($row = mysql_fetch_assoc($result)){
$description = $row['content_en'];
$notes = $row['owner_notes'];
}
return array('content' => $description,'notes' => $notes);
}
public function putPerformanceDescription($id,$content,$notes){
$result = $this->db->query("UPDATE performance SET content_en='$content',owner_notes='$notes' WHERE performance_id=$id");
return array('update' => true);
}
function parseRequest(){
if(isset($_POST['action'])){
$action = $_POST['action'];
$act = explode("_", $action);
$id = $_POST['id'];
$response = "";
$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['node'];
$ids = explode(",", $_POST['ids']);
$par = explode('_', $_POST['tid']);
$sid = $_POST['sid'];
$lid = $_POST['lid'];
$content = $_POST['content'];
$notes = $_POST['notes'];
$description = $_POST['description'];
switch($act[0]){
case "new":
$response = $this->addPerformanceItem($act[1]);
break;
case "delete":
$response = $this->deletePerformanceItem($id,$act[1]);
break;
case "duplicate":
$response = $this->duplicatePerformanceItem($id,$act[1]);
break;
case "rename":
$table = $this->getTableInfoFromType($type);
$response = $this->rename($id,$name,$table['table'],$table['id_name']);
break;
case "move":
$response = $this->movePerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "movedupl":
$response = $this->moveDublPerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "getassignment":
$response = $this->getAssignmentContent($id);
$response["info"] = $this->getAssignmentInfo($id);
break;
case "putassignment":
$response = $this->putAssignmentContent($id,$content,$notes);
break;
case "share":
$response = $this->sharePerformanceItem($id,$act[1]);
break;
case "private":
$response = $this->privatePerformanceItem($id,$act[1]);
break;
case "getassessperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = dlang("header_asignment_view_performance","View Performance");
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/performance.png";
break;
case "getperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = "View Assessments";
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/assessment.png";
break;
case "putperformance":
$response = $this->putPerformanceDescription($id,$_POST['content'],$_POST['notes']);
break;
case "newnotpublic":
$response = $this->addNotPublicPerformanceItem($act[1]);
}
return $response;
}else{
return false;
}
}
}
?> | ya6adu6adu/schoolmule | connectors/tree_performance.php | PHP | gpl-2.0 | 8,691 |
package imageresizerforandroid;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.ImageIcon;
/**
*
* @author fonter
*/
public class ImageContainer {
private final BufferedImage image;
private ImageIcon cache;
private final File file;
public ImageContainer (BufferedImage image, File file) {
this.image = image;
this.file = file;
}
public String getNormalizeName () {
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
return name.substring(0, pos);
}
return name;
}
public ImageIcon getCache () {
return cache;
}
public File getFile () {
return file;
}
public BufferedImage getImage () {
return image;
}
public void setCache (ImageIcon cache) {
this.cache = cache;
}
public boolean isCacheCreate () {
return cache != null;
}
}
| pinkiesky/ImageResizerForAndroid | ImageResizerForAndroid/src/imageresizerforandroid/ImageContainer.java | Java | gpl-2.0 | 995 |
#! /usr/bin/env python
# encoding: UTF-8
'''give access permission for files in this folder'''
| anandkp92/waf | gui/__init__.py | Python | gpl-2.0 | 96 |
<?php
/**
* Helpers for handling timezone based event datetimes.
*
* In our timezone logic, the term "local" refers to the locality of an event
* rather than the local WordPress timezone.
*/
class E_Register_NowTimezones {
const SITE_TIMEZONE = 'site';
const EVENT_TIMEZONE = 'event';
/**
* Container for reusable DateTimeZone objects.
*
* @var array
*/
protected static $timezones = array();
public static function init() {
self::invalidate_caches();
}
/**
* Clear any cached timezone-related values when appropriate.
*
* Currently we are concerned only with the site timezone abbreviation.
*/
protected static function invalidate_caches() {
add_filter( 'pre_update_option_gmt_offset', array( __CLASS__, 'clear_site_timezone_abbr' ) );
add_filter( 'pre_update_option_timezone_string', array( __CLASS__, 'clear_site_timezone_abbr' ) );
}
/**
* Wipe the cached site timezone abbreviation, if set.
*
* @param mixed $option_val (passed through without modification)
*
* @return mixed
*/
public static function clear_site_timezone_abbr( $option_val ) {
delete_transient( 'tribe_events_wp_timezone_abbr' );
return $option_val;
}
/**
* Returns the current site-wide timezone string.
*
* Based on the core WP code found in wp-admin/options-general.php.
*
* @return string
*/
public static function wp_timezone_string() {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Return the timezone string if already set
if ( ! empty( $tzstring ) ) {
return $tzstring;
}
// Otherwise return the UTC offset
if ( 0 == $current_offset ) {
return 'UTC+0';
} elseif ( $current_offset < 0 ) {
return 'UTC' . $current_offset;
}
return 'UTC+' . $current_offset;
}
/**
* Returns the current site-wide timezone string abbreviation, if it can be
* determined or falls back on the full timezone string/offset text.
*
* @param string $date
*
* @return string
*/
public static function wp_timezone_abbr( $date ) {
$abbr = get_transient( 'tribe_events_wp_timezone_abbr' );
if ( empty( $abbr ) ) {
$timezone_string = self::wp_timezone_string();
$abbr = self::abbr( $date, $timezone_string );
set_transient( 'tribe_events_wp_timezone_abbr', $abbr );
}
return empty( $abbr )
? $timezone_string
: $abbr;
}
/**
* Helper function to retrieve the timezone string for a given UTC offset
*
* This is a close copy of WooCommerce's wc_timezone_string() method
*
* @param string $offset UTC offset
*
* @return string
*/
public static function generate_timezone_string_from_utc_offset( $offset ) {
if ( ! self::is_utc_offset( $offset ) ) {
return $offset;
}
// ensure we have the minutes on the offset
if ( ! strpos( $offset, ':' ) ) {
$offset .= ':00';
}
$offset = str_replace( 'UTC', '', $offset );
list( $hours, $minutes ) = explode( ':', $offset );
$seconds = $hours * 60 * 60 + $minutes * 60;
// attempt to guess the timezone string from the UTC offset
$timezone = timezone_name_from_abbr( '', $seconds, 0 );
if ( false === $timezone ) {
$is_dst = date( 'I' );
foreach ( timezone_abbreviations_list() as $abbr ) {
foreach ( $abbr as $city ) {
if (
$city['dst'] == $is_dst
&& $city['offset'] == $seconds
) {
return $city['timezone_id'];
}
}
}
// fallback to UTC
return 'UTC';
}
return $timezone;
}
/**
* Tried to convert the provided $datetime to UTC from the timezone represented by $tzstring.
*
* Though the usual range of formats are allowed, $datetime ordinarily ought to be something
* like the "Y-m-d H:i:s" format (ie, no timezone information). If it itself contains timezone
* data, the results may be unexpected.
*
* In those cases where the conversion fails to take place, the $datetime string will be
* returned untouched.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_utc( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring, true );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $local )->setTimezone( $utc );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tries to convert the provided $datetime to the timezone represented by $tzstring.
*
* This is the sister function of self::to_utc() - please review the docs for that method
* for more information.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_tz( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $utc )->setTimezone( $local );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tests to see if the timezone string is a UTC offset, ie "UTC+2".
*
* @param string $timezone
*
* @return bool
*/
public static function is_utc_offset( $timezone ) {
$timezone = trim( $timezone );
return ( 0 === strpos( $timezone, 'UTC' ) && strlen( $timezone ) > 3 );
}
/**
* @param string $datetime
* @param mixed $offset (string or numeric offset)
* @param bool $invert = false
*
* @return string
*/
public static function apply_offset( $datetime, $offset, $invert = false ) {
// Normalize
$offset = strtolower( trim( $offset ) );
// Strip any leading "utc" text if set
if ( 0 === strpos( $offset, 'utc' ) ) {
$offset = substr( $offset, 3 );
}
// It's possible no adjustment will be needed
if ( 0 === $offset ) {
return $datetime;
}
// Convert the offset to minutes for easier handling of fractional offsets
$offset = (int) ( $offset * 60 );
// Invert the offset? Useful for stripping an offset that has already been applied
if ( $invert ) {
$offset *= -1;
}
try {
if ( $offset > 0 ) $offset = '+' . $offset;
$offset = $offset . ' minutes';
$datetime = date_create( $datetime )->modify( $offset );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Accepts a unix timestamp and adjusts it so that when it is used to consitute
* a new datetime string, that string reflects the designated timezone.
*
* @param string $unix_timestamp
* @param string $tzstring
*
* @return string
*/
public static function adjust_timestamp( $unix_timestamp, $tzstring ) {
try {
$local = self::get_timezone( $tzstring );
$datetime = date_create_from_format( 'U', $unix_timestamp )->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
return date_create_from_format( 'Y-m-d H:i:s', $datetime, $local )->getTimestamp();
}
catch( Exception $e ) {
return $unix_timestamp;
}
}
/**
* Returns a DateTimeZone object matching the representation in $tzstring where
* possible, or else representing UTC (or, in the worst case, false).
*
* If optional parameter $with_fallback is true, which is the default, then in
* the event it cannot find/create the desired timezone it will try to return the
* UTC DateTimeZone before bailing.
*
* @param string $tzstring
* @param bool $with_fallback = true
*
* @return DateTimeZone|false
*/
public static function get_timezone( $tzstring, $with_fallback = true ) {
if ( isset( self::$timezones[ $tzstring ] ) ) {
return self::$timezones[ $tzstring ];
}
try {
self::$timezones[ $tzstring ] = new DateTimeZone( $tzstring );
return self::$timezones[ $tzstring ];
}
catch ( Exception $e ) {
if ( $with_fallback ) {
return self::get_timezone( 'UTC', true );
}
}
return false;
}
/**
* Returns a string representing the timezone/offset currently desired for
* the display of dates and times.
*
* @return string
*/
public static function mode() {
$mode = self::EVENT_TIMEZONE;
if ( 'site' === tribe_get_option( 'tribe_events_timezone_mode' ) ) {
$mode = self::SITE_TIMEZONE;
}
return apply_filters( 'tribe_events_current_display_timezone', $mode );
}
/**
* Confirms if the current timezone mode matches the $possible_mode.
*
* @param string $possible_mode
*
* @return bool
*/
public static function is_mode( $possible_mode ) {
return $possible_mode === self::mode();
}
/**
* Attempts to provide the correct timezone abbreviation for the provided timezone string
* on the date given (and so should account for daylight saving time, etc).
*
* @param string $date
* @param string $timezone_string
*
* @return string
*/
public static function abbr( $date, $timezone_string ) {
try {
return date_create( $date, new DateTimeZone( $timezone_string ) )->format( 'T' );
}
catch ( Exception $e ) {
return '';
}
}
}
| romangrb/register-now-plugin | backup/event-tickets 1.2.3/common/src/e_register_now/Timezones.php | PHP | gpl-2.0 | 9,222 |
using UnityEngine;
using System.Collections;
public class EndScreenController : ScreenController {
public UnityEngine.UI.Text winnerText;
public UnityEngine.UI.Text player1Text;
public UnityEngine.UI.Text player2Text;
public UnityEngine.UI.Text nextLeftPlayers;
public UnityEngine.UI.Text nextRightPlayers;
protected override void OnActivation() {
gameObject.SetActive(true);
winnerText.text = "...";
player1Text.text = "...";
player2Text.text = "...";
nextLeftPlayers.text = "...";
nextRightPlayers.text = "...";
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
}
protected override void OnDeactivation() {
}
protected override void OnMatchInfoDownloaded (MatchInfo matchInfo) {
if (matchInfo.state != "OK") {
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
return;
}
Bot winner = matchInfo.GetWinner();
if (winner == null) {
winnerText.text = "Draw!";
Bot[] bots = matchInfo.bots;
player1Text.text = createText (bots[0].name, -1);
player2Text.text = createText (bots[1].name, -1);
} else {
winnerText.text = winner.name + " wins!";
Bot looser = matchInfo.GetLooser ();
player1Text.text = createText (winner.name, 3);
player2Text.text = createText (looser.name, 0);
}
int tournamentId = matchInfo.tournamentId;
StartCoroutine(DownloadUpcomingMatches(tournamentId));
}
protected override void OnUpcomingMatchesDownloaded(UpcomingMatches upcomingMatches) {
Match[] matches = upcomingMatches.matches;
nextLeftPlayers.text = "";
nextRightPlayers.text = "";
for (int i = 0; i < 3 && i < matches.Length; i++) {
Match match = matches [i];
string botNameLeft = match.bots [0];
string botNameRight = match.bots [1];
if (i > 0) {
nextLeftPlayers.text += "\n";
nextRightPlayers.text += "\n";
}
nextLeftPlayers.text += botNameLeft;
nextRightPlayers.text += botNameRight;
}
}
private string createText(string botName, int pts) {
string sign = pts >= 0 ? "+" : "";
return botName + "\n" + sign + pts + " pts";
}
}
| hackcraft-sk/swarm | ubwtv/Assets/Scripts/EndScreenController.cs | C# | gpl-2.0 | 2,119 |
package fortesting;
import java.io.IOException;
public class RunTransformTim {
/**
* Loads data into appropriate tables (assumes scheme already created)
*
* This will import the tables from my CSVs, which I have on dropbox. Let me
* (Tim) know if you need the CSVs No guarantee that it works on CSVs
* generated differently
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// String host = "127.0.0.1";
String host = "52.32.209.104";
// String keyspace = "new";
String keyspace = "main";
String year = "2012";
// if an error occurs during upload of first CSV, use
// GetLastRow.getLastEntry() to find its
// npi value and use that as start. This will not work in other CSVs
// unless the last npi
// added is greater than the largest npi in all previously loaded CSVs
String start = "";
TransformTim t = new TransformTim();
t.injest(host, keyspace, "CSV/MedicareA2012.csv", year, start);
t.injest(host, keyspace, "CSV/MedicareB2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareC2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareD2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareEG2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareHJ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareKL2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareMN2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareOQ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareR2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareS2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareTX2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareYZ2012.csv", year, "");
}
}
| ZheyuJin/CS8674.FALL2015.NEUSeattle | cassandra/Tim Cassandra Testing and Table Creation/RunTransformTim.java | Java | gpl-2.0 | 1,948 |
package edu.cmu.cs.cimds.geogame.client.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import edu.cmu.cs.cimds.geogame.client.model.dto.ItemDTO;
public class InventoryGrid extends Grid {
// public static final String MONEY_ICON_FILENAME = "coinbag.jpg";
public static final String BLANK_ICON_FILENAME = "blank.png";
private int numCells;
private VerticalPanel[] blanks;
private List<ItemDTO> inventory = new ArrayList<ItemDTO>();
private ItemImageCreator imageCreator;
private String imageWidth = null;
public InventoryGrid(int numRows, int numColumns) {
super(numRows, numColumns);
this.numCells = numRows * numColumns;
this.blanks = new VerticalPanel[this.numCells];
for(int i=0;i<numCells;i++) {
this.blanks[i] = new VerticalPanel();
this.blanks[i].add(new Image(BLANK_ICON_FILENAME));
this.setWidget(i, this.blanks[i]);
}
this.clearContent();
}
public InventoryGrid(int numRows, int numColumns, ItemImageCreator imageCreator) {
this(numRows, numColumns);
this.imageCreator = imageCreator;
}
public List<ItemDTO> getInventory() { return inventory; }
public void setInventory(List<ItemDTO> inventory) { this.inventory = inventory; }
// public void setInventory(List<ItemTypeDTO> inventory) {
// this.inventory = new ArrayList<ItemTypeDTO>();
// for(ItemTypeDTO itemType : inventory) {
// Item dummyItem = new Item();
// dummyItem.setItemType(itemType);
// this.inventory.add(dummyItem);
// }
// }
public ItemImageCreator getImageCreator() { return imageCreator; }
public void setImageCreator(ItemImageCreator imageCreator) { this.imageCreator = imageCreator; }
public void setImageWidth(String imageWidth) { this.imageWidth = imageWidth; }
public void setWidget(int numCell, Widget w) {
// if(numCell >= this.numCells) {
// throw new IndexOutOfBoundsException();
// }
super.setWidget((int)Math.floor(numCell/this.numColumns), numCell%this.numColumns, w);
}
public void clearContent() {
for(int i=0;i<numCells;i++) {
this.setWidget(i, this.blanks[i]);
}
}
public void refresh() {
this.clearContent();
Collections.sort(this.inventory);
for(int i=0;i<this.inventory.size();i++) {
final ItemDTO item = this.inventory.get(i);
Image image = this.imageCreator.createImage(item);
if(this.imageWidth!=null) {
image.setWidth(this.imageWidth);
}
//Label descriptionLabel = new Label(item.getItemType().getName() + " - " + item.getItemType().getBasePrice() + "G", true);
VerticalPanel itemPanel = new VerticalPanel();
itemPanel.add(image);
//itemPanel.add(descriptionLabel);
this.setWidget(i, itemPanel);
}
}
} | grapesmoker/geogame | src/edu/cmu/cs/cimds/geogame/client/ui/InventoryGrid.java | Java | gpl-2.0 | 2,903 |
<?php
/**
* @package phposm
* @copyright Copyright (C) 2015 Wene - ssm2017 Binder ( S.Massiaux ). All rights reserved.
* @link https://github.com/ssm2017/phposm
* @license GNU/GPL, http://www.gnu.org/licenses/gpl-2.0.html
* Phposm is free software. 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.
*/
function createArchiveUrl($file_path)
{
logWrite('[archive] createArchiveUrl called');
// check if file exists
if (!is_file($file_path))
{
logWrite('[archive] file not found : '. $file_path);
return False;
}
// parse the path
$splitted = explode('/', $file_path);
if ($splitted[1] != 'home' || $splitted[3] != 'opensimulator' or ($splitted[4] != 'iar' && $splitted[4] != 'oar'))
{
logWrite('[archive] wrong file path : '. $file_path);
return False;
}
$username = $splitted[2];
$archive_type = $splitted[4];
$expiration = time() + 300;
$url = '/archive?q='. $archive_type. '/'. $username. '/'. md5($expiration. ':'. $GLOBALS['config']['password']). '/'. $expiration. '/'. $splitted[5];
return $url;
}
function parseArchiveUrl($url)
{
logWrite('[archive] parseArchiveUrl called');
$splitted = explode('/', $url);
if ($splitted[1] != 'archive' || ($splitted[2] != 'oar' && $splitted[2] != 'iar'))
{
logWrite('[archive] wrong url : '. $url);
return Null;
}
$filename = $splitted[6];
$username = $splitted[3];
// check expiration
$expiration = $splitted[5];
$now = time();
if ($now > $expiration)
{
logWrite('[archive] url expired : '. $url);
return Null;
}
// check password
if ($splitted[4] != md5($expiration. ':'. $GLOBALS['config']['password']))
{
logWrite('[archive] wrong password');
return Null;
}
// check if file exists
$file_path = '/home/'. $username. '/opensimulator/'. $splitted[2]. '/'. $filename;
if (!is_file($file_path))
{
logWrite('[archive] file not found');
return Null;
}
return $file_path;
}
| ssm2017/phposm | includes/helpers/archive.php | PHP | gpl-2.0 | 2,275 |
<?php
/**
* NoNumber Framework Helper File: Assignments: Tags
*
* @package NoNumber Framework
* @version 14.9.9
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2014 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
/**
* Assignments: Tags
*/
class NNFrameworkAssignmentsTags
{
function passTags(&$parent, &$params, $selection = array(), $assignment = 'all', $article = 0)
{
$is_content = in_array($parent->params->option, array('com_content', 'com_flexicontent'));
if (!$is_content)
{
return $parent->pass(0, $assignment);
}
$is_item = in_array($parent->params->view, array('', 'article', 'item'));
$is_category = in_array($parent->params->view, array('category'));
if ($is_item)
{
$prefix = 'com_content.article';
}
else if ($is_category)
{
$prefix = 'com_content.category';
}
else
{
return $parent->pass(0, $assignment);
}
// Load the tags.
$parent->q->clear()
->select($parent->db->quoteName('t.id'))
->from('#__tags AS t')
->join(
'INNER', '#__contentitem_tag_map AS m'
. ' ON m.tag_id = t.id'
. ' AND m.type_alias = ' . $parent->db->quote($prefix)
. ' AND m.content_item_id IN ( ' . $parent->params->id . ')'
);
$parent->db->setQuery($parent->q);
$tags = $parent->db->loadColumn();
if (empty($tags))
{
return $parent->pass(0, $assignment);
}
$pass = 0;
foreach ($tags as $tag)
{
$pass = in_array($tag, $selection);
if ($pass && $params->inc_children == 2)
{
$pass = 0;
}
else if (!$pass && $params->inc_children)
{
$parentids = self::getParentIds($parent, $tag);
$parentids = array_diff($parentids, array('1'));
foreach ($parentids as $id)
{
if (in_array($id, $selection))
{
$pass = 1;
break;
}
}
unset($parentids);
}
}
return $parent->pass($pass, $assignment);
}
function getParentIds(&$parent, $id = 0)
{
return $parent->getParentIds($id, 'tags');
}
}
| rusuni/unicyclingru | plugins/system/nnframework/helpers/assignments/tags.php | PHP | gpl-2.0 | 2,139 |
/**
@file TextOutput.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2004-06-21
@edited 2010-03-14
Copyright 2000-2010, Morgan McGuire.
All rights reserved.
*/
#include "G3D/TextOutput.h"
#include "G3D/Log.h"
#include "G3D/fileutils.h"
#include "G3D/FileSystem.h"
namespace G3D {
TextOutput::TextOutput(const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(""),
indentLevel(0)
{
setOptions(opt);
}
TextOutput::TextOutput(const std::string& fil, const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(fil),
indentLevel(0)
{
setOptions(opt);
}
void TextOutput::setIndentLevel(int i) {
indentLevel = i;
// If there were more pops than pushes, don't let that take us below 0 indent.
// Don't ever indent more than the number of columns.
indentSpaces =
iClamp(option.spacesPerIndent * indentLevel,
0,
option.numColumns - 1);
}
void TextOutput::setOptions(const Settings& _opt) {
option = _opt;
debugAssert(option.numColumns > 1);
setIndentLevel(indentLevel);
newline = (option.newlineStyle == Settings::NEWLINE_WINDOWS) ? "\r\n" : "\n";
}
void TextOutput::pushIndent() {
setIndentLevel(indentLevel + 1);
}
void TextOutput::popIndent() {
setIndentLevel(indentLevel - 1);
}
static std::string escape(const std::string& string) {
std::string result = "";
for (std::string::size_type i = 0; i < string.length(); ++i) {
char c = string.at(i);
switch (c) {
case '\0':
result += "\\0";
break;
case '\r':
result += "\\r";
break;
case '\n':
result += "\\n";
break;
case '\t':
result += "\\t";
break;
case '\\':
result += "\\\\";
break;
default:
result += c;
}
}
return result;
}
void TextOutput::writeString(const std::string& string) {
// Convert special characters to escape sequences
this->printf("\"%s\"", escape(string).c_str());
}
void TextOutput::writeBoolean(bool b) {
this->printf("%s ", b ? option.trueSymbol.c_str() : option.falseSymbol.c_str());
}
void TextOutput::writeNumber(double n) {
this->printf("%f ", n);
}
void TextOutput::writeNumber(int n) {
this->printf("%d ", n);
}
void TextOutput::writeSymbol(const std::string& string) {
if (string.size() > 0) {
// TODO: check for legal symbols?
this->printf("%s ", string.c_str());
}
}
void TextOutput::writeSymbols(
const std::string& a,
const std::string& b,
const std::string& c,
const std::string& d,
const std::string& e,
const std::string& f) {
writeSymbol(a);
writeSymbol(b);
writeSymbol(c);
writeSymbol(d);
writeSymbol(e);
writeSymbol(f);
}
void TextOutput::printf(const std::string formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString.c_str(), argList);
va_end(argList);
}
void TextOutput::printf(const char* formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString, argList);
va_end(argList);
}
void TextOutput::convertNewlines(const std::string& in, std::string& out) {
// TODO: can be significantly optimized in cases where
// single characters are copied in order by walking through
// the array and copying substrings as needed.
if (option.convertNewlines) {
out = "";
for (uint32 i = 0; i < in.size(); ++i) {
if (in[i] == '\n') {
// Unix newline
out += newline;
} else if ((in[i] == '\r') && (i + 1 < in.size()) && (in[i + 1] == '\n')) {
// Windows newline
out += newline;
++i;
} else {
out += in[i];
}
}
} else {
out = in;
}
}
void TextOutput::writeNewline() {
for (uint32 i = 0; i < newline.size(); ++i) {
indentAppend(newline[i]);
}
}
void TextOutput::writeNewlines(int numLines) {
for (int i = 0; i < numLines; ++i) {
writeNewline();
}
}
void TextOutput::wordWrapIndentAppend(const std::string& str) {
// TODO: keep track of the last space character we saw so we don't
// have to always search.
if ((option.wordWrap == Settings::WRAP_NONE) ||
(currentColumn + (int)str.size() <= option.numColumns)) {
// No word-wrapping is needed
// Add one character at a time.
// TODO: optimize for strings without newlines to add multiple
// characters.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
}
return;
}
// Number of columns to wrap against
int cols = option.numColumns - indentSpaces;
// Copy forward until we exceed the column size,
// and then back up and try to insert newlines as needed.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) {
// \r\n, we need to hit the \n to enter word wrapping.
++i;
indentAppend(str[i]);
}
if (currentColumn >= cols) {
debugAssertM(str[i] != '\n' && str[i] != '\r',
"Should never enter word-wrapping on a newline character");
// True when we're allowed to treat a space as a space.
bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote;
// Cases:
//
// 1. Currently in a series of spaces that ends with a newline
// strip all spaces and let the newline
// flow through.
//
// 2. Currently in a series of spaces that does not end with a newline
// strip all spaces and replace them with single newline
//
// 3. Not in a series of spaces
// search backwards for a space, then execute case 2.
// Index of most recent space
uint32 lastSpace = data.size() - 1;
// How far back we had to look for a space
uint32 k = 0;
uint32 maxLookBackward = currentColumn - indentSpaces;
// Search backwards (from current character), looking for a space.
while ((k < maxLookBackward) &&
(lastSpace > 0) &&
(! ((data[lastSpace] == ' ') && unquotedSpace))) {
--lastSpace;
++k;
if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) {
unquotedSpace = ! unquotedSpace;
}
}
if (k == maxLookBackward) {
// We couldn't find a series of spaces
if (option.wordWrap == Settings::WRAP_ALWAYS) {
// Strip the last character we wrote, force a newline,
// and replace the last character;
data.pop();
writeNewline();
indentAppend(str[i]);
} else {
// Must be Settings::WRAP_WITHOUT_BREAKING
//
// Don't write the newline; we'll come back to
// the word wrap code after writing another character
}
} else {
// We found a series of spaces. If they continue
// to the new string, strip spaces off both. Otherwise
// strip spaces from data only and insert a newline.
// Find the start of the spaces. firstSpace is the index of the
// first non-space, looking backwards from lastSpace.
uint32 firstSpace = lastSpace;
while ((k < maxLookBackward) &&
(firstSpace > 0) &&
(data[firstSpace] == ' ')) {
--firstSpace;
++k;
}
if (k == maxLookBackward) {
++firstSpace;
}
if (lastSpace == (uint32)data.size() - 1) {
// Spaces continued up to the new string
data.resize(firstSpace + 1);
writeNewline();
// Delete the spaces from the new string
while ((i < str.size() - 1) && (str[i + 1] == ' ')) {
++i;
}
} else {
// Spaces were somewhere in the middle of the old string.
// replace them with a newline.
// Copy over the characters that should be saved
Array<char> temp;
for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) {
char c = data[j];
if (c == '\"') {
// Undo changes to quoting (they will be re-done
// when we paste these characters back on).
inDQuote = !inDQuote;
}
temp.append(c);
}
// Remove those characters and replace with a newline.
data.resize(firstSpace + 1);
writeNewline();
// Write them back
for (uint32 j = 0; j < (uint32)temp.size(); ++j) {
indentAppend(temp[j]);
}
// We are now free to continue adding from the
// new string, which may or may not begin with spaces.
} // if spaces included new string
} // if hit indent
} // if line exceeded
} // iterate over str
}
void TextOutput::indentAppend(char c) {
if (startingNewLine) {
for (int j = 0; j < indentSpaces; ++j) {
data.push(' ');
}
startingNewLine = false;
currentColumn = indentSpaces;
}
data.push(c);
// Don't increment the column count on return character
// newline is taken care of below.
if (c != '\r') {
++currentColumn;
}
if (c == '\"') {
inDQuote = ! inDQuote;
}
startingNewLine = (c == '\n');
if (startingNewLine) {
currentColumn = 0;
}
}
void TextOutput::vprintf(const char* formatString, va_list argPtr) {
std::string str = vformat(formatString, argPtr);
std::string clean;
convertNewlines(str, clean);
wordWrapIndentAppend(clean);
}
void TextOutput::commit(bool flush) {
std::string p = filenamePath(filename);
if (! FileSystem::exists(p, false)) {
FileSystem::createDirectory(p);
}
FILE* f = FileSystem::fopen(filename.c_str(), "wb");
debugAssertM(f, "Could not open \"" + filename + "\"");
fwrite(data.getCArray(), 1, data.size(), f);
if (flush) {
fflush(f);
}
FileSystem::fclose(f);
}
void TextOutput::commitString(std::string& out) {
// Null terminate
data.push('\0');
out = data.getCArray();
data.pop();
}
std::string TextOutput::commitString() {
std::string str;
commitString(str);
return str;
}
/////////////////////////////////////////////////////////////////////
void serialize(const float& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const bool& b, TextOutput& to) {
to.writeSymbol(b ? "true" : "false");
}
void serialize(const int& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const uint8& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const double& b, TextOutput& to) {
to.writeNumber(b);
}
}
| SeTM/MythCore | dep/g3dlite/source/TextOutput.cpp | C++ | gpl-2.0 | 11,994 |
package mx.gob.sct.utic.mimappir.admseg.postgreSQL.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import mx.gob.sct.utic.mimappir.admseg.postgreSQL.model.SEGUSUARIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
/**
* A custom service for retrieving users from a custom datasource, such as a
* database.
* <p>
* This custom service must implement Spring's {@link UserDetailsService}
*/
@Transactional(value="transactionManager_ADMSEG_POSGIS",readOnly=true)
public class CustomUserDetailsService implements UserDetailsService{
private SEGUSUARIO_Service SEGUSUARIO_Service;
//private UserDAO userDAO2 = new UserDAO();
/**
* Retrieves a user record containing the user's credentials and access.
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// Declare a null Spring User
UserDetails user = null;
try {
// Search database for a user that matches the specified username
// You can provide a custom DAO to access your persistence layer
// Or use JDBC to access your database
// DbUser is our custom domain user. This is not the same as
// Spring's User
List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuario(username);
//List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuariosList();
Iterator<SEGUSUARIO> it = registros.iterator();
SEGUSUARIO dbUser = null;
while(it.hasNext()){
dbUser = it.next();
}
// Populate the Spring User object with details from the dbUser
// Here we just pass the username, password, and access level
// getAuthorities() will translate the access level to the correct
// role type
user = new User(dbUser.getCUSUARIO(), dbUser.getCPASSWORD(), true, true,
true, true, getAuthorities(0));
} catch (Exception e) {
throw new UsernameNotFoundException("Error in retrieving user");
}
// Return user to Spring for processing.
// Take note we're not the one evaluating whether this user is
// authenticated or valid
// We just merely retrieve a user that matches the specified username
return user;
}
/**
* Retrieves the correct ROLE type depending on the access level, where
* access level is an Integer. Basically, this interprets the access value
* whether it's for a regular user or admin.
*
* @param access
* an integer value representing the access of the user
* @return collection of granted authorities
*/
public Collection<GrantedAuthority> getAuthorities(Integer access) {
// Create a list of grants for this user
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
// All users are granted with ROLE_USER access
// Therefore this user gets a ROLE_USER by default
authList.add(new GrantedAuthorityImpl("ROLE_USER"));
// Check if this user has admin access
// We interpret Integer(1) as an admin user
if (access.compareTo(1) == 0) {
// User has admin access
authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
}
// Return list of granted authorities
return authList;
}
@Autowired
public void setMenuService(SEGUSUARIO_Service service) {
this.SEGUSUARIO_Service = service;
}
} | IvanSantiago/retopublico | MiMappir/src/mx/gob/sct/utic/mimappir/admseg/postgreSQL/services/CustomUserDetailsService.java | Java | gpl-2.0 | 3,913 |
<?php
/* core/themes/classy/templates/views/views-view-grid.html.twig */
class __TwigTemplate_b1b5e6a9a8cd209497117279c69ebc6612c8c2cb7794b0f45dd07835addb061c 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())
{
$tags = array("set" => 28, "if" => 35, "for" => 56);
$filters = array();
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('set', 'if', 'for'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 28
$context["classes"] = array(0 => "views-view-grid", 1 => $this->getAttribute( // line 30
(isset($context["options"]) ? $context["options"] : null), "alignment", array()), 2 => ("cols-" . $this->getAttribute( // line 31
(isset($context["options"]) ? $context["options"] : null), "columns", array())), 3 => "clearfix");
// line 35
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) {
// line 36
echo " ";
// line 37
$context["row_classes"] = array(0 => "views-row", 1 => ((($this->getAttribute( // line 39
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) ? ("clearfix") : ("")));
}
// line 43
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) {
// line 44
echo " ";
// line 45
$context["col_classes"] = array(0 => "views-col", 1 => ((($this->getAttribute( // line 47
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "vertical")) ? ("clearfix") : ("")));
}
// line 51
if ((isset($context["title"]) ? $context["title"] : null)) {
// line 52
echo " <h3>";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (isset($context["title"]) ? $context["title"] : null), "html", null, true));
echo "</h3>
";
}
// line 54
echo "<div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 55
if (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) {
// line 56
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 57
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 58
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 59
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 60
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["column"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 63
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 65
echo " ";
} else {
// line 66
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 67
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 68
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 69
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 70
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["row"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 73
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 75
echo " ";
}
// line 76
echo "</div>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/views/views-view-grid.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 238 => 76, 235 => 75, 220 => 73, 203 => 70, 198 => 69, 181 => 68, 176 => 67, 158 => 66, 155 => 65, 140 => 63, 123 => 60, 118 => 59, 101 => 58, 96 => 57, 78 => 56, 76 => 55, 71 => 54, 65 => 52, 63 => 51, 60 => 47, 59 => 45, 57 => 44, 55 => 43, 52 => 39, 51 => 37, 49 => 36, 47 => 35, 45 => 31, 44 => 30, 43 => 28,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{#
/**
* @file
* Theme override for views to display rows in a grid.
*
* Available variables:
* - attributes: HTML attributes for the wrapping element.
* - title: The title of this group of rows.
* - view: The view object.
* - rows: The rendered view results.
* - options: The view plugin style options.
* - row_class_default: A flag indicating whether default classes should be
* used on rows.
* - col_class_default: A flag indicating whether default classes should be
* used on columns.
* - items: A list of grid items. Each item contains a list of rows or columns.
* The order in what comes first (row or column) depends on which alignment
* type is chosen (horizontal or vertical).
* - attributes: HTML attributes for each row or column.
* - content: A list of columns or rows. Each row or column contains:
* - attributes: HTML attributes for each row or column.
* - content: The row or column contents.
*
* @see template_preprocess_views_view_grid()
*/
#}
{%
set classes = [
'views-view-grid',
options.alignment,
'cols-' ~ options.columns,
'clearfix',
]
%}
{% if options.row_class_default %}
{%
set row_classes = [
'views-row',
options.alignment == 'horizontal' ? 'clearfix',
]
%}
{% endif %}
{% if options.col_class_default %}
{%
set col_classes = [
'views-col',
options.alignment == 'vertical' ? 'clearfix',
]
%}
{% endif %}
{% if title %}
<h3>{{ title }}</h3>
{% endif %}
<div{{ attributes.addClass(classes) }}>
{% if options.alignment == 'horizontal' %}
{% for row in items %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{% for column in row.content %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{{ column.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% else %}
{% for column in items %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{% for row in column.content %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{{ row.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% endif %}
</div>
", "core/themes/classy/templates/views/views-view-grid.html.twig", "/mnt/jeet/www/local/chipc/core/themes/classy/templates/views/views-view-grid.html.twig");
}
}
| jeetpatel/commerce | sites/default/files/php/twig/59bab1c8da2f0_views-view-grid.html.twig_EPlGe06aVJoi4zUrFjATKjYCr/1EZjvIiVVOjfsiRwHdlwVHySb4hg_3u82WztPZQxA3Y.php | PHP | gpl-2.0 | 17,619 |
<?php
/**
* @version $Id: joocmavatar.php 48 2010-02-08 22:15:48Z sterob $
* @package Joo!CM
* @copyright Copyright (C) 2007-2010 Joo!BB Project. All rights reserved.
* @license GNU/GPL. Please see license.php in Joo!CM directory
* for copyright notices and details.
* Joo!CM is free software. This version may have been NOT modified.
*/
/**
* Joocm Avatar Table Class
*
* @package Joo!CM
*/
class JTableJoocmAvatar extends JTable {
/** @var int Unique id*/
var $id = null;
/** @var string */
var $avatar_file = null;
/** @var int */
var $published = null;
/** @var int */
var $checked_out = null;
/** @var datetime */
var $checked_out_time = null;
/** @var int */
var $id_user = null;
/**
* @param database A database connector object
*/
function __construct(&$db) {
parent::__construct('#__joocm_avatars', 'id', $db);
}
}
?> | srajib/share2learn | administrator/components/com_joocm/tables/joocmavatar.php | PHP | gpl-2.0 | 891 |
package org.ljc.adoptojdk.class_name;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ResolveSimpleNameClassName {
private Collection<String> packages = null;
public Collection<String> getPackages() {
Set<String> returnPackages = new HashSet<String>();
for (Package aPackage : Package.getPackages()) {
returnPackages.add(aPackage.getName());
}
return returnPackages;
}
public List<String> getFullyQualifiedNames(String simpleName) {
if (this.packages == null) {
this.packages = getPackages();
}
List<String> fqns = new ArrayList<String>();
for (String aPackage : packages) {
try {
String fqn = aPackage + "." + simpleName;
Class.forName(fqn);
fqns.add(fqn);
} catch (Exception e) {
// Ignore
}
}
return fqns;
}
}
| neomatrix369/OpenJDKProductivityTool | src/main/java/org/ljc/adoptojdk/class_name/ResolveSimpleNameClassName.java | Java | gpl-2.0 | 1,001 |
/*
* Copyright (C) 2000 Matthias Elter <elter@kde.org>
* Copyright (C) 2001-2002 Raffaele Sandrini <sandrini@kde.org)
* Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
*
* 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 <unistd.h>
#include <tqcstring.h>
#include <tqcursor.h>
#include <tqdatastream.h>
#include <tqdir.h>
#include <tqdragobject.h>
#include <tqfileinfo.h>
#include <tqheader.h>
#include <tqpainter.h>
#include <tqpopupmenu.h>
#include <tqregexp.h>
#include <tqstringlist.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <kinputdialog.h>
#include <tdelocale.h>
#include <ksimpleconfig.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kdesktopfile.h>
#include <tdeaction.h>
#include <tdemessagebox.h>
#include <tdeapplication.h>
#include <kservice.h>
#include <kservicegroup.h>
#include <tdemultipledrag.h>
#include <kurldrag.h>
#include "treeview.h"
#include "treeview.moc"
#include "khotkeys.h"
#include "menufile.h"
#include "menuinfo.h"
#define MOVE_FOLDER 'M'
#define COPY_FOLDER 'C'
#define MOVE_FILE 'm'
#define COPY_FILE 'c'
#define COPY_SEPARATOR 'S'
TreeItem::TreeItem(TQListViewItem *parent, TQListViewItem *after, const TQString& menuId, bool __init)
:TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
TreeItem::TreeItem(TQListView *parent, TQListViewItem *after, const TQString& menuId, bool __init)
: TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
void TreeItem::setName(const TQString &name)
{
_name = name;
update();
}
void TreeItem::setHidden(bool b)
{
if (_hidden == b) return;
_hidden = b;
update();
}
void TreeItem::update()
{
TQString s = _name;
if (_hidden)
s += i18n(" [Hidden]");
setText(0, s);
}
void TreeItem::setOpen(bool o)
{
if (o)
load();
TQListViewItem::setOpen(o);
}
void TreeItem::load()
{
if (m_folderInfo && !_init)
{
_init = true;
TreeView *tv = static_cast<TreeView *>(listView());
tv->fillBranch(m_folderInfo, this);
}
}
void TreeItem::paintCell ( TQPainter * p, const TQColorGroup & cg, int column, int width, int align )
{
TQListViewItem::paintCell(p, cg, column, width, align);
if (!m_folderInfo && !m_entryInfo)
{
// Draw Separator
int h = (height() / 2) -1;
if (isSelected())
p->setPen( cg.highlightedText() );
else
p->setPen( cg.text() );
p->drawLine(0, h,
width, h);
}
}
void TreeItem::setup()
{
TQListViewItem::setup();
if (!m_folderInfo && !m_entryInfo)
setHeight(8);
}
static TQPixmap appIcon(const TQString &iconName)
{
TQPixmap normal = TDEGlobal::iconLoader()->loadIcon(iconName, TDEIcon::Small, 0, TDEIcon::DefaultState, 0L, true);
// make sure they are not larger than 20x20
if (normal.width() > 20 || normal.height() > 20)
{
TQImage tmp = normal.convertToImage();
tmp = tmp.smoothScale(20, 20);
normal.convertFromImage(tmp);
}
return normal;
}
TreeView::TreeView( bool controlCenter, TDEActionCollection *ac, TQWidget *parent, const char *name )
: TDEListView(parent, name), m_ac(ac), m_rmb(0), m_clipboard(0),
m_clipboardFolderInfo(0), m_clipboardEntryInfo(0),
m_controlCenter(controlCenter), m_layoutDirty(false)
{
setFrameStyle(TQFrame::WinPanel | TQFrame::Sunken);
setAllColumnsShowFocus(true);
setRootIsDecorated(true);
setSorting(-1);
setAcceptDrops(true);
setDropVisualizer(true);
setDragEnabled(true);
setMinimumWidth(240);
addColumn("");
header()->hide();
connect(this, TQT_SIGNAL(dropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)),
TQT_SLOT(slotDropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)));
connect(this, TQT_SIGNAL(clicked( TQListViewItem* )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this,TQT_SIGNAL(selectionChanged ( TQListViewItem * )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this, TQT_SIGNAL(rightButtonPressed(TQListViewItem*, const TQPoint&, int)),
TQT_SLOT(slotRMBPressed(TQListViewItem*, const TQPoint&)));
// connect actions
connect(m_ac->action("newitem"), TQT_SIGNAL(activated()), TQT_SLOT(newitem()));
connect(m_ac->action("newsubmenu"), TQT_SIGNAL(activated()), TQT_SLOT(newsubmenu()));
if (m_ac->action("newsep"))
connect(m_ac->action("newsep"), TQT_SIGNAL(activated()), TQT_SLOT(newsep()));
m_menuFile = new MenuFile( locateLocal("xdgconf-menu", "applications-tdemenuedit.menu"));
m_rootFolder = new MenuFolderInfo;
m_separator = new MenuSeparatorInfo;
m_drag = 0;
// Read menu format configuration information
TDESharedConfig::Ptr pConfig = TDESharedConfig::openConfig("kickerrc");
pConfig->setGroup("menus");
m_detailedMenuEntries = pConfig->readBoolEntry("DetailedMenuEntries",true);
if (m_detailedMenuEntries)
{
m_detailedEntriesNamesFirst = pConfig->readBoolEntry("DetailedEntriesNamesFirst",false);
}
}
TreeView::~TreeView() {
cleanupClipboard();
delete m_rootFolder;
delete m_separator;
}
void TreeView::setViewMode(bool showHidden)
{
delete m_rmb;
// setup rmb menu
m_rmb = new TQPopupMenu(this);
TDEAction *action;
action = m_ac->action("edit_cut");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(cut()));
}
action = m_ac->action("edit_copy");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(copy()));
}
action = m_ac->action("edit_paste");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(paste()));
}
m_rmb->insertSeparator();
action = m_ac->action("delete");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(del()));
}
m_rmb->insertSeparator();
if(m_ac->action("newitem"))
m_ac->action("newitem")->plug(m_rmb);
if(m_ac->action("newsubmenu"))
m_ac->action("newsubmenu")->plug(m_rmb);
if(m_ac->action("newsep"))
m_ac->action("newsep")->plug(m_rmb);
m_showHidden = showHidden;
readMenuFolderInfo();
fill();
}
void TreeView::readMenuFolderInfo(MenuFolderInfo *folderInfo, KServiceGroup::Ptr folder, const TQString &prefix)
{
if (!folderInfo)
{
folderInfo = m_rootFolder;
if (m_controlCenter)
folder = KServiceGroup::baseGroup("settings");
else
folder = KServiceGroup::root();
}
if (!folder || !folder->isValid())
return;
folderInfo->caption = folder->caption();
folderInfo->comment = folder->comment();
// Item names may contain ampersands. To avoid them being converted
// to accelerators, replace them with two ampersands.
folderInfo->hidden = folder->noDisplay();
folderInfo->directoryFile = folder->directoryEntryPath();
folderInfo->icon = folder->icon();
TQString id = folder->relPath();
int i = id.findRev('/', -2);
id = id.mid(i+1);
folderInfo->id = id;
folderInfo->fullId = prefix + id;
KServiceGroup::List list = folder->entries(true, !m_showHidden, true, m_detailedMenuEntries && !m_detailedEntriesNamesFirst);
for(KServiceGroup::List::ConstIterator it = list.begin();
it != list.end(); ++it)
{
KSycocaEntry * e = *it;
if (e->isType(KST_KServiceGroup))
{
KServiceGroup::Ptr g(static_cast<KServiceGroup *>(e));
MenuFolderInfo *subFolderInfo = new MenuFolderInfo();
readMenuFolderInfo(subFolderInfo, g, folderInfo->fullId);
folderInfo->add(subFolderInfo, true);
}
else if (e->isType(KST_KService))
{
folderInfo->add(new MenuEntryInfo(static_cast<KService *>(e)), true);
}
else if (e->isType(KST_KServiceSeparator))
{
folderInfo->add(m_separator, true);
}
}
}
void TreeView::fill()
{
TQApplication::setOverrideCursor(Qt::WaitCursor);
clear();
fillBranch(m_rootFolder, 0);
TQApplication::restoreOverrideCursor();
}
TQString TreeView::findName(KDesktopFile *df, bool deleted)
{
TQString name = df->readName();
if (deleted)
{
if (name == "empty")
name = TQString::null;
if (name.isEmpty())
{
TQString file = df->fileName();
TQString res = df->resource();
bool isLocal = true;
TQStringList files = TDEGlobal::dirs()->findAllResources(res.latin1(), file);
for(TQStringList::ConstIterator it = files.begin();
it != files.end();
++it)
{
if (isLocal)
{
isLocal = false;
continue;
}
KDesktopFile df2(*it);
name = df2.readName();
if (!name.isEmpty() && (name != "empty"))
return name;
}
}
}
return name;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuFolderInfo *folderInfo, bool _init)
{
TreeItem *item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null, _init);
item->setMenuFolderInfo(folderInfo);
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
item->setDirectoryPath(folderInfo->fullId);
item->setHidden(folderInfo->hidden);
item->setExpandable(true);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuEntryInfo *entryInfo, bool _init)
{
bool hidden = entryInfo->hidden;
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, entryInfo->menuId(), _init);
else
item = new TreeItem(parent, after, entryInfo->menuId(),_init);
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setMenuEntryInfo(entryInfo);
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
item->setHidden(hidden);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuSeparatorInfo *, bool _init)
{
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null,_init);
return item;
}
void TreeView::fillBranch(MenuFolderInfo *folderInfo, TreeItem *parent)
{
TQString relPath = parent ? parent->directory() : TQString::null;
TQPtrListIterator<MenuInfo> it( folderInfo->initialLayout );
TreeItem *after = 0;
for (MenuInfo *info; (info = it.current()); ++it)
{
MenuEntryInfo *entry = dynamic_cast<MenuEntryInfo*>(info);
if (entry)
{
after = createTreeItem(parent, after, entry);
continue;
}
MenuFolderInfo *subFolder = dynamic_cast<MenuFolderInfo*>(info);
if (subFolder)
{
after = createTreeItem(parent, after, subFolder);
continue;
}
MenuSeparatorInfo *separator = dynamic_cast<MenuSeparatorInfo*>(info);
if (separator)
{
after = createTreeItem(parent, after, separator);
continue;
}
}
}
void TreeView::closeAllItems(TQListViewItem *item)
{
if (!item) return;
while(item)
{
item->setOpen(false);
closeAllItems(item->firstChild());
item = item->nextSibling();
}
}
void TreeView::selectMenu(const TQString &menu)
{
closeAllItems(firstChild());
if (menu.length() <= 1)
{
setCurrentItem(firstChild());
clearSelection();
return; // Root menu
}
TQString restMenu = menu.mid(1);
if (!restMenu.endsWith("/"))
restMenu += "/";
TreeItem *item = 0;
do
{
int i = restMenu.find("/");
TQString subMenu = restMenu.left(i+1);
restMenu = restMenu.mid(i+1);
item = (TreeItem*)(item ? item->firstChild() : firstChild());
while(item)
{
MenuFolderInfo *folderInfo = item->folderInfo();
if (folderInfo && (folderInfo->id == subMenu))
{
item->setOpen(true);
break;
}
item = (TreeItem*) item->nextSibling();
}
}
while( item && !restMenu.isEmpty());
if (item)
{
setCurrentItem(item);
ensureItemVisible(item);
}
}
void TreeView::selectMenuEntry(const TQString &menuEntry)
{
TreeItem *item = (TreeItem *) selectedItem();
if (!item)
{
item = (TreeItem *) currentItem();
while (item && item->isDirectory())
item = (TreeItem*) item->nextSibling();
}
else
item = (TreeItem *) item->firstChild();
while(item)
{
MenuEntryInfo *entry = item->entryInfo();
if (entry && (entry->menuId() == menuEntry))
{
setCurrentItem(item);
ensureItemVisible(item);
return;
}
item = (TreeItem*) item->nextSibling();
}
}
void TreeView::itemSelected(TQListViewItem *item)
{
TreeItem *_item = (TreeItem*)item;
bool selected = false;
bool dselected = false;
if (_item) {
selected = true;
dselected = _item->isHidden();
}
m_ac->action("edit_cut")->setEnabled(selected);
m_ac->action("edit_copy")->setEnabled(selected);
if (m_ac->action("delete"))
m_ac->action("delete")->setEnabled(selected && !dselected);
if(!item)
{
emit disableAction();
return;
}
if (_item->isDirectory())
emit entrySelected(_item->folderInfo());
else
emit entrySelected(_item->entryInfo());
}
void TreeView::currentChanged(MenuFolderInfo *folderInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (folderInfo == 0) return;
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
}
void TreeView::currentChanged(MenuEntryInfo *entryInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (entryInfo == 0) return;
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
}
TQStringList TreeView::fileList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList filelist;
// loop through all resource dirs and build a file list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Files);
dir.setNameFilter("*.desktop;*.kdelnk");
// build a list of files
TQStringList files = dir.entryList();
for (TQStringList::ConstIterator it = files.begin(); it != files.end(); ++it) {
// does not work?!
//if (filelist.contains(*it)) continue;
if (relativePath.isEmpty()) {
filelist.remove(*it); // hack
filelist.append(*it);
}
else {
filelist.remove(relativePath + "/" + *it); //hack
filelist.append(relativePath + "/" + *it);
}
}
}
return filelist;
}
TQStringList TreeView::dirList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList dirlist;
// loop through all resource dirs and build a subdir list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Dirs);
// build a list of subdirs
TQStringList subdirs = dir.entryList();
for (TQStringList::ConstIterator it = subdirs.begin(); it != subdirs.end(); ++it) {
if ((*it) == "." || (*it) == "..") continue;
// does not work?!
// if (dirlist.contains(*it)) continue;
if (relativePath.isEmpty()) {
dirlist.remove(*it); //hack
dirlist.append(*it);
}
else {
dirlist.remove(relativePath + "/" + *it); //hack
dirlist.append(relativePath + "/" + *it);
}
}
}
return dirlist;
}
bool TreeView::acceptDrag(TQDropEvent* e) const
{
if (e->provides("application/x-kmenuedit-internal") &&
(e->source() == const_cast<TreeView *>(this)))
return true;
KURL::List urls;
if (KURLDrag::decode(e, urls) && (urls.count() == 1) &&
urls[0].isLocalFile() && urls[0].path().endsWith(".desktop"))
return true;
return false;
}
static TQString createDesktopFile(const TQString &file, TQString *menuId, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQRegExp r("(.*)(?=-\\d+)");
base = (r.search(base) > -1) ? r.cap(1) : base;
TQString result = KService::newServicePath(true, base, menuId, excludeList);
excludeList->append(*menuId);
// Todo for Undo-support: Undo menuId allocation:
return result;
}
static KDesktopFile *copyDesktopFile(MenuEntryInfo *entryInfo, TQString *menuId, TQStringList *excludeList)
{
TQString result = createDesktopFile(entryInfo->file(), menuId, excludeList);
KDesktopFile *df = entryInfo->desktopFile()->copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
return df;
}
static TQString createDirectoryFile(const TQString &file, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQString result;
int i = 1;
while(true)
{
if (i == 1)
result = base + ".directory";
else
result = base + TQString("-%1.directory").arg(i);
if (!excludeList->contains(result))
{
if (locate("xdgdata-dirs", result).isEmpty())
break;
}
i++;
}
excludeList->append(result);
result = locateLocal("xdgdata-dirs", result);
return result;
}
void TreeView::slotDropped (TQDropEvent * e, TQListViewItem *parent, TQListViewItem*after)
{
if(!e) return;
// get destination folder
TreeItem *parentItem = static_cast<TreeItem*>(parent);
TQString folder = parentItem ? parentItem->directory() : TQString::null;
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
if (e->source() != this)
{
// External drop
KURL::List urls;
if (!KURLDrag::decode(e, urls) || (urls.count() != 1) || !urls[0].isLocalFile())
return;
TQString path = urls[0].path();
if (!path.endsWith(".desktop"))
return;
TQString menuId;
TQString result = createDesktopFile(path, &menuId, &m_newMenuIds);
KDesktopFile orig_df(path);
KDesktopFile *df = orig_df.copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
m_drag = 0;
setLayoutDirty(parentItem);
return;
}
// is there content in the clipboard?
if (!m_drag) return;
if (m_dragItem == after) return; // Nothing to do
int command = m_drag;
if (command == MOVE_FOLDER)
{
MenuFolderInfo *folderInfo = m_dragInfo;
if (e->action() == TQDropEvent::Copy)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else
{
TreeItem *tmpItem = static_cast<TreeItem*>(parentItem);
while ( tmpItem )
{
if ( tmpItem == m_dragItem )
{
m_drag = 0;
return;
}
tmpItem = static_cast<TreeItem*>(tmpItem->parent() );
}
// Remove MenuFolderInfo
TreeItem *oldParentItem = static_cast<TreeItem*>(m_dragItem->parent());
MenuFolderInfo *oldParentFolderInfo = oldParentItem ? oldParentItem->folderInfo() : m_rootFolder;
oldParentFolderInfo->take(folderInfo);
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
//m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->updateFullId(parentFolderInfo->fullId);
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
if ((parentItem != oldParentItem) || !after)
{
if (oldParentItem)
oldParentItem->takeItem(m_dragItem);
else
takeItem(m_dragItem);
if (parentItem)
parentItem->insertItem(m_dragItem);
else
insertItem(m_dragItem);
}
m_dragItem->moveItem(after);
m_dragItem->setName(folderInfo->caption);
m_dragItem->setDirectoryPath(folderInfo->fullId);
setSelected(m_dragItem, true);
itemSelected(m_dragItem);
}
}
else if (command == MOVE_FILE)
{
MenuEntryInfo *entryInfo = m_dragItem->entryInfo();
TQString menuId = entryInfo->menuId();
if (e->action() == TQDropEvent::Copy)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
//UNDO-ACTION: NEW_MENU_ID (menuId)
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else
{
del(m_dragItem, false);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else if (command == COPY_SEPARATOR)
{
if (e->action() != TQDropEvent::Copy)
del(m_dragItem, false);
TreeItem *newItem = createTreeItem(parentItem, after, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// Error
}
m_drag = 0;
setLayoutDirty(parentItem);
}
void TreeView::startDrag()
{
TQDragObject *drag = dragObject();
if (!drag)
return;
drag->dragMove();
}
TQDragObject *TreeView::dragObject()
{
m_dragPath = TQString::null;
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return 0;
KMultipleDrag *drag = new KMultipleDrag( this );
if (item->isDirectory())
{
m_drag = MOVE_FOLDER;
m_dragInfo = item->folderInfo();
m_dragItem = item;
}
else if (item->isEntry())
{
m_drag = MOVE_FILE;
m_dragInfo = 0;
m_dragItem = item;
TQString menuId = item->menuId();
m_dragPath = item->entryInfo()->service->desktopEntryPath();
if (!m_dragPath.isEmpty())
m_dragPath = locate("apps", m_dragPath);
if (!m_dragPath.isEmpty())
{
KURL url;
url.setPath(m_dragPath);
drag->addDragObject( new KURLDrag(url, 0));
}
}
else
{
m_drag = COPY_SEPARATOR;
m_dragInfo = 0;
m_dragItem = item;
}
drag->addDragObject( new TQStoredDrag("application/x-kmenuedit-internal", 0));
if ( item->pixmap(0) )
drag->setPixmap(*item->pixmap(0));
return drag;
}
void TreeView::slotRMBPressed(TQListViewItem*, const TQPoint& p)
{
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return;
if(m_rmb) m_rmb->exec(p);
}
void TreeView::newsubmenu()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Submenu" ),
i18n( "Submenu name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString file = caption;
file.replace('/', '-');
file = createDirectoryFile(file, &m_newDirectoryList); // Create
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
MenuFolderInfo *folderInfo = new MenuFolderInfo();
folderInfo->caption = parentFolderInfo->uniqueMenuCaption(caption);
folderInfo->id = m_menuFile->uniqueMenuName(folder, caption, parentFolderInfo->existingMenuIds());
folderInfo->directoryFile = file;
folderInfo->icon = "package";
folderInfo->hidden = false;
folderInfo->setDirty();
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", folderInfo->caption);
df->writeEntry("Icon", folderInfo->icon);
df->sync();
delete df;
// Add file to menu
// m_menuFile->addMenu(folder + folderInfo->id, file);
m_menuFile->pushAction(MenuFile::ADD_MENU, folder + folderInfo->id, file);
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newitem()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Item" ),
i18n( "Item name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString menuId;
TQString file = caption;
file.replace('/', '-');
file = createDesktopFile(file, &menuId, &m_newMenuIds); // Create
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", caption);
df->writeEntry("Type", "Application");
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newsep()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
if(!item)
{
parentItem = 0;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::cut()
{
copy( true );
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::copy()
{
copy( false );
}
void TreeView::copy( bool cutting )
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to copy
if (item == 0) return;
if (cutting)
setLayoutDirty((TreeItem*)item->parent());
// clean up old stuff
cleanupClipboard();
// is item a folder or a file?
if(item->isDirectory())
{
TQString folder = item->directory();
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
}
}
else if (item->isEntry())
{
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FILE;
m_clipboardEntryInfo = item->entryInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FILE;
m_clipboardEntryInfo = item->entryInfo();
}
}
else
{
// Place in clipboard
m_clipboard = COPY_SEPARATOR;
if (cutting)
del(item, false);
}
m_ac->action("edit_paste")->setEnabled(true);
}
void TreeView::paste()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to paste to
if (item == 0) return;
// is there content in the clipboard?
if (!m_clipboard) return;
// get destination folder
TQString folder;
if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
int command = m_clipboard;
if ((command == COPY_FOLDER) || (command == MOVE_FOLDER))
{
MenuFolderInfo *folderInfo = m_clipboardFolderInfo;
if (command == COPY_FOLDER)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else if (command == MOVE_FOLDER)
{
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
// m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo);
setSelected ( newItem, true);
itemSelected( newItem);
}
m_clipboard = COPY_FOLDER; // Next one copies.
}
else if ((command == COPY_FILE) || (command == MOVE_FILE))
{
MenuEntryInfo *entryInfo = m_clipboardEntryInfo;
TQString menuId;
if (command == COPY_FILE)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else if (command == MOVE_FILE)
{
menuId = entryInfo->menuId();
m_clipboard = COPY_FILE; // Next one copies.
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// create separator
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
setLayoutDirty(parentItem);
}
void TreeView::del()
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to delete
if (item == 0) return;
del(item, true);
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::del(TreeItem *item, bool deleteInfo)
{
TreeItem *parentItem = static_cast<TreeItem*>(item->parent());
// is file a .directory or a .desktop file
if(item->isDirectory())
{
MenuFolderInfo *folderInfo = item->folderInfo();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(folderInfo);
folderInfo->setInUse(false);
if (m_clipboard == COPY_FOLDER && (m_clipboardFolderInfo == folderInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FOLDER; // Clipboard now owns folderInfo
}
else
{
if (folderInfo->takeRecursive(m_clipboardFolderInfo))
m_clipboard = MOVE_FOLDER; // Clipboard now owns m_clipboardFolderInfo
if (deleteInfo)
delete folderInfo; // Delete folderInfo
}
// Remove from menu
// m_menuFile->removeMenu(item->directory());
m_menuFile->pushAction(MenuFile::REMOVE_MENU, item->directory(), TQString::null);
// Remove tree item
delete item;
}
else if (item->isEntry())
{
MenuEntryInfo *entryInfo = item->entryInfo();
TQString menuId = entryInfo->menuId();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(entryInfo);
entryInfo->setInUse(false);
if (m_clipboard == COPY_FILE && (m_clipboardEntryInfo == entryInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FILE; // Clipboard now owns entryInfo
}
else
{
if (deleteInfo)
delete entryInfo; // Delete entryInfo
}
// Remove from menu
TQString folder = parentItem ? parentItem->directory() : TQString::null;
// m_menuFile->removeEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::REMOVE_ENTRY, folder, menuId);
// Remove tree item
delete item;
}
else
{
// Remove separator
delete item;
}
setLayoutDirty(parentItem);
}
void TreeView::cleanupClipboard() {
if (m_clipboard == MOVE_FOLDER)
delete m_clipboardFolderInfo;
m_clipboardFolderInfo = 0;
if (m_clipboard == MOVE_FILE)
delete m_clipboardEntryInfo;
m_clipboardEntryInfo = 0;
m_clipboard = 0;
}
static TQStringList extractLayout(TreeItem *item)
{
bool firstFolder = true;
bool firstEntry = true;
TQStringList layout;
for(;item; item = static_cast<TreeItem*>(item->nextSibling()))
{
if (item->isDirectory())
{
if (firstFolder)
{
firstFolder = false;
layout << ":M"; // Add new folders here...
}
layout << (item->folderInfo()->id);
}
else if (item->isEntry())
{
if (firstEntry)
{
firstEntry = false;
layout << ":F"; // Add new entries here...
}
layout << (item->entryInfo()->menuId());
}
else
{
layout << ":S";
}
}
return layout;
}
TQStringList TreeItem::layout()
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
_layoutDirty = false;
return layout;
}
void TreeView::saveLayout()
{
if (m_layoutDirty)
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
m_menuFile->setLayout(m_rootFolder->fullId, layout);
m_layoutDirty = false;
}
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
TreeItem *item = static_cast<TreeItem*>(it.current());
if ( item->isLayoutDirty() )
{
m_menuFile->setLayout(item->folderInfo()->fullId, item->layout());
}
++it;
}
}
bool TreeView::save()
{
saveLayout();
m_rootFolder->save(m_menuFile);
bool success = m_menuFile->performAllActions();
m_newMenuIds.clear();
m_newDirectoryList.clear();
if (success)
{
KService::rebuildKSycoca(this);
}
else
{
KMessageBox::sorry(this, "<qt>"+i18n("Menu changes could not be saved because of the following problem:")+"<br><br>"+
m_menuFile->error()+"</qt>");
}
return success;
}
void TreeView::setLayoutDirty(TreeItem *parentItem)
{
if (parentItem)
parentItem->setLayoutDirty();
else
m_layoutDirty = true;
}
bool TreeView::isLayoutDirty()
{
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
if ( static_cast<TreeItem*>(it.current())->isLayoutDirty() )
return true;
++it;
}
return false;
}
bool TreeView::dirty()
{
return m_layoutDirty || m_rootFolder->hasDirt() || m_menuFile->dirty() || isLayoutDirty();
}
void TreeView::findServiceShortcut(const TDEShortcut&cut, KService::Ptr &service)
{
service = m_rootFolder->findServiceShortcut(cut);
}
| Fat-Zer/tdebase | kmenuedit/treeview.cpp | C++ | gpl-2.0 | 42,979 |
/*
* Copyright (C) Dag Henning Liodden Sørbø <daghenning@lioddensorbo.com>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "drawingview.h"
#include <QApplication>
#include "randomgenerator.h"
#include "drawingcontroller.h"
#include "drawingsetupcontroller.h"
#include "lotwindow.h"
#include "app.h"
#include <QLibraryInfo>
#include <QTranslator>
#include "color.h"
#include "settingshandler.h"
#include "selectlanguagedialog.h"
#include "updatereminder.h"
#include "updateview.h"
#include "i18n.h"
bool setLanguageToSystemLanguage() {
QString langCountry = QLocale().system().name();
QString lang = langCountry.left(2);
if (lang == "nb" || lang == "nn") {
lang = "no";
}
bool langIsSupported = false;
for (int i = 0; i < NUM_LANGUAGES; ++i) {
if (LANGUAGES[i][1] == lang) {
langIsSupported = true;
}
}
if (langIsSupported) {
SettingsHandler::setLanguage(lang);
}
return langIsSupported;
}
int setupLanguage(QApplication& app) {
if (!SettingsHandler::hasLanguage()) {
bool ok = setLanguageToSystemLanguage();
if (!ok) {
SelectLanguageDialog dialog;
if (dialog.exec() == QDialog::Rejected) {
return -1;
}
}
}
QString language = SettingsHandler::language();
if (language != "en") {
QTranslator* translator = new QTranslator();
QString filename = QString(language).append(".qm");
translator->load(filename, ":/app/translations");
app.installTranslator(translator);
}
return 0;
}
int main(int argc, char *argv[])
{
RandomGenerator::init();
qRegisterMetaTypeStreamOperators<Color>("Color");
QApplication app(argc, argv);
app.setApplicationName(APPLICATION_NAME);
app.setApplicationDisplayName(APPLICATION_NAME);
app.setApplicationVersion(APPLICATION_VERSION);
app.setOrganizationName(ORG_NAME);
app.setOrganizationDomain(ORG_DOMAIN);
QIcon icon(":/gui/icons/lots.svg");
app.setWindowIcon(icon);
#ifdef Q_OS_MAC
app.setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif
SettingsHandler::initialize(ORG_NAME, APPLICATION_NAME);
if (int res = setupLanguage(app) != 0) {
return res;
}
DrawingSetupController setupController;
DrawingSetupDialog setupDialog(&setupController);
DrawingController controller;
DrawingView drawingView(&controller, &setupDialog);
controller.setDrawingView(&drawingView);
UpdateView updateView(&setupDialog);
UpdateReminder reminder([&](UpdateInfo info) {
if (!info.hasError && info.hasUpdate) {
updateView.setUpdateInfo(info);
updateView.show();
}
});
if (!SettingsHandler::autoUpdatesDisabled()) {
reminder.checkForUpdate();
}
return app.exec();
}
| Soerboe/Urim | app/main.cpp | C++ | gpl-2.0 | 3,410 |
/** ======================================================================== */
/** */
/** @copyright Copyright (c) 2010-2015, S2S s.r.l. */
/** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */
/** @version 6.0 */
/** This file is part of SdS - Sistema della Sicurezza . */
/** SdS - Sistema della Sicurezza 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. */
/** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */
/** */
/** ======================================================================== */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.apconsulting.luna.ejb.Corsi;
/**
*
* @author Dario
*/
public class MaterialeCorso_View implements java.io.Serializable {
public long COD_DOC;
public String TIT_DOC;
public java.sql.Date DAT_REV_DOC;
public String RSP_DOC;
public String NOME_FILE;
}
| s2sprodotti/SDS | SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/Corsi/MaterialeCorso_View.java | Java | gpl-2.0 | 1,710 |
/*
* Copyright (C) 2014-2017 StormCore
*
* 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 "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "vault_of_archavon.h"
enum Events
{
// Koralon
EVENT_BURNING_BREATH = 1,
EVENT_BURNING_FURY = 2,
EVENT_FLAME_CINDER = 3,
EVENT_METEOR_FISTS = 4,
// Flame Warder
EVENT_FW_LAVA_BIRST = 5,
EVENT_FW_METEOR_FISTS = 6
};
enum Spells
{
// Spells Koralon
SPELL_BURNING_BREATH = 66665,
SPELL_BURNING_FURY = 66721,
SPELL_FLAME_CINDER_A = 66684,
SPELL_FLAME_CINDER_B = 66681, // don't know the real relation to SPELL_FLAME_CINDER_A atm.
SPELL_METEOR_FISTS = 66725,
SPELL_METEOR_FISTS_DAMAGE = 66765,
// Spells Flame Warder
SPELL_FW_LAVA_BIRST = 66813,
SPELL_FW_METEOR_FISTS = 66808,
SPELL_FW_METEOR_FISTS_DAMAGE = 66809
};
class boss_koralon : public CreatureScript
{
public:
boss_koralon() : CreatureScript("boss_koralon") { }
struct boss_koralonAI : public BossAI
{
boss_koralonAI(Creature* creature) : BossAI(creature, DATA_KORALON)
{
}
void EnterCombat(Unit* /*who*/) override
{
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000); /// @todo check timer
events.ScheduleEvent(EVENT_BURNING_BREATH, 15000); // 1st after 15sec, then every 45sec
events.ScheduleEvent(EVENT_METEOR_FISTS, 75000); // 1st after 75sec, then every 45sec
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000); /// @todo check timer
_EnterCombat();
}
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_BURNING_FURY:
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000);
break;
case EVENT_BURNING_BREATH:
DoCast(me, SPELL_BURNING_BREATH);
events.ScheduleEvent(EVENT_BURNING_BREATH, 45000);
break;
case EVENT_METEOR_FISTS:
DoCast(me, SPELL_METEOR_FISTS);
events.ScheduleEvent(EVENT_METEOR_FISTS, 45000);
break;
case EVENT_FLAME_CINDER:
DoCast(me, SPELL_FLAME_CINDER_A);
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_koralonAI(creature);
}
};
/*######
## Npc Flame Warder
######*/
class npc_flame_warder : public CreatureScript
{
public:
npc_flame_warder() : CreatureScript("npc_flame_warder") { }
struct npc_flame_warderAI : public ScriptedAI
{
npc_flame_warderAI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset() override
{
events.Reset();
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 5000);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 10000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FW_LAVA_BIRST:
DoCastVictim(SPELL_FW_LAVA_BIRST);
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 15000);
break;
case EVENT_FW_METEOR_FISTS:
DoCast(me, SPELL_FW_METEOR_FISTS);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 20000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_flame_warderAI(creature);
}
};
class spell_koralon_meteor_fists : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists() : SpellScriptLoader("spell_koralon_meteor_fists") { }
class spell_koralon_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_koralon_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_koralon_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_koralon_meteor_fists_AuraScript();
}
};
class spell_koralon_meteor_fists_damage : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists_damage() : SpellScriptLoader("spell_koralon_meteor_fists_damage") { }
class spell_koralon_meteor_fists_damage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_koralon_meteor_fists_damage_SpellScript);
public:
spell_koralon_meteor_fists_damage_SpellScript()
{
_chainTargets = 0;
}
private:
void FilterTargets(std::list<WorldObject*>& targets)
{
_chainTargets = targets.size();
}
void CalculateSplitDamage()
{
if (_chainTargets)
SetHitDamage(GetHitDamage() / (_chainTargets + 1));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_koralon_meteor_fists_damage_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_TARGET_ENEMY);
OnHit += SpellHitFn(spell_koralon_meteor_fists_damage_SpellScript::CalculateSplitDamage);
}
private:
uint8 _chainTargets;
};
SpellScript* GetSpellScript() const override
{
return new spell_koralon_meteor_fists_damage_SpellScript();
}
};
class spell_flame_warder_meteor_fists : public SpellScriptLoader
{
public:
spell_flame_warder_meteor_fists() : SpellScriptLoader("spell_flame_warder_meteor_fists") { }
class spell_flame_warder_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_flame_warder_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_flame_warder_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_flame_warder_meteor_fists_AuraScript();
}
};
void AddSC_boss_koralon()
{
new boss_koralon();
new npc_flame_warder();
new spell_koralon_meteor_fists();
new spell_koralon_meteor_fists_damage();
new spell_flame_warder_meteor_fists();
}
| Ragebones/StormCore | src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp | C++ | gpl-2.0 | 9,922 |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: version.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url http://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
require_once JPATH_COMPONENT.'/helpers/helper_version.php';
// Model
class CCKModelVersion extends JCckBaseLegacyModelAdmin
{
protected $text_prefix = 'COM_CCK';
protected $vName = 'version';
// populateState
protected function populateState()
{
$app = JFactory::getApplication( 'administrator' );
$pk = $app->input->getInt( 'id', 0 );
$this->setState( 'version.id', $pk );
}
// getForm
public function getForm( $data = array(), $loadData = true )
{
$form = $this->loadForm( CCK_COM.'.'.$this->vName, $this->vName, array( 'control' => 'jform', 'load_data' => $loadData ) );
if ( empty( $form ) ) {
return false;
}
return $form;
}
// getItem
public function getItem( $pk = null )
{
if ( $item = parent::getItem( $pk ) ) {
//
}
return $item;
}
// getTable
public function getTable( $type = 'Version', $prefix = CCK_TABLE, $config = array() )
{
return JTable::getInstance( $type, $prefix, $config );
}
// loadFormData
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState( CCK_COM.'.edit.'.$this->vName.'.data', array() );
if ( empty( $data ) ) {
$data = $this->getItem();
}
return $data;
}
// -------- -------- -------- -------- -------- -------- -------- -------- // Store
// prepareData
protected function prepareData()
{
$data = JRequest::get( 'post' );
return $data;
}
// revert
public function revert( $pk, $type )
{
$db = $this->getDbo();
$table = $this->getTable();
if ( !$pk || !$type ) {
return false;
}
$table->load( $pk );
if ( JCck::getConfig_Param( 'version_revert', 1 ) == 1 ) {
Helper_Version::createVersion( $type, $table->e_id, JText::sprintf( 'COM_CCK_VERSION_AUTO_BEFORE_REVERT', $table->e_version ) );
}
$row = JTable::getInstance( $type, 'CCK_Table' );
$row->load( $table->e_id );
$core = JCckDev::fromJSON( $table->e_core );
if ( isset( $row->asset_id ) && $row->asset_id && isset( $core['rules'] ) ) {
JCckDatabase::execute( 'UPDATE #__assets SET rules = "'.$db->escape( $core['rules'] ).'" WHERE id = '.(int)$row->asset_id );
}
// More
if ( $type == 'search' ) {
$clients = array( 1=>'search', 2=>'filter', 3=>'list', 4=>'item', 5=>'order' );
} else {
$clients = array( 1=>'admin', 2=>'site', 3=>'intro', 4=>'content' );
}
foreach ( $clients as $i=>$client ) {
$name = 'e_more'.$i;
$this->_revert_more( $type, $client, $table->e_id, $table->{$name} );
}
// Override
if ( $row->version && ( $row->version != $table->e_version ) ) {
$core['version'] = ++$row->version;
}
$core['checked_out'] = 0;
$core['checked_out_time'] = '0000-00-00 00:00:00';
$row->bind( $core );
$row->check();
$row->store();
return true;
}
// _revert_more
public function _revert_more( $type, $client, $pk, $json )
{
$data = json_decode( $json );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_field' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->fields, array(), array(), array( 'markup'=>'', 'restriction'=>'', 'restriction_options'=>'' ) );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_position' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->positions );
}
}
?> | klas/SEBLOD | administrator/components/com_cck/models/version.php | PHP | gpl-2.0 | 3,951 |
/*
How would you design a stack which, in addition to push and pop, also has a function min
which returns the minimum element? Push, pop and min should all operate in O(1) time.
*/
#include <stdio.h>
#include <map>
using namespace std;
#define N 500
typedef struct Stack
{
int top;
int min;
int value[N];
map<int, int> minTr;
}Stack;
void init(Stack& s)
{
s.top = 0;
s.min = 1 << 30;
}
void push(Stack& s, int val)
{
if(s.top >= N)
{
printf("overflow!\n");
return;
}
s.value[s.top] = val;
if(val < s.min)
{
s.minTr.insert(pair<int, int>(s.top, val));
s.min = val;
}
s.top++;
}
int pop(Stack& s)
{
if(s.top <= 0)
{
printf("Stack is empty!\n");
return 0;
}
s.top--;
int e = s.value[s.top];
if(e == s.min)
{
int ind = s.minTr.rbegin()->first;
if(ind == s.top)
{
s.minTr.erase(s.top);
if(s.minTr.empty())
s.min = 1 << 30;
else
s.min = s.minTr.rbegin()->second;
}
}
return e;
}
int minEle(Stack s)
{
if(s.top == 0)
{
printf("Stack is empty!\n");
return 0;
}
return s.min;
}
void createStack(Stack& s, int *a, int n)
{
for (int i = 0; i < 9; ++i)
{
push(s, a[i]);
//printf("%d %d\n", a[i], minEle(s));
}
}
void popEmpty(Stack s)
{
//printf("hello\n");
while(s.top > 0)
{
int e = pop(s);
printf("%d %d\n", e, s.min);
}
}
int main()
{
int a[9] = {3, 4, 5, 2, 6, 8, 1, 1, 4};
Stack s;
init(s);
createStack(s, a, 9);
popEmpty(s);
return 0;
} | pgxiaolianzi/cracking-the-code-interview | 3_2.cpp | C++ | gpl-2.0 | 1,447 |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2022 MaNGOS <https://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "Common.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "GossipDef.h"
#include "UpdateMask.h"
#include "ScriptMgr.h"
#include "Creature.h"
#include "Pet.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Chat.h"
#include "Item.h"
#ifdef ENABLE_ELUNA
#include "LuaEngine.h"
#endif /* ENABLE_ELUNA */
enum StableResultCode
{
STABLE_ERR_MONEY = 0x01, // "you don't have enough money"
STABLE_ERR_STABLE = 0x06, // currently used in most fail cases
STABLE_SUCCESS_STABLE = 0x08, // stable success
STABLE_SUCCESS_UNSTABLE = 0x09, // unstable/swap success
STABLE_SUCCESS_BUY_SLOT = 0x0A, // buy slot success
STABLE_ERR_EXOTIC = 0x0C, // "you are unable to control exotic creatures"
};
void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TABARDDESIGNER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleTabardVendorActivateOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendTabardVendorActivate(guid);
}
void WorldSession::SendTabardVendorActivate(ObjectGuid guid)
{
WorldPacket data(MSG_TABARDVENDOR_ACTIVATE, 8);
data << ObjectGuid(guid);
SendPacket(&data);
}
void WorldSession::HandleBankerActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
DEBUG_LOG("WORLD: Received opcode CMSG_BANKER_ACTIVATE");
recv_data >> guid;
if (!CheckBanker(guid))
{
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendShowBank(guid);
}
void WorldSession::SendShowBank(ObjectGuid guid)
{
WorldPacket data(SMSG_SHOW_BANK, 8);
data << ObjectGuid(guid);
SendPacket(&data);
}
void WorldSession::HandleTrainerListOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
SendTrainerList(guid);
}
void WorldSession::SendTrainerList(ObjectGuid guid)
{
std::string str = GetMangosString(LANG_NPC_TAINER_HELLO);
SendTrainerList(guid, str);
}
static void SendTrainerSpellHelper(WorldPacket& data, TrainerSpell const* tSpell, TrainerSpellState state, float fDiscountMod, bool can_learn_primary_prof, uint32 reqLevel)
{
bool primary_prof_first_rank = sSpellMgr.IsPrimaryProfessionFirstRankSpell(tSpell->learnedSpell);
SpellChainNode const* chain_node = sSpellMgr.GetSpellChainNode(tSpell->learnedSpell);
data << uint32(tSpell->spell); // learned spell (or cast-spell in profession case)
data << uint8(state == TRAINER_SPELL_GREEN_DISABLED ? TRAINER_SPELL_GREEN : state);
data << uint32(floor(tSpell->spellCost * fDiscountMod));
data << uint32(primary_prof_first_rank && can_learn_primary_prof ? 1 : 0);
// primary prof. learn confirmation dialog
data << uint32(primary_prof_first_rank ? 1 : 0); // must be equal prev. field to have learn button in enabled state
data << uint8(reqLevel);
data << uint32(tSpell->reqSkill);
data << uint32(tSpell->reqSkillValue);
data << uint32(!tSpell->IsCastable() && chain_node ? (chain_node->prev ? chain_node->prev : chain_node->req) : 0);
data << uint32(!tSpell->IsCastable() && chain_node && chain_node->prev ? chain_node->req : 0);
data << uint32(0);
}
void WorldSession::SendTrainerList(ObjectGuid guid, const std::string& strTitle)
{
DEBUG_LOG("WORLD: SendTrainerList");
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
if (!unit)
{
DEBUG_LOG("WORLD: SendTrainerList - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
// trainer list loaded at check;
if (!unit->IsTrainerOf(_player, true))
{
return;
}
CreatureInfo const* ci = unit->GetCreatureInfo();
if (!ci)
{
return;
}
TrainerSpellData const* cSpells = unit->GetTrainerSpells();
TrainerSpellData const* tSpells = unit->GetTrainerTemplateSpells();
if (!cSpells && !tSpells)
{
DEBUG_LOG("WORLD: SendTrainerList - Training spells not found for %s", guid.GetString().c_str());
return;
}
uint32 maxcount = (cSpells ? cSpells->spellList.size() : 0) + (tSpells ? tSpells->spellList.size() : 0);
uint32 trainer_type = cSpells && cSpells->trainerType ? cSpells->trainerType : (tSpells ? tSpells->trainerType : 0);
WorldPacket data(SMSG_TRAINER_LIST, 8 + 4 + 4 + maxcount * 38 + strTitle.size() + 1);
data << ObjectGuid(guid);
data << uint32(trainer_type);
size_t count_pos = data.wpos();
data << uint32(maxcount);
// reputation discount
float fDiscountMod = _player->GetReputationPriceDiscount(unit);
bool can_learn_primary_prof = GetPlayer()->GetFreePrimaryProfessionPoints() > 0;
uint32 count = 0;
if (cSpells)
{
for (TrainerSpellMap::const_iterator itr = cSpells->spellList.begin(); itr != cSpells->spellList.end(); ++itr)
{
TrainerSpell const* tSpell = &itr->second;
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel))
{
continue;
}
reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel);
TrainerSpellState state = _player->GetTrainerSpellState(tSpell, reqLevel);
SendTrainerSpellHelper(data, tSpell, state, fDiscountMod, can_learn_primary_prof, reqLevel);
++count;
}
}
if (tSpells)
{
for (TrainerSpellMap::const_iterator itr = tSpells->spellList.begin(); itr != tSpells->spellList.end(); ++itr)
{
TrainerSpell const* tSpell = &itr->second;
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel))
{
continue;
}
reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel);
TrainerSpellState state = _player->GetTrainerSpellState(tSpell, reqLevel);
SendTrainerSpellHelper(data, tSpell, state, fDiscountMod, can_learn_primary_prof, reqLevel);
++count;
}
}
data << strTitle;
data.put<uint32>(count_pos, count);
SendPacket(&data);
}
void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
uint32 spellId = 0;
recv_data >> guid >> spellId;
DEBUG_LOG("WORLD: Received opcode CMSG_TRAINER_BUY_SPELL Trainer: %s, learn spell id is: %u", guid.GetString().c_str(), spellId);
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleTrainerBuySpellOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
if (!unit->IsTrainerOf(_player, true))
{
return;
}
// check present spell in trainer spell list
TrainerSpellData const* cSpells = unit->GetTrainerSpells();
TrainerSpellData const* tSpells = unit->GetTrainerTemplateSpells();
if (!cSpells && !tSpells)
{
return;
}
// Try find spell in npc_trainer
TrainerSpell const* trainer_spell = cSpells ? cSpells->Find(spellId) : NULL;
// Not found, try find in npc_trainer_template
if (!trainer_spell && tSpells)
{
trainer_spell = tSpells->Find(spellId);
}
// Not found anywhere, cheating?
if (!trainer_spell)
{
return;
}
// can't be learn, cheat? Or double learn with lags...
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(trainer_spell->learnedSpell, &reqLevel))
{
return;
}
reqLevel = trainer_spell->isProvidedReqLevel ? trainer_spell->reqLevel : std::max(reqLevel, trainer_spell->reqLevel);
if (_player->GetTrainerSpellState(trainer_spell, reqLevel) != TRAINER_SPELL_GREEN)
{
return;
}
// apply reputation discount
uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(unit)));
// check money requirement
if (_player->GetMoney() < nSpellCost)
{
return;
}
_player->ModifyMoney(-int32(nSpellCost));
SendPlaySpellVisual(guid, 0xB3); // visual effect on trainer
WorldPacket data(SMSG_PLAY_SPELL_IMPACT, 8 + 4); // visual effect on player
data << _player->GetObjectGuid();
data << uint32(0x016A); // index from SpellVisualKit.dbc
SendPacket(&data);
// learn explicitly or cast explicitly
// TODO - Are these spells really cast correctly this way?
if (trainer_spell->IsCastable())
{
_player->CastSpell(_player, trainer_spell->spell, true);
}
else
{
_player->learnSpell(spellId, false);
}
data.Initialize(SMSG_TRAINER_BUY_SUCCEEDED, 12);
data << ObjectGuid(guid);
data << uint32(spellId); // should be same as in packet from client
SendPacket(&data);
}
void WorldSession::HandleGossipHelloOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_GOSSIP_HELLO");
ObjectGuid guid;
recv_data >> guid;
Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE);
if (!pCreature)
{
DEBUG_LOG("WORLD: HandleGossipHelloOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
pCreature->StopMoving();
if (pCreature->IsSpiritGuide())
{
pCreature->SendAreaSpiritHealerQueryOpcode(_player);
}
if (!sScriptMgr.OnGossipHello(_player, pCreature))
{
_player->PrepareGossipMenu(pCreature, pCreature->GetCreatureInfo()->GossipMenuId);
_player->SendPreparedGossip(pCreature);
}
}
void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_GOSSIP_SELECT_OPTION");
uint32 gossipListId;
uint32 menuId;
ObjectGuid guid;
std::string code;
recv_data >> guid >> menuId >> gossipListId;
if (_player->PlayerTalkClass->GossipOptionCoded(gossipListId))
{
recv_data >> code;
DEBUG_LOG("Gossip code: %s", code.c_str());
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
uint32 sender = _player->PlayerTalkClass->GossipOptionSender(gossipListId);
uint32 action = _player->PlayerTalkClass->GossipOptionAction(gossipListId);
if (guid.IsAnyTypeCreature())
{
Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE);
if (!pCreature)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, pCreature, sender, action, code.empty() ? NULL : code.c_str()))
{
_player->OnGossipSelect(pCreature, gossipListId, menuId);
}
}
else if (guid.IsGameObject())
{
GameObject* pGo = GetPlayer()->GetGameObjectIfCanInteractWith(guid);
if (!pGo)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, pGo, sender, action, code.empty() ? NULL : code.c_str()))
{
_player->OnGossipSelect(pGo, gossipListId, menuId);
}
}
else if (guid.IsItem())
{
Item* item = GetPlayer()->GetItemByGuid(guid);
if (!item)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, item, sender, action, code.empty() ? NULL : code.c_str()))
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - item script for %s not found or you can't interact with it.", item->GetProto()->Name1);
return;
}
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->HandleGossipSelectOption(GetPlayer(), item, GetPlayer()->PlayerTalkClass->GossipOptionSender(gossipListId), GetPlayer()->PlayerTalkClass->GossipOptionAction(gossipListId), code);
#endif /* ENABLE_ELUNA */
}
else if (guid.IsPlayer())
{
if (GetPlayer()->GetGUIDLow() != guid || GetPlayer()->PlayerTalkClass->GetGossipMenu().GetMenuId() != menuId)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->HandleGossipSelectOption(GetPlayer(), menuId, GetPlayer()->PlayerTalkClass->GossipOptionSender(gossipListId), GetPlayer()->PlayerTalkClass->GossipOptionAction(gossipListId), code);
#endif /* ENABLE_ELUNA */
}
}
void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_SPIRIT_HEALER_ACTIVATE");
ObjectGuid guid;
recv_data >> guid;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_SPIRITHEALER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleSpiritHealerActivateOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendSpiritResurrect();
}
void WorldSession::SendSpiritResurrect()
{
_player->ResurrectPlayer(0.5f, true);
_player->DurabilityLossAll(0.25f, true);
// get corpse nearest graveyard
WorldSafeLocsEntry const* corpseGrave = NULL;
Corpse* corpse = _player->GetCorpse();
if (corpse)
corpseGrave = sObjectMgr.GetClosestGraveYard(
corpse->GetPositionX(), corpse->GetPositionY(), corpse->GetPositionZ(), corpse->GetMapId(), _player->GetTeam());
// now can spawn bones
_player->SpawnCorpseBones();
// teleport to nearest from corpse graveyard, if different from nearest to player ghost
if (corpseGrave)
{
WorldSafeLocsEntry const* ghostGrave = sObjectMgr.GetClosestGraveYard(
_player->GetPositionX(), _player->GetPositionY(), _player->GetPositionZ(), _player->GetMapId(), _player->GetTeam());
if (corpseGrave != ghostGrave)
{
_player->TeleportTo(corpseGrave->map_id, corpseGrave->x, corpseGrave->y, corpseGrave->z, _player->GetOrientation());
}
// or update at original position
else
{
_player->GetCamera().UpdateVisibilityForOwner();
_player->UpdateObjectVisibility();
}
}
// or update at original position
else
{
_player->GetCamera().UpdateVisibilityForOwner();
_player->UpdateObjectVisibility();
}
}
void WorldSession::HandleBinderActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid npcGuid;
recv_data >> npcGuid;
if (!GetPlayer()->IsInWorld() || !GetPlayer()->IsAlive())
{
return;
}
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(npcGuid, UNIT_NPC_FLAG_INNKEEPER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleBinderActivateOpcode - %s not found or you can't interact with him.", npcGuid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendBindPoint(unit);
}
void WorldSession::SendBindPoint(Creature* npc)
{
// prevent set homebind to instances in any case
if (GetPlayer()->GetMap()->Instanceable())
{
return;
}
// send spell for bind 3286 bind magic
npc->CastSpell(_player, 3286, true); // Bind
WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8 + 4));
data << npc->GetObjectGuid();
data << uint32(3286); // Bind
SendPacket(&data);
_player->PlayerTalkClass->CloseGossip();
}
void WorldSession::HandleListStabledPetsOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv MSG_LIST_STABLED_PETS");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendStablePet(npcGUID);
}
void WorldSession::SendStablePet(ObjectGuid guid)
{
DEBUG_LOG("WORLD: Recv MSG_LIST_STABLED_PETS Send.");
WorldPacket data(MSG_LIST_STABLED_PETS, 200); // guess size
data << guid;
Pet* pet = _player->GetPet();
size_t wpos = data.wpos();
data << uint8(0); // place holder for slot show number
data << uint8(GetPlayer()->m_stableSlots);
uint8 num = 0; // counter for place holder
// not let move dead pet in slot
if (pet && pet->IsAlive() && pet->getPetType() == HUNTER_PET)
{
data << uint32(pet->GetCharmInfo()->GetPetNumber());
data << uint32(pet->GetEntry());
data << uint32(pet->getLevel());
data << pet->GetName(); // petname
data << uint8(1); // 1 = current, 2/3 = in stable (any from 4,5,... create problems with proper show)
++num;
}
// 0 1 2 3 4
QueryResult* result = CharacterDatabase.PQuery("SELECT `owner`, `id`, `entry`, `level`, `name` FROM `character_pet` WHERE `owner` = '%u' AND `slot` >= '%u' AND `slot` <= '%u' ORDER BY `slot`",
_player->GetGUIDLow(), PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
do
{
Field* fields = result->Fetch();
data << uint32(fields[1].GetUInt32()); // petnumber
data << uint32(fields[2].GetUInt32()); // creature entry
data << uint32(fields[3].GetUInt32()); // level
data << fields[4].GetString(); // name
data << uint8(2); // 1 = current, 2/3 = in stable (any from 4,5,... create problems with proper show)
++num;
}
while (result->NextRow());
delete result;
}
data.put<uint8>(wpos, num); // set real data to placeholder
SendPacket(&data);
}
void WorldSession::SendStableResult(uint8 res)
{
WorldPacket data(SMSG_STABLE_RESULT, 1);
data << uint8(res);
SendPacket(&data);
}
bool WorldSession::CheckStableMaster(ObjectGuid guid)
{
// spell case or GM
if (guid == GetPlayer()->GetObjectGuid())
{
// command case will return only if player have real access to command
if (!GetPlayer()->HasAuraType(SPELL_AURA_OPEN_STABLE) && !ChatHandler(GetPlayer()).FindCommand("stable"))
{
DEBUG_LOG("%s attempt open stable in cheating way.", guid.GetString().c_str());
return false;
}
}
// stable master case
else
{
if (!GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_STABLEMASTER))
{
DEBUG_LOG("Stablemaster %s not found or you can't interact with him.", guid.GetString().c_str());
return false;
}
}
return true;
}
void WorldSession::HandleStablePet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_STABLE_PET");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!GetPlayer()->IsAlive())
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
Pet* pet = _player->GetPet();
// can't place in stable dead pet
if (!pet || !pet->IsAlive() || pet->getPetType() != HUNTER_PET)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
uint32 free_slot = 1;
QueryResult* result = CharacterDatabase.PQuery("SELECT `owner`,`slot`,`id` FROM `character_pet` WHERE `owner` = '%u' AND `slot` >= '%u' AND `slot` <= '%u' ORDER BY `slot`",
_player->GetGUIDLow(), PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 slot = fields[1].GetUInt32();
// slots ordered in query, and if not equal then free
if (slot != free_slot)
{
break;
}
// this slot not free, skip
++free_slot;
}
while (result->NextRow());
delete result;
}
if (free_slot > 0 && free_slot <= GetPlayer()->m_stableSlots)
{
pet->Unsummon(PetSaveMode(free_slot), _player);
SendStableResult(STABLE_SUCCESS_STABLE);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
}
void WorldSession::HandleUnstablePet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_UNSTABLE_PET.");
ObjectGuid npcGUID;
uint32 petnumber;
recv_data >> npcGUID >> petnumber;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
uint32 creature_id = 0;
{
QueryResult* result = CharacterDatabase.PQuery("SELECT `entry` FROM `character_pet` WHERE `owner` = '%u' AND `id` = '%u' AND `slot` >='%u' AND `slot` <= '%u'",
_player->GetGUIDLow(), petnumber, PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
Field* fields = result->Fetch();
creature_id = fields[0].GetUInt32();
delete result;
}
}
if (!creature_id)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
CreatureInfo const* creatureInfo = ObjectMgr::GetCreatureTemplate(creature_id);
if (!creatureInfo || !creatureInfo->isTameable(_player->CanTameExoticPets()))
{
// if problem in exotic pet
if (creatureInfo && creatureInfo->isTameable(true))
{
SendStableResult(STABLE_ERR_EXOTIC);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
return;
}
Pet* pet = _player->GetPet();
if (pet && pet->IsAlive())
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// delete dead pet
if (pet)
{
pet->Unsummon(PET_SAVE_AS_DELETED, _player);
}
Pet* newpet = new Pet(HUNTER_PET);
if (!newpet->LoadPetFromDB(_player, creature_id, petnumber))
{
delete newpet;
newpet = NULL;
SendStableResult(STABLE_ERR_STABLE);
return;
}
SendStableResult(STABLE_SUCCESS_UNSTABLE);
}
void WorldSession::HandleBuyStableSlot(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_BUY_STABLE_SLOT.");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
if (GetPlayer()->m_stableSlots < MAX_PET_STABLES)
{
StableSlotPricesEntry const* SlotPrice = sStableSlotPricesStore.LookupEntry(GetPlayer()->m_stableSlots + 1);
if (_player->GetMoney() >= SlotPrice->Price)
{
++GetPlayer()->m_stableSlots;
_player->ModifyMoney(-int32(SlotPrice->Price));
SendStableResult(STABLE_SUCCESS_BUY_SLOT);
}
else
{
SendStableResult(STABLE_ERR_MONEY);
}
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
}
void WorldSession::HandleStableRevivePet(WorldPacket& /* recv_data */)
{
DEBUG_LOG("HandleStableRevivePet: Not implemented");
}
void WorldSession::HandleStableSwapPet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_STABLE_SWAP_PET.");
ObjectGuid npcGUID;
uint32 pet_number;
recv_data >> npcGUID >> pet_number;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
Pet* pet = _player->GetPet();
if (!pet || pet->getPetType() != HUNTER_PET)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// find swapped pet slot in stable
QueryResult* result = CharacterDatabase.PQuery("SELECT `slot`,`entry` FROM `character_pet` WHERE `owner` = '%u' AND `id` = '%u'",
_player->GetGUIDLow(), pet_number);
if (!result)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
Field* fields = result->Fetch();
uint32 slot = fields[0].GetUInt32();
uint32 creature_id = fields[1].GetUInt32();
delete result;
if (!creature_id)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
CreatureInfo const* creatureInfo = ObjectMgr::GetCreatureTemplate(creature_id);
if (!creatureInfo || !creatureInfo->isTameable(_player->CanTameExoticPets()))
{
// if problem in exotic pet
if (creatureInfo && creatureInfo->isTameable(true))
{
SendStableResult(STABLE_ERR_EXOTIC);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
return;
}
// move alive pet to slot or delete dead pet
pet->Unsummon(pet->IsAlive() ? PetSaveMode(slot) : PET_SAVE_AS_DELETED, _player);
// summon unstabled pet
Pet* newpet = new Pet;
if (!newpet->LoadPetFromDB(_player, creature_id, pet_number))
{
delete newpet;
SendStableResult(STABLE_ERR_STABLE);
}
else
{
SendStableResult(STABLE_SUCCESS_UNSTABLE);
}
}
void WorldSession::HandleRepairItemOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_REPAIR_ITEM");
ObjectGuid npcGuid;
ObjectGuid itemGuid;
uint8 guildBank; // new in 2.3.2, bool that means from guild bank money
recv_data >> npcGuid >> itemGuid >> guildBank;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(npcGuid, UNIT_NPC_FLAG_REPAIR);
if (!unit)
{
DEBUG_LOG("WORLD: HandleRepairItemOpcode - %s not found or you can't interact with him.", npcGuid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
// reputation discount
float discountMod = _player->GetReputationPriceDiscount(unit);
uint32 TotalCost = 0;
if (itemGuid)
{
DEBUG_LOG("ITEM: %s repair of %s", npcGuid.GetString().c_str(), itemGuid.GetString().c_str());
Item* item = _player->GetItemByGuid(itemGuid);
if (item)
{
TotalCost = _player->DurabilityRepair(item->GetPos(), true, discountMod, (guildBank > 0));
}
}
else
{
DEBUG_LOG("ITEM: %s repair all items", npcGuid.GetString().c_str());
TotalCost = _player->DurabilityRepairAll(true, discountMod, (guildBank > 0));
}
if (guildBank)
{
uint32 GuildId = _player->GetGuildId();
if (!GuildId)
{
return;
}
Guild* pGuild = sGuildMgr.GetGuildById(GuildId);
if (!pGuild)
{
return;
}
pGuild->LogBankEvent(GUILD_BANK_LOG_REPAIR_MONEY, 0, _player->GetGUIDLow(), TotalCost);
pGuild->SendMoneyInfo(this, _player->GetGUIDLow());
}
}
| mangostwo/server | src/game/WorldHandlers/NPCHandler.cpp | C++ | gpl-2.0 | 30,883 |
<?php
/* TwigBundle:Exception:exception_full.html.twig */
class __TwigTemplate_12d6106874fca48a5e6b4ba3ab89b6fc520d1b724c37c5efb25ee5ce99e9e8da extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/css/exception.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
";
}
// line 7
public function block_title($context, array $blocks = array())
{
// line 8
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message"), "html", null, true);
echo " (";
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code")), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text")), "html", null, true);
echo ")
";
}
// line 11
public function block_body($context, array $blocks = array())
{
// line 12
echo " ";
$this->env->loadTemplate("TwigBundle:Exception:exception.html.twig")->display($context);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception_full.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 57 => 12, 54 => 11, 43 => 8, 40 => 7, 33 => 4, 30 => 3,);
}
}
| fjbatresv/REMIS | app/cache/dev/twig/12/d6/106874fca48a5e6b4ba3ab89b6fc520d1b724c37c5efb25ee5ce99e9e8da.php | PHP | gpl-2.0 | 2,475 |
module.exports = {
dist: {
options: {
plugin_slug: 'simple-user-adding',
svn_user: 'wearerequired',
build_dir: 'release/svn/',
assets_dir: 'assets/'
}
}
};
| wearerequired/simple-user-adding | grunt/wp_deploy.js | JavaScript | gpl-2.0 | 180 |
<?php
class ezxpdfpreview
{
function ezxpdfpreview()
{
$this->Operators = array( 'pdfpreview' );
}
/*!
\return an array with the template operator name.
*/
function operatorList()
{
return $this->Operators;
}
/*!
\return true to tell the template engine that the parameter list exists per operator type,
this is needed for operator classes that have multiple operators.
*/
function namedParameterPerOperator()
{
return true;
}
/*!
See eZTemplateOperator::namedParameterList
*/
function namedParameterList()
{
return array( 'pdfpreview' => array(
'width' => array( 'type' => 'integer', 'required' => true ),
'height' => array( 'type' => 'integer', 'required' => true ),
'attribute_id' => array( 'type' => 'integer', 'required' => true),
'attribute_version' => array( 'type' => 'integer', 'required' => true),
'page' => array( 'type' => 'integer', 'required' => false, 'default' => 1)
)
);
}
/*!
Executes the PHP function for the operator cleanup and modifies \a $operatorValue.
*/
function modify( &$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters )
{
$ini = eZINI::instance();
$contentId = $operatorValue;
$width = (int)$namedParameters['width'];
$height = (int)$namedParameters['height'];
$container = ezpKernel::instance()->getServiceContainer();
$pdfPreview = $container->get( 'xrow_pdf_preview' );
$operatorValue = $pdfPreview->preview($contentId, $width, $height);
}
function previewRetrieve( $file, $mtime, $args )
{
//do nothing
}
function previewGenerate( $file, $args )
{
extract( $args );
$pdffile->fetch(true);
$cmd = "convert " . eZSys::escapeShellArgument( $pdf_file_path . "[" . $page . "]" ) . " " . " -alpha remove -resize " . eZSys::escapeShellArgument( $width . "x" . $height ) . " " . eZSys::escapeShellArgument( $cacheImageFilePath );
$out = shell_exec( $cmd );
$fileHandler = eZClusterFileHandler::instance();
$fileHandler->fileStore( $cacheImageFilePath, 'pdfpreview', false );
eZDebug::writeDebug( $cmd, "pdfpreview" );
if ( $out )
{
eZDebug::writeDebug( $out, "pdfpreview" );
}
//return values for the storecache function
return array( 'content' => $cacheImageFilePath,
'scope' => 'pdfpreview',
'store' => true );
}
}
?>
| xrowgmbh/pdfpreview | classes/ezxpdfpreview.php | PHP | gpl-2.0 | 2,967 |
<?php
/*
* Copyright (C) 2015 andi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace ErsBase\View\Helper;
use Zend\View\Helper\AbstractHelper;
#use Zend\View\HelperPluginManager as ServiceManager;
use Zend\Session\Container;
class Session extends AbstractHelper {
#protected $serviceManager;
/*public function __construct(ServiceManager $serviceManager) {
$this->serviceManager = $serviceManager;
}*/
public function __invoke() {
$container = new Container('ers');
return $container;
}
} | inbaz/ers | module/ErsBase/src/ErsBase/View/Helper/Session.php | PHP | gpl-2.0 | 1,154 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018-2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.kafka.producer;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.opennms.core.ipc.common.kafka.Utils;
import org.opennms.features.kafka.producer.datasync.KafkaAlarmDataSync;
import org.opennms.features.kafka.producer.model.OpennmsModelProtos;
import org.opennms.features.situationfeedback.api.AlarmFeedback;
import org.opennms.features.situationfeedback.api.AlarmFeedbackListener;
import org.opennms.netmgt.alarmd.api.AlarmCallbackStateTracker;
import org.opennms.netmgt.alarmd.api.AlarmLifecycleListener;
import org.opennms.netmgt.events.api.EventListener;
import org.opennms.netmgt.events.api.EventSubscriptionService;
import org.opennms.netmgt.events.api.ThreadAwareEventListener;
import org.opennms.netmgt.events.api.model.IEvent;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyConsumer;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyDao;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyEdge;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage.TopologyMessageStatus;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyProtocol;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyVertex;
import org.opennms.netmgt.topologies.service.api.TopologyVisitor;
import org.opennms.netmgt.xml.event.Event;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.swrve.ratelimitedlogger.RateLimitedLog;
public class OpennmsKafkaProducer implements AlarmLifecycleListener, EventListener, AlarmFeedbackListener, OnmsTopologyConsumer, ThreadAwareEventListener {
private static final Logger LOG = LoggerFactory.getLogger(OpennmsKafkaProducer.class);
private static final RateLimitedLog RATE_LIMITED_LOGGER = RateLimitedLog
.withRateLimit(LOG)
.maxRate(5).every(Duration.ofSeconds(30))
.build();
public static final String KAFKA_CLIENT_PID = "org.opennms.features.kafka.producer.client";
private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser();
private final ThreadFactory nodeUpdateThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("kafka-producer-node-update-%d")
.build();
private final ProtobufMapper protobufMapper;
private final NodeCache nodeCache;
private final ConfigurationAdmin configAdmin;
private final EventSubscriptionService eventSubscriptionService;
private KafkaAlarmDataSync dataSync;
private String eventTopic;
private String alarmTopic;
private String nodeTopic;
private String alarmFeedbackTopic;
private String topologyVertexTopic;
private String topologyEdgeTopic;
private boolean forwardEvents;
private boolean forwardAlarms;
private boolean forwardAlarmFeedback;
private boolean suppressIncrementalAlarms;
private boolean forwardNodes;
private Expression eventFilterExpression;
private Expression alarmFilterExpression;
private final CountDownLatch forwardedEvent = new CountDownLatch(1);
private final CountDownLatch forwardedAlarm = new CountDownLatch(1);
private final CountDownLatch forwardedNode = new CountDownLatch(1);
private final CountDownLatch forwardedAlarmFeedback = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyVertexMessage = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyEdgeMessage = new CountDownLatch(1);
private KafkaProducer<byte[], byte[]> producer;
private final Map<String, OpennmsModelProtos.Alarm> outstandingAlarms = new ConcurrentHashMap<>();
private final AlarmEqualityChecker alarmEqualityChecker =
AlarmEqualityChecker.with(AlarmEqualityChecker.Exclusions::defaultExclusions);
private final AlarmCallbackStateTracker stateTracker = new AlarmCallbackStateTracker();
private final OnmsTopologyDao topologyDao;
private int kafkaSendQueueCapacity;
private BlockingDeque<KafkaRecord> kafkaSendDeque;
private final ExecutorService kafkaSendQueueExecutor =
Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "KafkaSendQueueProcessor"));
private final ExecutorService nodeUpdateExecutor;
private String encoding = "UTF8";
private int numEventListenerThreads = 4;
public OpennmsKafkaProducer(ProtobufMapper protobufMapper, NodeCache nodeCache,
ConfigurationAdmin configAdmin, EventSubscriptionService eventSubscriptionService,
OnmsTopologyDao topologyDao, int nodeAsyncUpdateThreads) {
this.protobufMapper = Objects.requireNonNull(protobufMapper);
this.nodeCache = Objects.requireNonNull(nodeCache);
this.configAdmin = Objects.requireNonNull(configAdmin);
this.eventSubscriptionService = Objects.requireNonNull(eventSubscriptionService);
this.topologyDao = Objects.requireNonNull(topologyDao);
this.nodeUpdateExecutor = Executors.newFixedThreadPool(nodeAsyncUpdateThreads, nodeUpdateThreadFactory);
}
public void init() throws IOException {
// Create the Kafka producer
final Properties producerConfig = new Properties();
final Dictionary<String, Object> properties = configAdmin.getConfiguration(KAFKA_CLIENT_PID).getProperties();
if (properties != null) {
final Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
final String key = keys.nextElement();
producerConfig.put(key, properties.get(key));
}
}
// Overwrite the serializers, since we rely on these
producerConfig.put("key.serializer", ByteArraySerializer.class.getCanonicalName());
producerConfig.put("value.serializer", ByteArraySerializer.class.getCanonicalName());
// Class-loader hack for accessing the kafka classes when initializing producer.
producer = Utils.runWithGivenClassLoader(() -> new KafkaProducer<>(producerConfig), KafkaProducer.class.getClassLoader());
// Start processing records that have been queued for sending
if (kafkaSendQueueCapacity <= 0) {
kafkaSendQueueCapacity = 1000;
LOG.info("Defaulted the 'kafkaSendQueueCapacity' to 1000 since no property was set");
}
kafkaSendDeque = new LinkedBlockingDeque<>(kafkaSendQueueCapacity);
kafkaSendQueueExecutor.execute(this::processKafkaSendQueue);
if (forwardEvents) {
eventSubscriptionService.addEventListener(this);
}
topologyDao.subscribe(this);
}
public void destroy() {
kafkaSendQueueExecutor.shutdownNow();
nodeUpdateExecutor.shutdownNow();
if (producer != null) {
producer.close();
producer = null;
}
if (forwardEvents) {
eventSubscriptionService.removeEventListener(this);
}
topologyDao.unsubscribe(this);
}
private void forwardTopologyMessage(OnmsTopologyMessage message) {
if (message.getProtocol() == null) {
LOG.error("forwardTopologyMessage: null protocol");
return;
}
if (message.getMessagestatus() == null) {
LOG.error("forwardTopologyMessage: null status");
return;
}
if (message.getMessagebody() == null) {
LOG.error("forwardTopologyMessage: null message");
return;
}
if (message.getMessagestatus() == TopologyMessageStatus.DELETE) {
message.getMessagebody().accept(new DeletingVisitor(message));
} else {
message.getMessagebody().accept(new UpdatingVisitor(message));
}
}
private void forwardTopologyEdgeMessage(byte[] refid, byte[] message) {
sendRecord(() -> {
return new ProducerRecord<>(topologyEdgeTopic, refid, message);
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedTopologyEdgeMessage.countDown();
});
}
private void forwardEvent(Event event) {
boolean shouldForwardEvent = true;
// Filtering
if (eventFilterExpression != null) {
try {
shouldForwardEvent = eventFilterExpression.getValue(event, Boolean.class);
} catch (Exception e) {
LOG.error("Event filter '{}' failed to return a result for event: {}. The event will be forwarded anyways.",
eventFilterExpression.getExpressionString(), event.toStringSimple(), e);
}
}
if (!shouldForwardEvent) {
if (LOG.isTraceEnabled()) {
LOG.trace("Event {} not forwarded due to event filter: {}",
event.toStringSimple(), eventFilterExpression.getExpressionString());
}
return;
}
// Node handling
if (forwardNodes && event.getNodeid() != null && event.getNodeid() != 0) {
updateNodeAsynchronously(event.getNodeid());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Event mappedEvent = protobufMapper.toEvent(event).build();
LOG.debug("Sending event with UEI: {}", mappedEvent.getUei());
return new ProducerRecord<>(eventTopic, mappedEvent.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedEvent.countDown();
});
}
public boolean shouldForwardAlarm(OnmsAlarm alarm) {
if (alarmFilterExpression != null) {
// The expression is not necessarily thread safe
synchronized (this) {
try {
final boolean shouldForwardAlarm = alarmFilterExpression.getValue(alarm, Boolean.class);
if (LOG.isTraceEnabled()) {
LOG.trace("Alarm {} not forwarded due to event filter: {}",
alarm, alarmFilterExpression.getExpressionString());
}
return shouldForwardAlarm;
} catch (Exception e) {
LOG.error("Alarm filter '{}' failed to return a result for event: {}. The alarm will be forwarded anyways.",
alarmFilterExpression.getExpressionString(), alarm, e);
}
}
}
return true;
}
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
OpennmsModelProtos.Alarm existingAlarm = outstandingAlarms.get(reductionKey);
return existingAlarm != null && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm),
existingAlarm);
}
private void recordIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
// Apply the excluded fields when putting to the map so we do not have to perform this calculation
// on each equality check
outstandingAlarms.put(reductionKey,
AlarmEqualityChecker.Exclusions.defaultExclusions(protobufMapper.toAlarm(alarm)).build());
}
private void updateAlarm(String reductionKey, OnmsAlarm alarm) {
// Always push null records, no good way to perform filtering on these
if (alarm == null) {
// The alarm has been deleted so we shouldn't track it in the map of outstanding alarms any longer
outstandingAlarms.remove(reductionKey);
// The alarm was deleted, push a null record to the reduction key
sendRecord(() -> {
LOG.debug("Deleting alarm with reduction key: {}", reductionKey);
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), null);
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
return;
}
// Filtering
if (!shouldForwardAlarm(alarm)) {
return;
}
if (suppressIncrementalAlarms && isIncrementalAlarm(reductionKey, alarm)) {
return;
}
// Node handling
if (forwardNodes && alarm.getNodeId() != null) {
updateNodeAsynchronously(alarm.getNodeId());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Alarm mappedAlarm = protobufMapper.toAlarm(alarm).build();
LOG.debug("Sending alarm with reduction key: {}", reductionKey);
if (suppressIncrementalAlarms) {
recordIncrementalAlarm(reductionKey, alarm);
}
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), mappedAlarm.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
}
private void updateNodeAsynchronously(long nodeId) {
// Updating node asynchronously will unblock event consumption.
nodeUpdateExecutor.execute(() -> {
maybeUpdateNode(nodeId);
});
}
private void maybeUpdateNode(long nodeId) {
nodeCache.triggerIfNeeded(nodeId, (node) -> {
final String nodeCriteria;
if (node != null && node.getForeignSource() != null && node.getForeignId() != null) {
nodeCriteria = String.format("%s:%s", node.getForeignSource(), node.getForeignId());
} else {
nodeCriteria = Long.toString(nodeId);
}
if (node == null) {
// The node was deleted, push a null record
sendRecord(() -> {
LOG.debug("Deleting node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), null);
});
return;
}
sendRecord(() -> {
final OpennmsModelProtos.Node mappedNode = protobufMapper.toNode(node).build();
LOG.debug("Sending node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), mappedNode.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the node was forwarded
// Let other threads know when we've successfully forwarded a node
forwardedNode.countDown();
});
});
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable) {
sendRecord(callable, null);
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable, Consumer<RecordMetadata> callback) {
if (producer == null) {
return;
}
final ProducerRecord<byte[], byte[]> record;
try {
record = callable.call();
} catch (Exception e) {
// Propagate
throw new RuntimeException(e);
}
// Rather than attempt to send, we instead queue the record to avoid blocking since KafkaProducer's send()
// method can block if Kafka is not available when metadata is attempted to be retrieved
// Any offer that fails due to capacity overflow will simply be dropped and will have to wait until the next
// sync to be processed so this is just a best effort attempt
if (!kafkaSendDeque.offer(new KafkaRecord(record, callback))) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
private void processKafkaSendQueue() {
//noinspection InfiniteLoopStatement
while (true) {
try {
KafkaRecord kafkaRecord = kafkaSendDeque.take();
ProducerRecord<byte[], byte[]> producerRecord = kafkaRecord.getProducerRecord();
Consumer<RecordMetadata> consumer = kafkaRecord.getConsumer();
try {
producer.send(producerRecord, (recordMetadata, e) -> {
if (e != null) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
if (e instanceof TimeoutException) {
// If Kafka is Offline, buffer the record again for events.
// This is best effort to keep the order although in-flight elements may still miss the order.
if (producerRecord != null &&
this.eventTopic.equalsIgnoreCase(producerRecord.topic())) {
if(!kafkaSendDeque.offerFirst(kafkaRecord)) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
}
return;
}
if (consumer != null) {
consumer.accept(recordMetadata);
}
});
} catch (RuntimeException e) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
}
} catch (InterruptedException ignore) {
break;
}
}
}
@Override
public void handleAlarmSnapshot(List<OnmsAlarm> alarms) {
if (!forwardAlarms || dataSync == null) {
// Ignore
return;
}
dataSync.handleAlarmSnapshot(alarms);
}
@Override
public void preHandleAlarmSnapshot() {
stateTracker.startTrackingAlarms();
}
@Override
public void postHandleAlarmSnapshot() {
stateTracker.resetStateAndStopTrackingAlarms();
}
@Override
public void handleNewOrUpdatedAlarm(OnmsAlarm alarm) {
if (!forwardAlarms) {
// Ignore
return;
}
updateAlarm(alarm.getReductionKey(), alarm);
stateTracker.trackNewOrUpdatedAlarm(alarm.getId(), alarm.getReductionKey());
}
@Override
public void handleDeletedAlarm(int alarmId, String reductionKey) {
if (!forwardAlarms) {
// Ignore
return;
}
handleDeletedAlarm(reductionKey);
stateTracker.trackDeletedAlarm(alarmId, reductionKey);
}
private void handleDeletedAlarm(String reductionKey) {
updateAlarm(reductionKey, null);
}
@Override
public String getName() {
return OpennmsKafkaProducer.class.getName();
}
@Override
public void onEvent(IEvent event) {
forwardEvent(Event.copyFrom(event));
}
@Override
public Set<OnmsTopologyProtocol> getProtocols() {
return Collections.singleton(OnmsTopologyProtocol.allProtocols());
}
@Override
public void consume(OnmsTopologyMessage message) {
forwardTopologyMessage(message);
}
public void setTopologyVertexTopic(String topologyVertexTopic) {
this.topologyVertexTopic = topologyVertexTopic;
}
public void setTopologyEdgeTopic(String topologyEdgeTopic) {
this.topologyEdgeTopic = topologyEdgeTopic;
}
public void setEventTopic(String eventTopic) {
this.eventTopic = eventTopic;
forwardEvents = !Strings.isNullOrEmpty(eventTopic);
}
public void setAlarmTopic(String alarmTopic) {
this.alarmTopic = alarmTopic;
forwardAlarms = !Strings.isNullOrEmpty(alarmTopic);
}
public void setNodeTopic(String nodeTopic) {
this.nodeTopic = nodeTopic;
forwardNodes = !Strings.isNullOrEmpty(nodeTopic);
}
public void setAlarmFeedbackTopic(String alarmFeedbackTopic) {
this.alarmFeedbackTopic = alarmFeedbackTopic;
forwardAlarmFeedback = !Strings.isNullOrEmpty(alarmFeedbackTopic);
}
public void setEventFilter(String eventFilter) {
if (Strings.isNullOrEmpty(eventFilter)) {
eventFilterExpression = null;
} else {
eventFilterExpression = SPEL_PARSER.parseExpression(eventFilter);
}
}
public void setAlarmFilter(String alarmFilter) {
if (Strings.isNullOrEmpty(alarmFilter)) {
alarmFilterExpression = null;
} else {
alarmFilterExpression = SPEL_PARSER.parseExpression(alarmFilter);
}
}
public OpennmsKafkaProducer setDataSync(KafkaAlarmDataSync dataSync) {
this.dataSync = dataSync;
return this;
}
@Override
public void handleAlarmFeedback(List<AlarmFeedback> alarmFeedback) {
if (!forwardAlarmFeedback) {
return;
}
// NOTE: This will currently block while waiting for Kafka metadata if Kafka is not available.
alarmFeedback.forEach(feedback -> sendRecord(() -> {
LOG.debug("Sending alarm feedback with key: {}", feedback.getAlarmKey());
return new ProducerRecord<>(alarmFeedbackTopic, feedback.getAlarmKey().getBytes(encoding),
protobufMapper.toAlarmFeedback(feedback).build().toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm feedback was forwarded
// Let other threads know when we've successfully forwarded an alarm feedback
forwardedAlarmFeedback.countDown();
}));
}
public boolean isForwardingAlarms() {
return forwardAlarms;
}
public CountDownLatch getEventForwardedLatch() {
return forwardedEvent;
}
public CountDownLatch getAlarmForwardedLatch() {
return forwardedAlarm;
}
public CountDownLatch getNodeForwardedLatch() {
return forwardedNode;
}
public CountDownLatch getAlarmFeedbackForwardedLatch() {
return forwardedAlarmFeedback;
}
public void setSuppressIncrementalAlarms(boolean suppressIncrementalAlarms) {
this.suppressIncrementalAlarms = suppressIncrementalAlarms;
}
@VisibleForTesting
KafkaAlarmDataSync getDataSync() {
return dataSync;
}
public AlarmCallbackStateTracker getAlarmCallbackStateTracker() {
return stateTracker;
}
public void setKafkaSendQueueCapacity(int kafkaSendQueueCapacity) {
this.kafkaSendQueueCapacity = kafkaSendQueueCapacity;
}
@Override
public int getNumThreads() {
return numEventListenerThreads;
}
private static final class KafkaRecord {
private final ProducerRecord<byte[], byte[]> producerRecord;
private final Consumer<RecordMetadata> consumer;
KafkaRecord(ProducerRecord<byte[], byte[]> producerRecord, Consumer<RecordMetadata> consumer) {
this.producerRecord = producerRecord;
this.consumer = consumer;
}
ProducerRecord<byte[], byte[]> getProducerRecord() {
return producerRecord;
}
Consumer<RecordMetadata> getConsumer() {
return consumer;
}
}
public CountDownLatch getForwardedTopologyVertexMessage() {
return forwardedTopologyVertexMessage;
}
public CountDownLatch getForwardedTopologyEdgeMessage() {
return forwardedTopologyEdgeMessage;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public int getNumEventListenerThreads() {
return numEventListenerThreads;
}
public void setNumEventListenerThreads(int numEventListenerThreads) {
this.numEventListenerThreads = numEventListenerThreads;
}
private class TopologyVisitorImpl implements TopologyVisitor {
final OnmsTopologyMessage onmsTopologyMessage;
TopologyVisitorImpl(OnmsTopologyMessage onmsTopologyMessage) {
this.onmsTopologyMessage = Objects.requireNonNull(onmsTopologyMessage);
}
byte[] getKeyForEdge(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
return String.format("topology:%s:%s", onmsTopologyMessage.getProtocol().getId(), edge.getId()).getBytes();
}
}
private class DeletingVisitor extends TopologyVisitorImpl {
DeletingVisitor(OnmsTopologyMessage topologyMessage) {
super(topologyMessage);
}
@Override
public void visit(OnmsTopologyEdge edge) {
forwardTopologyEdgeMessage(getKeyForEdge(edge), null);
}
}
private class UpdatingVisitor extends TopologyVisitorImpl {
UpdatingVisitor(OnmsTopologyMessage onmsTopologyMessage) {
super(onmsTopologyMessage);
}
@Override
public void visit(OnmsTopologyVertex vertex) {
// Node handling
if (forwardNodes && vertex.getNodeid() != null) {
updateNodeAsynchronously(vertex.getNodeid());
}
}
@Override
public void visit(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
final OpennmsModelProtos.TopologyEdge mappedTopoMsg =
protobufMapper.toEdgeTopologyMessage(onmsTopologyMessage.getProtocol(), edge);
forwardTopologyEdgeMessage(getKeyForEdge(edge), mappedTopoMsg.toByteArray());
}
}
}
| jeffgdotorg/opennms | features/kafka/producer/src/main/java/org/opennms/features/kafka/producer/OpennmsKafkaProducer.java | Java | gpl-2.0 | 28,520 |
/**
* The routes worker process
*
* This worker process gets the app routes by running the application dynamically
* on the server, then stores the publicly exposed routes in an intermediate format
* (just the url paths) in Redis.
* From there, the paths are used by the live app for serving /sitemap.xml and /robots.txt requests.
* The paths are also used by downstream worker processes (snapshots) to produce the site's html snapshots
* for _escaped_fragment_ requests.
*
* Run this worker anytime the app menu has changed and needs to be refreshed.
*
* PATH and NODE_ENV have to set in the environment before running this.
* PATH has to include phantomjs bin
*/
var phantom = require("node-phantom");
var urlm = require("url");
var redis = require("../../../helpers/redis");
var configLib = require("../../../config");
var config = configLib.create();
// Write the appRoutes to Redis
function writeAppRoutes(appRoutes) {
// remove pattern routes, and prepend /
appRoutes = appRoutes.filter(function(appRoute) {
return !/[*\(\:]/.test(appRoute);
}).map(function(appRoute) {
return "/"+appRoute;
});
if (appRoutes.length > 0) {
var redisClient = redis.client();
redisClient.set(config.keys.routes, appRoutes, function(err) {
if (err) {
console.error("failed to store the routes for "+config.keys.routes);
} else {
console.log("successfully stored "+appRoutes.length+" routes in "+config.keys.routes);
}
redisClient.quit();
});
} else {
console.error("no routes found for "+config.app.hostname);
}
}
// Start up phantom, wait for the page, get the appRoutes
function routes(urlPath, timeout) {
var url = urlm.format({
protocol: "http",
hostname: config.app.hostname,
port: config.app.port || 80,
pathname: urlPath
});
phantom.create(function(err, ph) {
return ph.createPage(function(err, page) {
return page.open(url, function(err, status) {
if (status !== "success") {
console.error("Unable to load page " + url);
ph.exit();
} else {
setTimeout(function() {
return page.evaluate(function() {
return window.wpspa.appRoutes;
}, function(err, result) {
if (err) {
console.error("failed to get appRoutes");
} else {
writeAppRoutes(Object.keys(result));
}
ph.exit();
});
}, timeout);
}
});
});
});
}
module.exports = {
routes: routes
}; | localnerve/wpspa | server/workers/routes/lib/index.js | JavaScript | gpl-2.0 | 2,589 |
#region Using directives
using System;
using System.Collections;
using System.Data;
using UFSoft.UBF.UI.MD.Runtime;
using UFSoft.UBF.UI.MD.Runtime.Implement;
#endregion
namespace DocumentTypeRef
{ public partial class DocumentTypeRefModel
{
//初始化UIMODEL之后的方法
public override void AfterInitModel()
{
//this.Views[0].Fields[0].DefaultValue = thsi.co
}
//UIModel提交保存之前的校验操作.
public override void OnValidate()
{
base.OnValidate() ;
OnValidate_DefualtImpl();
//your coustom code ...
}
}
} | amazingbow/yonyou | 金龙/XMJL_Code/XMJLUI/Model/DocumentTypeRefModelExtend.cs | C# | gpl-2.0 | 650 |
<?php
//------------------------------------------------------------------------------------------------------------------
// SKY HIGH CMS - Sky High Software Custom Content Management System - http://www.skyhighsoftware.com
// Copyright (C) 2008 - 2010 Sky High Software. All Rights Reserved.
// Permission to use and modify this software is for a single website installation as per written agreement.
//
// DO NOT DISTRIBUTE OR COPY this software to any additional purpose, websites, or hosting. If the original website
// is move to new hosting, this software may also be moved to new location.
//
// IN NO EVENT SHALL SKY HIGH SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, OR INCIDENTAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING FROM USE OF THIS SOFTWARE.
//
// THIS SOFTWARE IS PROVIDED "AS IS". SKY HIGH SOFTWARE HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
// ENHANCEMENTS, OR MODIFICATIONS BEYOND THAT SPECIFICALLY AGREED TO IN SEPARATE WRITTEN AGREEMENT.
//------------------------------------------------------------------------------------------------------------------
?>
<tr><td colspan="3" height="20" class="pageEditBars"> SERVICES</td></tr>
<tr>
<td valign="top" ><div align="right">Service</div></td>
<td colspan="2"><input name="sub_title" type="text" id="sub_title" size="50" maxlength="100" value="<?php echo $sub_title; ?>"/></td>
</tr>
<tr>
<td valign="top" ><div align="right">Pricing</div></td>
<td colspan="2">
<?php
$oFCKeditor = new FCKeditor('other') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other;
$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 70;
$oFCKeditor->Create() ;
?>
</td>
</tr>
<tr>
<td valign="top" ><div align="right">Related Services</div></td>
<td colspan="2"><?php
$oFCKeditor = new FCKeditor('other2') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other2;
//$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 240;
$oFCKeditor->Create() ;
?></td>
</tr>
<tr>
<td valign="top" ><div align="right">Quote</div></td>
<td colspan="2">
<?php
$oFCKeditor = new FCKeditor('other5') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other5;
$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 140;
$oFCKeditor->Create() ;
?>
</td>
</tr>
<?php include("page_edit_image_inc.php"); ?> | Since84/AGD-Site | paymentportal/admin/page_edit_91.php | PHP | gpl-2.0 | 2,602 |
<?php
/**
* The template for displaying Comments.
*
* The area of the page that contains both current comments
* and the comment form. The actual display of comments is
* handled by a callback to hoshin_comment which is
* located in the functions.php file.
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/
?>
<div id="comments" class="comments">
<?php if ( post_password_required() ) : ?>
<p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'hoshin' ); ?></p>
</div><!-- #comments -->
<?php
/* Stop the rest of comments.php from being processed,
* but don't kill the script entirely -- we still have
* to fully load the template.
*/
return;
endif;
?>
<?php
// You can start editing here -- including this comment!
?>
<?php if ( have_comments() ) : ?>
<h3 class="comments-title"><?php
printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'hoshin' ),
number_format_i18n( get_comments_number() ), '<em>' . get_the_title() . '</em>' );
?></h3>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
<div class="navigation">
<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'hoshin' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'hoshin' ) ); ?></div>
</div> <!-- .navigation -->
<?php endif; // check for comment navigation ?>
<ol class="commentlist">
<?php
/* Loop through and list the comments. Tell wp_list_comments()
* to use hoshin_comment() to format the comments.
* If you want to overload this in a child theme then you can
* define hoshin_comment() and that will be used instead.
* See hoshin_comment() in hoshin/functions.php for more.
*/
wp_list_comments( array( 'callback' => 'hoshin_comment' ) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
<div class="navigation">
<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'hoshin' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'hoshin' ) ); ?></div>
</div><!-- .navigation -->
<?php endif; // check for comment navigation ?>
<?php else : // or, if we don't have comments:
/* If there are no comments and comments are closed,
* let's leave a little note, shall we?
*/
if ( ! comments_open() ) :
?>
<p class="nocomments"><?php _e( 'Comments are closed.', 'hoshin' ); ?></p>
<?php endif; // end ! comments_open() ?>
<?php endif; // end have_comments() ?>
<?php comment_form(); ?>
</div><!-- #comments -->
| artzstudio/hoshinbudo.com | wp-content/themes/hoshin/comments.php | PHP | gpl-2.0 | 3,028 |
jQuery('#bootstrapslider').carousel({
interval: bootstrapslider_script_vars.interval,
pause: bootstrapslider_script_vars.pause,
wrap: bootstrapslider_script_vars.wrap
});
| bassjobsen/twitter-bootstrap-slider | js/bootstrapslider.js | JavaScript | gpl-2.0 | 177 |
/******************************************************************************
*
* Copyright (C) 1997-2013 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
#include <stdlib.h>
#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qintdict.h>
#include "xmlgen.h"
#include "doxygen.h"
#include "message.h"
#include "config.h"
#include "classlist.h"
#include "util.h"
#include "defargs.h"
#include "outputgen.h"
#include "dot.h"
#include "pagedef.h"
#include "filename.h"
#include "version.h"
#include "xmldocvisitor.h"
#include "docparser.h"
#include "language.h"
#include "parserintf.h"
#include "arguments.h"
#include "memberlist.h"
#include "groupdef.h"
#include "memberdef.h"
#include "namespacedef.h"
#include "membername.h"
#include "membergroup.h"
#include "dirdef.h"
#include "section.h"
// no debug info
#define XML_DB(x) do {} while(0)
// debug to stdout
//#define XML_DB(x) printf x
// debug inside output
//#define XML_DB(x) QCString __t;__t.sprintf x;m_t << __t
//------------------
static const char index_xsd[] =
#include "index_xsd.h"
;
//------------------
//
static const char compound_xsd[] =
#include "compound_xsd.h"
;
//------------------
/** Helper class mapping MemberList::ListType to a string representing */
class XmlSectionMapper : public QIntDict<char>
{
public:
XmlSectionMapper() : QIntDict<char>(47)
{
insert(MemberListType_pubTypes,"public-type");
insert(MemberListType_pubMethods,"public-func");
insert(MemberListType_pubAttribs,"public-attrib");
insert(MemberListType_pubSlots,"public-slot");
insert(MemberListType_signals,"signal");
insert(MemberListType_dcopMethods,"dcop-func");
insert(MemberListType_properties,"property");
insert(MemberListType_events,"event");
insert(MemberListType_pubStaticMethods,"public-static-func");
insert(MemberListType_pubStaticAttribs,"public-static-attrib");
insert(MemberListType_proTypes,"protected-type");
insert(MemberListType_proMethods,"protected-func");
insert(MemberListType_proAttribs,"protected-attrib");
insert(MemberListType_proSlots,"protected-slot");
insert(MemberListType_proStaticMethods,"protected-static-func");
insert(MemberListType_proStaticAttribs,"protected-static-attrib");
insert(MemberListType_pacTypes,"package-type");
insert(MemberListType_pacMethods,"package-func");
insert(MemberListType_pacAttribs,"package-attrib");
insert(MemberListType_pacStaticMethods,"package-static-func");
insert(MemberListType_pacStaticAttribs,"package-static-attrib");
insert(MemberListType_priTypes,"private-type");
insert(MemberListType_priMethods,"private-func");
insert(MemberListType_priAttribs,"private-attrib");
insert(MemberListType_priSlots,"private-slot");
insert(MemberListType_priStaticMethods,"private-static-func");
insert(MemberListType_priStaticAttribs,"private-static-attrib");
insert(MemberListType_friends,"friend");
insert(MemberListType_related,"related");
insert(MemberListType_decDefineMembers,"define");
insert(MemberListType_decProtoMembers,"prototype");
insert(MemberListType_decTypedefMembers,"typedef");
insert(MemberListType_decEnumMembers,"enum");
insert(MemberListType_decFuncMembers,"func");
insert(MemberListType_decVarMembers,"var");
}
};
static XmlSectionMapper g_xmlSectionMapper;
inline void writeXMLString(FTextStream &t,const char *s)
{
t << convertToXML(s);
}
inline void writeXMLCodeString(FTextStream &t,const char *s, int &col)
{
char c;
while ((c=*s++))
{
switch(c)
{
case '\t':
{
static int tabSize = Config_getInt("TAB_SIZE");
int spacesToNextTabStop = tabSize - (col%tabSize);
col+=spacesToNextTabStop;
while (spacesToNextTabStop--) t << "<sp/>";
break;
}
case ' ': t << "<sp/>"; col++; break;
case '<': t << "<"; col++; break;
case '>': t << ">"; col++; break;
case '&': t << "&"; col++; break;
case '\'': t << "'"; col++; break;
case '"': t << """; col++; break;
default: t << c; col++; break;
}
}
}
static void writeXMLHeader(FTextStream &t)
{
t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;;
t << "<doxygen xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
t << "xsi:noNamespaceSchemaLocation=\"compound.xsd\" ";
t << "version=\"" << versionString << "\">" << endl;
}
static void writeCombineScript()
{
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/combine.xslt";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
t <<
"<!-- XSLT script to combine the generated output into a single file. \n"
" If you have xsltproc you could use:\n"
" xsltproc combine.xslt index.xml >all.xml\n"
"-->\n"
"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n"
" <xsl:output method=\"xml\" version=\"1.0\" indent=\"no\" standalone=\"yes\" />\n"
" <xsl:template match=\"/\">\n"
" <doxygen version=\"{doxygenindex/@version}\">\n"
" <!-- Load all doxgen generated xml files -->\n"
" <xsl:for-each select=\"doxygenindex/compound\">\n"
" <xsl:copy-of select=\"document( concat( @refid, '.xml' ) )/doxygen/*\" />\n"
" </xsl:for-each>\n"
" </doxygen>\n"
" </xsl:template>\n"
"</xsl:stylesheet>\n";
}
void writeXMLLink(FTextStream &t,const char *extRef,const char *compoundId,
const char *anchorId,const char *text,const char *tooltip)
{
t << "<ref refid=\"" << compoundId;
if (anchorId) t << "_1" << anchorId;
t << "\" kindref=\"";
if (anchorId) t << "member"; else t << "compound";
t << "\"";
if (extRef) t << " external=\"" << extRef << "\"";
if (tooltip) t << " tooltip=\"" << convertToXML(tooltip) << "\"";
t << ">";
writeXMLString(t,text);
t << "</ref>";
}
/** Implements TextGeneratorIntf for an XML stream. */
class TextGeneratorXMLImpl : public TextGeneratorIntf
{
public:
TextGeneratorXMLImpl(FTextStream &t): m_t(t) {}
void writeString(const char *s,bool /*keepSpaces*/) const
{
writeXMLString(m_t,s);
}
void writeBreak(int) const {}
void writeLink(const char *extRef,const char *file,
const char *anchor,const char *text
) const
{
writeXMLLink(m_t,extRef,file,anchor,text,0);
}
private:
FTextStream &m_t;
};
/** Helper class representing a stack of objects stored by value */
template<class T> class ValStack
{
public:
ValStack() : m_values(10), m_sp(0), m_size(10) {}
virtual ~ValStack() {}
ValStack(const ValStack<T> &s)
{
m_values=s.m_values.copy();
m_sp=s.m_sp;
m_size=s.m_size;
}
ValStack &operator=(const ValStack<T> &s)
{
m_values=s.m_values.copy();
m_sp=s.m_sp;
m_size=s.m_size;
return *this;
}
void push(T v)
{
m_sp++;
if (m_sp>=m_size)
{
m_size+=10;
m_values.resize(m_size);
}
m_values[m_sp]=v;
}
T pop()
{
ASSERT(m_sp!=0);
return m_values[m_sp--];
}
T& top()
{
ASSERT(m_sp!=0);
return m_values[m_sp];
}
bool isEmpty()
{
return m_sp==0;
}
uint count() const
{
return m_sp;
}
private:
QArray<T> m_values;
int m_sp;
int m_size;
};
/** Generator for producing XML formatted source code. */
class XMLCodeGenerator : public CodeOutputInterface
{
public:
XMLCodeGenerator(FTextStream &t) : m_t(t), m_lineNumber(-1),
m_insideCodeLine(FALSE), m_normalHLNeedStartTag(TRUE),
m_insideSpecialHL(FALSE) {}
virtual ~XMLCodeGenerator() { }
void codify(const char *text)
{
XML_DB(("(codify \"%s\")\n",text));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
writeXMLCodeString(m_t,text,col);
}
void writeCodeLink(const char *ref,const char *file,
const char *anchor,const char *name,
const char *tooltip)
{
XML_DB(("(writeCodeLink)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
writeXMLLink(m_t,ref,file,anchor,name,tooltip);
col+=qstrlen(name);
}
void startCodeLine(bool)
{
XML_DB(("(startCodeLine)\n"));
m_t << "<codeline";
if (m_lineNumber!=-1)
{
m_t << " lineno=\"" << m_lineNumber << "\"";
if (!m_refId.isEmpty())
{
m_t << " refid=\"" << m_refId << "\"";
if (m_isMemberRef)
{
m_t << " refkind=\"member\"";
}
else
{
m_t << " refkind=\"compound\"";
}
}
if (!m_external.isEmpty())
{
m_t << " external=\"" << m_external << "\"";
}
}
m_t << ">";
m_insideCodeLine=TRUE;
col=0;
}
void endCodeLine()
{
XML_DB(("(endCodeLine)\n"));
if (!m_insideSpecialHL && !m_normalHLNeedStartTag)
{
m_t << "</highlight>";
m_normalHLNeedStartTag=TRUE;
}
m_t << "</codeline>" << endl; // non DocBook
m_lineNumber = -1;
m_refId.resize(0);
m_external.resize(0);
m_insideCodeLine=FALSE;
}
void startCodeAnchor(const char *id)
{
XML_DB(("(startCodeAnchor)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
m_t << "<anchor id=\"" << id << "\">";
}
void endCodeAnchor()
{
XML_DB(("(endCodeAnchor)\n"));
m_t << "</anchor>";
}
void startFontClass(const char *colorClass)
{
XML_DB(("(startFontClass)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && !m_normalHLNeedStartTag)
{
m_t << "</highlight>";
m_normalHLNeedStartTag=TRUE;
}
m_t << "<highlight class=\"" << colorClass << "\">"; // non DocBook
m_insideSpecialHL=TRUE;
}
void endFontClass()
{
XML_DB(("(endFontClass)\n"));
m_t << "</highlight>"; // non DocBook
m_insideSpecialHL=FALSE;
}
void writeCodeAnchor(const char *)
{
XML_DB(("(writeCodeAnchor)\n"));
}
void writeLineNumber(const char *extRef,const char *compId,
const char *anchorId,int l)
{
XML_DB(("(writeLineNumber)\n"));
// we remember the information provided here to use it
// at the <codeline> start tag.
m_lineNumber = l;
if (compId)
{
m_refId=compId;
if (anchorId) m_refId+=(QCString)"_1"+anchorId;
m_isMemberRef = anchorId!=0;
if (extRef) m_external=extRef;
}
}
void linkableSymbol(int, const char *,Definition *,Definition *)
{
}
void setCurrentDoc(Definition *,const char *,bool)
{
}
void addWord(const char *,bool)
{
}
void finish()
{
if (m_insideCodeLine) endCodeLine();
}
private:
FTextStream &m_t;
QCString m_refId;
QCString m_external;
int m_lineNumber;
bool m_isMemberRef;
int col;
bool m_insideCodeLine;
bool m_normalHLNeedStartTag;
bool m_insideSpecialHL;
};
static void writeTemplateArgumentList(ArgumentList *al,
FTextStream &t,
Definition *scope,
FileDef *fileScope,
int indent)
{
QCString indentStr;
indentStr.fill(' ',indent);
if (al)
{
t << indentStr << "<templateparamlist>" << endl;
ArgumentListIterator ali(*al);
Argument *a;
for (ali.toFirst();(a=ali.current());++ali)
{
t << indentStr << " <param>" << endl;
if (!a->type.isEmpty())
{
t << indentStr << " <type>";
linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->type);
t << "</type>" << endl;
}
if (!a->name.isEmpty())
{
t << indentStr << " <declname>" << a->name << "</declname>" << endl;
t << indentStr << " <defname>" << a->name << "</defname>" << endl;
}
if (!a->defval.isEmpty())
{
t << indentStr << " <defval>";
linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->defval);
t << "</defval>" << endl;
}
t << indentStr << " </param>" << endl;
}
t << indentStr << "</templateparamlist>" << endl;
}
}
static void writeMemberTemplateLists(MemberDef *md,FTextStream &t)
{
LockingPtr<ArgumentList> templMd = md->templateArguments();
if (templMd!=0) // function template prefix
{
writeTemplateArgumentList(templMd.pointer(),t,md->getClassDef(),md->getFileDef(),8);
}
}
static void writeTemplateList(ClassDef *cd,FTextStream &t)
{
writeTemplateArgumentList(cd->templateArguments(),t,cd,0,4);
}
static void writeXMLDocBlock(FTextStream &t,
const QCString &fileName,
int lineNr,
Definition *scope,
MemberDef * md,
const QCString &text)
{
QCString stext = text.stripWhiteSpace();
if (stext.isEmpty()) return;
// convert the documentation string into an abstract syntax tree
DocNode *root = validatingParseDoc(fileName,lineNr,scope,md,text+"\n",FALSE,FALSE);
// create a code generator
XMLCodeGenerator *xmlCodeGen = new XMLCodeGenerator(t);
// create a parse tree visitor for XML
XmlDocVisitor *visitor = new XmlDocVisitor(t,*xmlCodeGen);
// visit all nodes
root->accept(visitor);
// clean up
delete visitor;
delete xmlCodeGen;
delete root;
}
void writeXMLCodeBlock(FTextStream &t,FileDef *fd)
{
ParserInterface *pIntf=Doxygen::parserManager->getParser(fd->getDefFileExtension());
pIntf->resetCodeParserState();
XMLCodeGenerator *xmlGen = new XMLCodeGenerator(t);
pIntf->parseCode(*xmlGen, // codeOutIntf
0, // scopeName
fileToString(fd->absFilePath(),Config_getBool("FILTER_SOURCE_FILES")),
FALSE, // isExampleBlock
0, // exampleName
fd, // fileDef
-1, // startLine
-1, // endLine
FALSE, // inlineFragement
0, // memberDef
TRUE // showLineNumbers
);
xmlGen->finish();
delete xmlGen;
}
static void writeMemberReference(FTextStream &t,Definition *def,MemberDef *rmd,const char *tagName)
{
QCString scope = rmd->getScopeString();
QCString name = rmd->name();
if (!scope.isEmpty() && scope!=def->name())
{
name.prepend(scope+getLanguageSpecificSeparator(rmd->getLanguage()));
}
t << " <" << tagName << " refid=\"";
t << rmd->getOutputFileBase() << "_1" << rmd->anchor() << "\"";
if (rmd->getStartBodyLine()!=-1 && rmd->getBodyDef())
{
t << " compoundref=\"" << rmd->getBodyDef()->getOutputFileBase() << "\"";
t << " startline=\"" << rmd->getStartBodyLine() << "\"";
if (rmd->getEndBodyLine()!=-1)
{
t << " endline=\"" << rmd->getEndBodyLine() << "\"";
}
}
t << ">" << convertToXML(name) << "</" << tagName << ">" << endl;
}
static void stripQualifiers(QCString &typeStr)
{
bool done=FALSE;
while (!done)
{
if (typeStr.stripPrefix("static "));
else if (typeStr.stripPrefix("virtual "));
else if (typeStr.stripPrefix("volatile "));
else if (typeStr=="virtual") typeStr="";
else done=TRUE;
}
}
static QCString classOutputFileBase(ClassDef *cd)
{
//static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES");
//if (inlineGroupedClasses && cd->partOfGroups()!=0)
return cd->getOutputFileBase();
//else
// return cd->getOutputFileBase();
}
static QCString memberOutputFileBase(MemberDef *md)
{
//static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES");
//if (inlineGroupedClasses && md->getClassDef() && md->getClassDef()->partOfGroups()!=0)
// return md->getClassDef()->getXmlOutputFileBase();
//else
// return md->getOutputFileBase();
return md->getOutputFileBase();
}
static void generateXMLForMember(MemberDef *md,FTextStream &ti,FTextStream &t,Definition *def)
{
// + declaration/definition arg lists
// + reimplements
// + reimplementedBy
// + exceptions
// + const/volatile specifiers
// - examples
// + source definition
// + source references
// + source referenced by
// - body code
// + template arguments
// (templateArguments(), definitionTemplateParameterLists())
// - call graph
// enum values are written as part of the enum
if (md->memberType()==MemberType_EnumValue) return;
if (md->isHidden()) return;
//if (md->name().at(0)=='@') return; // anonymous member
// group members are only visible in their group
//if (def->definitionType()!=Definition::TypeGroup && md->getGroupDef()) return;
QCString memType;
bool isFunc=FALSE;
switch (md->memberType())
{
case MemberType_Define: memType="define"; break;
case MemberType_EnumValue: ASSERT(0); break;
case MemberType_Property: memType="property"; break;
case MemberType_Event: memType="event"; break;
case MemberType_Variable: memType="variable"; break;
case MemberType_Typedef: memType="typedef"; break;
case MemberType_Enumeration: memType="enum"; break;
case MemberType_Function: memType="function"; isFunc=TRUE; break;
case MemberType_Signal: memType="signal"; isFunc=TRUE; break;
case MemberType_Friend: memType="friend"; isFunc=TRUE; break;
case MemberType_DCOP: memType="dcop"; isFunc=TRUE; break;
case MemberType_Slot: memType="slot"; isFunc=TRUE; break;
}
ti << " <member refid=\"" << memberOutputFileBase(md)
<< "_1" << md->anchor() << "\" kind=\"" << memType << "\"><name>"
<< convertToXML(md->name()) << "</name></member>" << endl;
QCString scopeName;
if (md->getClassDef())
scopeName=md->getClassDef()->name();
else if (md->getNamespaceDef())
scopeName=md->getNamespaceDef()->name();
t << " <memberdef kind=\"";
//enum { define_t,variable_t,typedef_t,enum_t,function_t } xmlType = function_t;
t << memType << "\" id=\"";
if (md->getGroupDef() && def->definitionType()==Definition::TypeGroup)
{
t << md->getGroupDef()->getOutputFileBase();
}
else
{
t << memberOutputFileBase(md);
}
t << "_1" // encoded `:' character (see util.cpp:convertNameToFile)
<< md->anchor();
t << "\" prot=\"";
switch(md->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\"";
t << " static=\"";
if (md->isStatic()) t << "yes"; else t << "no";
t << "\"";
if (isFunc)
{
LockingPtr<ArgumentList> al = md->argumentList();
t << " const=\"";
if (al!=0 && al->constSpecifier) t << "yes"; else t << "no";
t << "\"";
t << " explicit=\"";
if (md->isExplicit()) t << "yes"; else t << "no";
t << "\"";
t << " inline=\"";
if (md->isInline()) t << "yes"; else t << "no";
t << "\"";
if (md->isFinal())
{
t << " final=\"yes\"";
}
if (md->isSealed())
{
t << " sealed=\"yes\"";
}
if (md->isNew())
{
t << " new=\"yes\"";
}
if (md->isOptional())
{
t << " optional=\"yes\"";
}
if (md->isRequired())
{
t << " required=\"yes\"";
}
t << " virt=\"";
switch (md->virtualness())
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
default: ASSERT(0);
}
t << "\"";
}
if (md->memberType() == MemberType_Variable)
{
//ArgumentList *al = md->argumentList();
//t << " volatile=\"";
//if (al && al->volatileSpecifier) t << "yes"; else t << "no";
t << " mutable=\"";
if (md->isMutable()) t << "yes"; else t << "no";
t << "\"";
if (md->isInitonly())
{
t << " initonly=\"yes\"";
}
}
else if (md->memberType() == MemberType_Property)
{
t << " readable=\"";
if (md->isReadable()) t << "yes"; else t << "no";
t << "\"";
t << " writable=\"";
if (md->isWritable()) t << "yes"; else t << "no";
t << "\"";
t << " gettable=\"";
if (md->isGettable()) t << "yes"; else t << "no";
t << "\"";
t << " settable=\"";
if (md->isSettable()) t << "yes"; else t << "no";
t << "\"";
if (md->isAssign() || md->isCopy() || md->isRetain() || md->isStrong() || md->isWeak())
{
t << " accessor=\"";
if (md->isAssign()) t << "assign";
else if (md->isCopy()) t << "copy";
else if (md->isRetain()) t << "retain";
else if (md->isStrong()) t << "strong";
else if (md->isWeak()) t << "weak";
t << "\"";
}
}
else if (md->memberType() == MemberType_Event)
{
t << " add=\"";
if (md->isAddable()) t << "yes"; else t << "no";
t << "\"";
t << " remove=\"";
if (md->isRemovable()) t << "yes"; else t << "no";
t << "\"";
t << " raise=\"";
if (md->isRaisable()) t << "yes"; else t << "no";
t << "\"";
}
t << ">" << endl;
if (md->memberType()!=MemberType_Define &&
md->memberType()!=MemberType_Enumeration
)
{
if (md->memberType()!=MemberType_Typedef)
{
writeMemberTemplateLists(md,t);
}
QCString typeStr = md->typeString(); //replaceAnonymousScopes(md->typeString());
stripQualifiers(typeStr);
t << " <type>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,typeStr);
t << "</type>" << endl;
t << " <definition>" << convertToXML(md->definition()) << "</definition>" << endl;
t << " <argsstring>" << convertToXML(md->argsString()) << "</argsstring>" << endl;
}
t << " <name>" << convertToXML(md->name()) << "</name>" << endl;
if (md->memberType() == MemberType_Property)
{
if (md->isReadable())
t << " <read>" << convertToXML(md->getReadAccessor()) << "</read>" << endl;
if (md->isWritable())
t << " <write>" << convertToXML(md->getWriteAccessor()) << "</write>" << endl;
}
if (md->memberType()==MemberType_Variable && md->bitfieldString())
{
QCString bitfield = md->bitfieldString();
if (bitfield.at(0)==':') bitfield=bitfield.mid(1);
t << " <bitfield>" << bitfield << "</bitfield>" << endl;
}
MemberDef *rmd = md->reimplements();
if (rmd)
{
t << " <reimplements refid=\""
<< memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">"
<< convertToXML(rmd->name()) << "</reimplements>" << endl;
}
LockingPtr<MemberList> rbml = md->reimplementedBy();
if (rbml!=0)
{
MemberListIterator mli(*rbml);
for (mli.toFirst();(rmd=mli.current());++mli)
{
t << " <reimplementedby refid=\""
<< memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">"
<< convertToXML(rmd->name()) << "</reimplementedby>" << endl;
}
}
if (isFunc) //function
{
LockingPtr<ArgumentList> declAl = md->declArgumentList();
LockingPtr<ArgumentList> defAl = md->argumentList();
if (declAl!=0 && declAl->count()>0)
{
ArgumentListIterator declAli(*declAl);
ArgumentListIterator defAli(*defAl);
Argument *a;
for (declAli.toFirst();(a=declAli.current());++declAli)
{
Argument *defArg = defAli.current();
t << " <param>" << endl;
if (!a->attrib.isEmpty())
{
t << " <attributes>";
writeXMLString(t,a->attrib);
t << "</attributes>" << endl;
}
if (!a->type.isEmpty())
{
t << " <type>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->type);
t << "</type>" << endl;
}
if (!a->name.isEmpty())
{
t << " <declname>";
writeXMLString(t,a->name);
t << "</declname>" << endl;
}
if (defArg && !defArg->name.isEmpty() && defArg->name!=a->name)
{
t << " <defname>";
writeXMLString(t,defArg->name);
t << "</defname>" << endl;
}
if (!a->array.isEmpty())
{
t << " <array>";
writeXMLString(t,a->array);
t << "</array>" << endl;
}
if (!a->defval.isEmpty())
{
t << " <defval>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->defval);
t << "</defval>" << endl;
}
if (defArg && defArg->hasDocumentation())
{
t << " <briefdescription>";
writeXMLDocBlock(t,md->getDefFileName(),md->getDefLine(),
md->getOuterScope(),md,defArg->docs);
t << "</briefdescription>" << endl;
}
t << " </param>" << endl;
if (defArg) ++defAli;
}
}
}
else if (md->memberType()==MemberType_Define &&
md->argsString()) // define
{
if (md->argumentList()->count()==0) // special case for "foo()" to
// disguish it from "foo".
{
t << " <param></param>" << endl;
}
else
{
ArgumentListIterator ali(*md->argumentList());
Argument *a;
for (ali.toFirst();(a=ali.current());++ali)
{
t << " <param><defname>" << a->type << "</defname></param>" << endl;
}
}
}
// avoid that extremely large tables are written to the output.
// todo: it's better to adhere to MAX_INITIALIZER_LINES.
if (!md->initializer().isEmpty() && md->initializer().length()<2000)
{
t << " <initializer>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->initializer());
t << "</initializer>" << endl;
}
if (md->excpString())
{
t << " <exceptions>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->excpString());
t << "</exceptions>" << endl;
}
if (md->memberType()==MemberType_Enumeration) // enum
{
LockingPtr<MemberList> enumFields = md->enumFieldList();
if (enumFields!=0)
{
MemberListIterator emli(*enumFields);
MemberDef *emd;
for (emli.toFirst();(emd=emli.current());++emli)
{
ti << " <member refid=\"" << memberOutputFileBase(emd)
<< "_1" << emd->anchor() << "\" kind=\"enumvalue\"><name>"
<< convertToXML(emd->name()) << "</name></member>" << endl;
t << " <enumvalue id=\"" << memberOutputFileBase(emd) << "_1"
<< emd->anchor() << "\" prot=\"";
switch (emd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\">" << endl;
t << " <name>";
writeXMLString(t,emd->name());
t << "</name>" << endl;
if (!emd->initializer().isEmpty())
{
t << " <initializer>";
writeXMLString(t,emd->initializer());
t << "</initializer>" << endl;
}
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,emd->briefFile(),emd->briefLine(),emd->getOuterScope(),emd,emd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,emd->docFile(),emd->docLine(),emd->getOuterScope(),emd,emd->documentation());
t << " </detaileddescription>" << endl;
t << " </enumvalue>" << endl;
}
}
}
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,md->briefFile(),md->briefLine(),md->getOuterScope(),md,md->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,md->docFile(),md->docLine(),md->getOuterScope(),md,md->documentation());
t << " </detaileddescription>" << endl;
t << " <inbodydescription>" << endl;
writeXMLDocBlock(t,md->docFile(),md->inbodyLine(),md->getOuterScope(),md,md->inbodyDocumentation());
t << " </inbodydescription>" << endl;
if (md->getDefLine()!=-1)
{
t << " <location file=\""
<< md->getDefFileName() << "\" line=\""
<< md->getDefLine() << "\"";
if (md->getStartBodyLine()!=-1)
{
FileDef *bodyDef = md->getBodyDef();
if (bodyDef)
{
t << " bodyfile=\"" << bodyDef->absFilePath() << "\"";
}
t << " bodystart=\"" << md->getStartBodyLine() << "\" bodyend=\""
<< md->getEndBodyLine() << "\"";
}
t << "/>" << endl;
}
//printf("md->getReferencesMembers()=%p\n",md->getReferencesMembers());
LockingPtr<MemberSDict> mdict = md->getReferencesMembers();
if (mdict!=0)
{
MemberSDict::Iterator mdi(*mdict);
MemberDef *rmd;
for (mdi.toFirst();(rmd=mdi.current());++mdi)
{
writeMemberReference(t,def,rmd,"references");
}
}
mdict = md->getReferencedByMembers();
if (mdict!=0)
{
MemberSDict::Iterator mdi(*mdict);
MemberDef *rmd;
for (mdi.toFirst();(rmd=mdi.current());++mdi)
{
writeMemberReference(t,def,rmd,"referencedby");
}
}
t << " </memberdef>" << endl;
}
static void generateXMLSection(Definition *d,FTextStream &ti,FTextStream &t,
MemberList *ml,const char *kind,const char *header=0,
const char *documentation=0)
{
if (ml==0) return;
MemberListIterator mli(*ml);
MemberDef *md;
int count=0;
for (mli.toFirst();(md=mli.current());++mli)
{
// namespace members are also inserted in the file scope, but
// to prevent this duplication in the XML output, we filter those here.
if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0)
{
count++;
}
}
if (count==0) return; // empty list
t << " <sectiondef kind=\"" << kind << "\">" << endl;
if (header)
{
t << " <header>" << convertToXML(header) << "</header>" << endl;
}
if (documentation)
{
t << " <description>";
writeXMLDocBlock(t,d->docFile(),d->docLine(),d,0,documentation);
t << "</description>" << endl;
}
for (mli.toFirst();(md=mli.current());++mli)
{
// namespace members are also inserted in the file scope, but
// to prevent this duplication in the XML output, we filter those here.
if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0)
{
generateXMLForMember(md,ti,t,d);
}
}
t << " </sectiondef>" << endl;
}
static void writeListOfAllMembers(ClassDef *cd,FTextStream &t)
{
t << " <listofallmembers>" << endl;
if (cd->memberNameInfoSDict())
{
MemberNameInfoSDict::Iterator mnii(*cd->memberNameInfoSDict());
MemberNameInfo *mni;
for (mnii.toFirst();(mni=mnii.current());++mnii)
{
MemberNameInfoIterator mii(*mni);
MemberInfo *mi;
for (mii.toFirst();(mi=mii.current());++mii)
{
MemberDef *md=mi->memberDef;
if (md->name().at(0)!='@') // skip anonymous members
{
Protection prot = mi->prot;
Specifier virt=md->virtualness();
t << " <member refid=\"" << memberOutputFileBase(md) << "_1" <<
md->anchor() << "\" prot=\"";
switch (prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\" virt=\"";
switch(virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
}
t << "\"";
if (!mi->ambiguityResolutionScope.isEmpty())
{
t << " ambiguityscope=\"" << convertToXML(mi->ambiguityResolutionScope) << "\"";
}
t << "><scope>" << convertToXML(cd->name()) << "</scope><name>" <<
convertToXML(md->name()) << "</name></member>" << endl;
}
}
}
}
t << " </listofallmembers>" << endl;
}
static void writeInnerClasses(const ClassSDict *cl,FTextStream &t)
{
if (cl)
{
ClassSDict::Iterator cli(*cl);
ClassDef *cd;
for (cli.toFirst();(cd=cli.current());++cli)
{
if (!cd->isHidden() && cd->name().find('@')==-1) // skip anonymous scopes
{
t << " <innerclass refid=\"" << classOutputFileBase(cd)
<< "\" prot=\"";
switch(cd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\">" << convertToXML(cd->name()) << "</innerclass>" << endl;
}
}
}
}
static void writeInnerNamespaces(const NamespaceSDict *nl,FTextStream &t)
{
if (nl)
{
NamespaceSDict::Iterator nli(*nl);
NamespaceDef *nd;
for (nli.toFirst();(nd=nli.current());++nli)
{
if (!nd->isHidden() && nd->name().find('@')==-1) // skip anonymouse scopes
{
t << " <innernamespace refid=\"" << nd->getOutputFileBase()
<< "\">" << convertToXML(nd->name()) << "</innernamespace>" << endl;
}
}
}
}
static void writeInnerFiles(const FileList *fl,FTextStream &t)
{
if (fl)
{
QListIterator<FileDef> fli(*fl);
FileDef *fd;
for (fli.toFirst();(fd=fli.current());++fli)
{
t << " <innerfile refid=\"" << fd->getOutputFileBase()
<< "\">" << convertToXML(fd->name()) << "</innerfile>" << endl;
}
}
}
static void writeInnerPages(const PageSDict *pl,FTextStream &t)
{
if (pl)
{
PageSDict::Iterator pli(*pl);
PageDef *pd;
for (pli.toFirst();(pd=pli.current());++pli)
{
t << " <innerpage refid=\"" << pd->getOutputFileBase();
if (pd->getGroupDef())
{
t << "_" << pd->name();
}
t << "\">" << convertToXML(pd->title()) << "</innerpage>" << endl;
}
}
}
static void writeInnerGroups(const GroupList *gl,FTextStream &t)
{
if (gl)
{
GroupListIterator gli(*gl);
GroupDef *sgd;
for (gli.toFirst();(sgd=gli.current());++gli)
{
t << " <innergroup refid=\"" << sgd->getOutputFileBase()
<< "\">" << convertToXML(sgd->groupTitle())
<< "</innergroup>" << endl;
}
}
}
static void writeInnerDirs(const DirList *dl,FTextStream &t)
{
if (dl)
{
QListIterator<DirDef> subdirs(*dl);
DirDef *subdir;
for (subdirs.toFirst();(subdir=subdirs.current());++subdirs)
{
t << " <innerdir refid=\"" << subdir->getOutputFileBase()
<< "\">" << convertToXML(subdir->displayName()) << "</innerdir>" << endl;
}
}
}
static void generateXMLForClass(ClassDef *cd,FTextStream &ti)
{
// + brief description
// + detailed description
// + template argument list(s)
// - include file
// + member groups
// + inheritance diagram
// + list of direct super classes
// + list of direct sub classes
// + list of inner classes
// + collaboration diagram
// + list of all members
// + user defined member sections
// + standard member sections
// + detailed member documentation
// - examples using the class
if (cd->isReference()) return; // skip external references.
if (cd->isHidden()) return; // skip hidden classes.
if (cd->name().find('@')!=-1) return; // skip anonymous compounds.
if (cd->templateMaster()!=0) return; // skip generated template instances.
if (cd->isArtificial()) return; // skip artificially created classes
msg("Generating XML output for class %s\n",cd->name().data());
ti << " <compound refid=\"" << classOutputFileBase(cd)
<< "\" kind=\"" << cd->compoundTypeString()
<< "\"><name>" << convertToXML(cd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+ classOutputFileBase(cd)+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< classOutputFileBase(cd) << "\" kind=\""
<< cd->compoundTypeString() << "\" prot=\"";
switch (cd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
if (cd->isFinal()) t << "\" final=\"yes";
if (cd->isSealed()) t << "\" sealed=\"yes";
if (cd->isAbstract()) t << "\" abstract=\"yes";
t << "\">" << endl;
t << " <compoundname>";
writeXMLString(t,cd->name());
t << "</compoundname>" << endl;
if (cd->baseClasses())
{
BaseClassListIterator bcli(*cd->baseClasses());
BaseClassDef *bcd;
for (bcli.toFirst();(bcd=bcli.current());++bcli)
{
t << " <basecompoundref ";
if (bcd->classDef->isLinkable())
{
t << "refid=\"" << classOutputFileBase(bcd->classDef) << "\" ";
}
t << "prot=\"";
switch (bcd->prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: ASSERT(0); break;
}
t << "\" virt=\"";
switch(bcd->virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t <<"pure-virtual"; break;
}
t << "\">";
if (!bcd->templSpecifiers.isEmpty())
{
t << convertToXML(
insertTemplateSpecifierInScope(
bcd->classDef->name(),bcd->templSpecifiers)
);
}
else
{
t << convertToXML(bcd->classDef->displayName());
}
t << "</basecompoundref>" << endl;
}
}
if (cd->subClasses())
{
BaseClassListIterator bcli(*cd->subClasses());
BaseClassDef *bcd;
for (bcli.toFirst();(bcd=bcli.current());++bcli)
{
t << " <derivedcompoundref refid=\""
<< classOutputFileBase(bcd->classDef)
<< "\" prot=\"";
switch (bcd->prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: ASSERT(0); break;
}
t << "\" virt=\"";
switch(bcd->virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
}
t << "\">" << convertToXML(bcd->classDef->displayName())
<< "</derivedcompoundref>" << endl;
}
}
IncludeInfo *ii=cd->includeInfo();
if (ii)
{
QCString nm = ii->includeName;
if (nm.isEmpty() && ii->fileDef) nm = ii->fileDef->docName();
if (!nm.isEmpty())
{
t << " <includes";
if (ii->fileDef && !ii->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << ii->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (ii->local ? "yes" : "no") << "\">";
t << nm;
t << "</includes>" << endl;
}
}
writeInnerClasses(cd->getClassSDict(),t);
writeTemplateList(cd,t);
if (cd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*cd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(cd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(cd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_detailedLists)==0)
{
generateXMLSection(cd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(cd,ti,t,cd->pubTypes,"public-type");
generateXMLSection(cd,ti,t,cd->pubMethods,"public-func");
generateXMLSection(cd,ti,t,cd->pubAttribs,"public-attrib");
generateXMLSection(cd,ti,t,cd->pubSlots,"public-slot");
generateXMLSection(cd,ti,t,cd->signals,"signal");
generateXMLSection(cd,ti,t,cd->dcopMethods,"dcop-func");
generateXMLSection(cd,ti,t,cd->properties,"property");
generateXMLSection(cd,ti,t,cd->events,"event");
generateXMLSection(cd,ti,t,cd->pubStaticMethods,"public-static-func");
generateXMLSection(cd,ti,t,cd->pubStaticAttribs,"public-static-attrib");
generateXMLSection(cd,ti,t,cd->proTypes,"protected-type");
generateXMLSection(cd,ti,t,cd->proMethods,"protected-func");
generateXMLSection(cd,ti,t,cd->proAttribs,"protected-attrib");
generateXMLSection(cd,ti,t,cd->proSlots,"protected-slot");
generateXMLSection(cd,ti,t,cd->proStaticMethods,"protected-static-func");
generateXMLSection(cd,ti,t,cd->proStaticAttribs,"protected-static-attrib");
generateXMLSection(cd,ti,t,cd->pacTypes,"package-type");
generateXMLSection(cd,ti,t,cd->pacMethods,"package-func");
generateXMLSection(cd,ti,t,cd->pacAttribs,"package-attrib");
generateXMLSection(cd,ti,t,cd->pacStaticMethods,"package-static-func");
generateXMLSection(cd,ti,t,cd->pacStaticAttribs,"package-static-attrib");
generateXMLSection(cd,ti,t,cd->priTypes,"private-type");
generateXMLSection(cd,ti,t,cd->priMethods,"private-func");
generateXMLSection(cd,ti,t,cd->priAttribs,"private-attrib");
generateXMLSection(cd,ti,t,cd->priSlots,"private-slot");
generateXMLSection(cd,ti,t,cd->priStaticMethods,"private-static-func");
generateXMLSection(cd,ti,t,cd->priStaticAttribs,"private-static-attrib");
generateXMLSection(cd,ti,t,cd->friends,"friend");
generateXMLSection(cd,ti,t,cd->related,"related");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,cd->briefFile(),cd->briefLine(),cd,0,cd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,cd->docFile(),cd->docLine(),cd,0,cd->documentation());
t << " </detaileddescription>" << endl;
DotClassGraph inheritanceGraph(cd,DotNode::Inheritance);
if (!inheritanceGraph.isTrivial())
{
t << " <inheritancegraph>" << endl;
inheritanceGraph.writeXML(t);
t << " </inheritancegraph>" << endl;
}
DotClassGraph collaborationGraph(cd,DotNode::Collaboration);
if (!collaborationGraph.isTrivial())
{
t << " <collaborationgraph>" << endl;
collaborationGraph.writeXML(t);
t << " </collaborationgraph>" << endl;
}
t << " <location file=\""
<< cd->getDefFileName() << "\" line=\""
<< cd->getDefLine() << "\"";
if (cd->getStartBodyLine()!=-1)
{
FileDef *bodyDef = cd->getBodyDef();
if (bodyDef)
{
t << " bodyfile=\"" << bodyDef->absFilePath() << "\"";
}
t << " bodystart=\"" << cd->getStartBodyLine() << "\" bodyend=\""
<< cd->getEndBodyLine() << "\"";
}
t << "/>" << endl;
writeListOfAllMembers(cd,t);
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForNamespace(NamespaceDef *nd,FTextStream &ti)
{
// + contained class definitions
// + contained namespace definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + location
// - files containing (parts of) the namespace definition
if (nd->isReference() || nd->isHidden()) return; // skip external references
ti << " <compound refid=\"" << nd->getOutputFileBase()
<< "\" kind=\"namespace\"" << "><name>"
<< convertToXML(nd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+nd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< nd->getOutputFileBase() << "\" kind=\"namespace\">" << endl;
t << " <compoundname>";
writeXMLString(t,nd->name());
t << "</compoundname>" << endl;
writeInnerClasses(nd->getClassSDict(),t);
writeInnerNamespaces(nd->getNamespaceSDict(),t);
if (nd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*nd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(nd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(nd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(nd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(nd,ti,t,&nd->decDefineMembers,"define");
generateXMLSection(nd,ti,t,&nd->decProtoMembers,"prototype");
generateXMLSection(nd,ti,t,&nd->decTypedefMembers,"typedef");
generateXMLSection(nd,ti,t,&nd->decEnumMembers,"enum");
generateXMLSection(nd,ti,t,&nd->decFuncMembers,"func");
generateXMLSection(nd,ti,t,&nd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,nd->briefFile(),nd->briefLine(),nd,0,nd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,nd->docFile(),nd->docLine(),nd,0,nd->documentation());
t << " </detaileddescription>" << endl;
t << " <location file=\""
<< nd->getDefFileName() << "\" line=\""
<< nd->getDefLine() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForFile(FileDef *fd,FTextStream &ti)
{
// + includes files
// + includedby files
// + include graph
// + included by graph
// + contained class definitions
// + contained namespace definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + source code
// + location
// - number of lines
if (fd->isReference()) return; // skip external references
ti << " <compound refid=\"" << fd->getOutputFileBase()
<< "\" kind=\"file\"><name>" << convertToXML(fd->name())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+fd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< fd->getOutputFileBase() << "\" kind=\"file\">" << endl;
t << " <compoundname>";
writeXMLString(t,fd->name());
t << "</compoundname>" << endl;
IncludeInfo *inc;
if (fd->includeFileList())
{
QListIterator<IncludeInfo> ili1(*fd->includeFileList());
for (ili1.toFirst();(inc=ili1.current());++ili1)
{
t << " <includes";
if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (inc->local ? "yes" : "no") << "\">";
t << inc->includeName;
t << "</includes>" << endl;
}
}
if (fd->includedByFileList())
{
QListIterator<IncludeInfo> ili2(*fd->includedByFileList());
for (ili2.toFirst();(inc=ili2.current());++ili2)
{
t << " <includedby";
if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (inc->local ? "yes" : "no") << "\">";
t << inc->includeName;
t << "</includedby>" << endl;
}
}
DotInclDepGraph incDepGraph(fd,FALSE);
if (!incDepGraph.isTrivial())
{
t << " <incdepgraph>" << endl;
incDepGraph.writeXML(t);
t << " </incdepgraph>" << endl;
}
DotInclDepGraph invIncDepGraph(fd,TRUE);
if (!invIncDepGraph.isTrivial())
{
t << " <invincdepgraph>" << endl;
invIncDepGraph.writeXML(t);
t << " </invincdepgraph>" << endl;
}
if (fd->getClassSDict())
{
writeInnerClasses(fd->getClassSDict(),t);
}
if (fd->getNamespaceSDict())
{
writeInnerNamespaces(fd->getNamespaceSDict(),t);
}
if (fd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*fd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(fd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(fd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(fd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(fd,ti,t,fd->decDefineMembers,"define");
generateXMLSection(fd,ti,t,fd->decProtoMembers,"prototype");
generateXMLSection(fd,ti,t,fd->decTypedefMembers,"typedef");
generateXMLSection(fd,ti,t,fd->decEnumMembers,"enum");
generateXMLSection(fd,ti,t,fd->decFuncMembers,"func");
generateXMLSection(fd,ti,t,fd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,fd->briefFile(),fd->briefLine(),fd,0,fd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,fd->docFile(),fd->docLine(),fd,0,fd->documentation());
t << " </detaileddescription>" << endl;
if (Config_getBool("XML_PROGRAMLISTING"))
{
t << " <programlisting>" << endl;
writeXMLCodeBlock(t,fd);
t << " </programlisting>" << endl;
}
t << " <location file=\"" << fd->getDefFileName() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForGroup(GroupDef *gd,FTextStream &ti)
{
// + members
// + member groups
// + files
// + classes
// + namespaces
// - packages
// + pages
// + child groups
// - examples
// + brief description
// + detailed description
if (gd->isReference()) return; // skip external references
ti << " <compound refid=\"" << gd->getOutputFileBase()
<< "\" kind=\"group\"><name>" << convertToXML(gd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+gd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< gd->getOutputFileBase() << "\" kind=\"group\">" << endl;
t << " <compoundname>" << convertToXML(gd->name()) << "</compoundname>" << endl;
t << " <title>" << convertToXML(gd->groupTitle()) << "</title>" << endl;
writeInnerFiles(gd->getFiles(),t);
writeInnerClasses(gd->getClasses(),t);
writeInnerNamespaces(gd->getNamespaces(),t);
writeInnerPages(gd->getPages(),t);
writeInnerGroups(gd->getSubGroups(),t);
if (gd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*gd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(gd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(gd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(gd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(gd,ti,t,&gd->decDefineMembers,"define");
generateXMLSection(gd,ti,t,&gd->decProtoMembers,"prototype");
generateXMLSection(gd,ti,t,&gd->decTypedefMembers,"typedef");
generateXMLSection(gd,ti,t,&gd->decEnumMembers,"enum");
generateXMLSection(gd,ti,t,&gd->decFuncMembers,"func");
generateXMLSection(gd,ti,t,&gd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,gd->briefFile(),gd->briefLine(),gd,0,gd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,gd->docFile(),gd->docLine(),gd,0,gd->documentation());
t << " </detaileddescription>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForDir(DirDef *dd,FTextStream &ti)
{
if (dd->isReference()) return; // skip external references
ti << " <compound refid=\"" << dd->getOutputFileBase()
<< "\" kind=\"dir\"><name>" << convertToXML(dd->displayName())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+dd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< dd->getOutputFileBase() << "\" kind=\"dir\">" << endl;
t << " <compoundname>" << convertToXML(dd->displayName()) << "</compoundname>" << endl;
writeInnerDirs(&dd->subDirs(),t);
writeInnerFiles(dd->getFiles(),t);
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,dd->briefFile(),dd->briefLine(),dd,0,dd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,dd->docFile(),dd->docLine(),dd,0,dd->documentation());
t << " </detaileddescription>" << endl;
t << " <location file=\"" << dd->name() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForPage(PageDef *pd,FTextStream &ti,bool isExample)
{
// + name
// + title
// + documentation
const char *kindName = isExample ? "example" : "page";
if (pd->isReference()) return;
QCString pageName = pd->getOutputFileBase();
if (pd->getGroupDef())
{
pageName+=(QCString)"_"+pd->name();
}
if (pageName=="index") pageName="indexpage"; // to prevent overwriting the generated index page.
ti << " <compound refid=\"" << pageName
<< "\" kind=\"" << kindName << "\"><name>" << convertToXML(pd->name())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+pageName+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\"" << pageName;
t << "\" kind=\"" << kindName << "\">" << endl;
t << " <compoundname>" << convertToXML(pd->name())
<< "</compoundname>" << endl;
if (pd==Doxygen::mainPage) // main page is special
{
QCString title;
if (!pd->title().isEmpty() && pd->title().lower()!="notitle")
{
title = filterTitle(Doxygen::mainPage->title());
}
else
{
title = Config_getString("PROJECT_NAME");
}
t << " <title>" << convertToXML(title) << "</title>" << endl;
}
else
{
SectionInfo *si = Doxygen::sectionDict->find(pd->name());
if (si)
{
t << " <title>" << convertToXML(si->title) << "</title>" << endl;
}
}
writeInnerPages(pd->getSubPages(),t);
t << " <detaileddescription>" << endl;
if (isExample)
{
writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0,
pd->documentation()+"\n\\include "+pd->name());
}
else
{
writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0,
pd->documentation());
}
t << " </detaileddescription>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
void generateXML()
{
// + classes
// + namespaces
// + files
// + groups
// + related pages
// - examples
QCString outputDirectory = Config_getString("XML_OUTPUT");
if (outputDirectory.isEmpty())
{
outputDirectory=QDir::currentDirPath().utf8();
}
else
{
QDir dir(outputDirectory);
if (!dir.exists())
{
dir.setPath(QDir::currentDirPath());
if (!dir.mkdir(outputDirectory))
{
err("error: tag XML_OUTPUT: Output directory `%s' does not "
"exist and cannot be created\n",outputDirectory.data());
exit(1);
}
else if (!Config_getBool("QUIET"))
{
err("notice: Output directory `%s' does not exist. "
"I have created it for you.\n", outputDirectory.data());
}
dir.cd(outputDirectory);
}
outputDirectory=dir.absPath().utf8();
}
QDir dir(outputDirectory);
if (!dir.exists())
{
dir.setPath(QDir::currentDirPath());
if (!dir.mkdir(outputDirectory))
{
err("Cannot create directory %s\n",outputDirectory.data());
return;
}
}
QDir xmlDir(outputDirectory);
createSubDirs(xmlDir);
QCString fileName=outputDirectory+"/index.xsd";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
f.writeBlock(index_xsd,qstrlen(index_xsd));
f.close();
fileName=outputDirectory+"/compound.xsd";
f.setName(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
f.writeBlock(compound_xsd,qstrlen(compound_xsd));
f.close();
fileName=outputDirectory+"/index.xml";
f.setName(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
// write index header
t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;;
t << "<doxygenindex xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
t << "xsi:noNamespaceSchemaLocation=\"index.xsd\" ";
t << "version=\"" << versionString << "\">" << endl;
{
ClassSDict::Iterator cli(*Doxygen::classSDict);
ClassDef *cd;
for (cli.toFirst();(cd=cli.current());++cli)
{
generateXMLForClass(cd,t);
}
}
//{
// ClassSDict::Iterator cli(Doxygen::hiddenClasses);
// ClassDef *cd;
// for (cli.toFirst();(cd=cli.current());++cli)
// {
// msg("Generating XML output for class %s\n",cd->name().data());
// generateXMLForClass(cd,t);
// }
//}
NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict);
NamespaceDef *nd;
for (nli.toFirst();(nd=nli.current());++nli)
{
msg("Generating XML output for namespace %s\n",nd->name().data());
generateXMLForNamespace(nd,t);
}
FileNameListIterator fnli(*Doxygen::inputNameList);
FileName *fn;
for (;(fn=fnli.current());++fnli)
{
FileNameIterator fni(*fn);
FileDef *fd;
for (;(fd=fni.current());++fni)
{
msg("Generating XML output for file %s\n",fd->name().data());
generateXMLForFile(fd,t);
}
}
GroupSDict::Iterator gli(*Doxygen::groupSDict);
GroupDef *gd;
for (;(gd=gli.current());++gli)
{
msg("Generating XML output for group %s\n",gd->name().data());
generateXMLForGroup(gd,t);
}
{
PageSDict::Iterator pdi(*Doxygen::pageSDict);
PageDef *pd=0;
for (pdi.toFirst();(pd=pdi.current());++pdi)
{
msg("Generating XML output for page %s\n",pd->name().data());
generateXMLForPage(pd,t,FALSE);
}
}
{
DirDef *dir;
DirSDict::Iterator sdi(*Doxygen::directories);
for (sdi.toFirst();(dir=sdi.current());++sdi)
{
msg("Generate XML output for dir %s\n",dir->name().data());
generateXMLForDir(dir,t);
}
}
{
PageSDict::Iterator pdi(*Doxygen::exampleSDict);
PageDef *pd=0;
for (pdi.toFirst();(pd=pdi.current());++pdi)
{
msg("Generating XML output for example %s\n",pd->name().data());
generateXMLForPage(pd,t,TRUE);
}
}
if (Doxygen::mainPage)
{
msg("Generating XML output for the main page\n");
generateXMLForPage(Doxygen::mainPage,t,FALSE);
}
//t << " </compoundlist>" << endl;
t << "</doxygenindex>" << endl;
writeCombineScript();
}
| bo0ts/doxygen-fixes | src/xmlgen.cpp | C++ | gpl-2.0 | 62,426 |
<?php
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Events\Api;
use Hubzero\Component\Router\Base;
/**
* Routing class for the component
*/
class Router extends Base
{
/**
* Build the route for the component.
*
* @param array &$query An array of URL arguments
* @return array The URL arguments to use to assemble the subsequent URL.
*/
public function build(&$query)
{
$segments = array();
if (!empty($query['controller']))
{
$segments[] = $query['controller'];
unset($query['controller']);
}
if (!empty($query['task']))
{
$segments[] = $query['task'];
unset($query['task']);
}
return $segments;
}
/**
* Parse the segments of a URL.
*
* @param array &$segments The segments of the URL to parse.
* @return array The URL attributes to be used by the application.
*/
public function parse(&$segments)
{
$vars = array();
$vars['controller'] = 'events';
if (isset($segments[0]))
{
if (is_numeric($segments[0]))
{
$vars['id'] = $segments[0];
if (\App::get('request')->method() == 'GET')
{
$vars['task'] = 'read';
}
}
else
{
$vars['task'] = $segments[0];
}
}
return $vars;
}
}
| hubzero/hubzero-cms | core/components/com_events/api/router.php | PHP | gpl-2.0 | 1,353 |
//
// (c) Copyright 2013 DESY, Eugen Wintersberger <eugen.wintersberger@desy.de>
//
// This file is part of pninexus.
//
// pninexus 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.
//
// pninexus 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 pninexus. If not, see <http://www.gnu.org/licenses/>.
//
// ===========================================================================
//
// Created on: Oct 28, 2013
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
//
#ifdef __GNUG__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <boost/test/unit_test.hpp>
#ifdef __GNUG__
#pragma GCC diagnostic pop
#endif
#include <pni/arrays.hpp>
#include "array_types.hpp"
#include "../data_generator.hpp"
#include "../compiler_version.hpp"
using namespace pni;
template<typename AT> struct test_mdarray_fixture
{
typedef AT array_type;
typedef typename array_type::value_type value_type;
typedef typename array_type::storage_type storage_type;
typedef typename array_type::map_type map_type;
typedef random_generator<value_type> generator_type;
generator_type generator;
shape_t shape;
test_mdarray_fixture():
generator(),
shape(shape_t{2,3,5})
{}
};
BOOST_AUTO_TEST_SUITE(test_mdarray)
typedef boost::mpl::joint_view<all_dynamic_arrays,
#if GCC_VERSION > 40800
boost::mpl::joint_view<
all_fixed_dim_arrays<3>,
all_static_arrays<2,3,5>
>
#else
all_fixed_dim_arrays<3>
#endif
> array_types;
template<typename CTYPE,typename...ITYPES>
static void create_index(CTYPE &index,ITYPES ...indexes)
{
index = CTYPE{indexes...};
}
template<typename T,size_t N,typename ...ITYPES>
static void create_index(std::array<T,N> &c,ITYPES ...indexes)
{
c = std::array<T,N>{{indexes...}};
}
template<
typename ITYPE,
typename ATYPE
>
void test_multiindex_access_with_container()
{
typedef test_mdarray_fixture<ATYPE> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = ATYPE::create(fixture.shape);
ITYPE index;
for(size_t i=0;i<fixture.shape[0];i++)
for(size_t j=0;j<fixture.shape[1];j++)
for(size_t k=0;k<fixture.shape[2];k++)
{
value_type v = fixture.generator();
create_index(index,i,j,k);
a(index) = v;
BOOST_CHECK_EQUAL(a(index),v);
}
}
//========================================================================
// Create a mdarray instance from a view
BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_construction,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
typedef dynamic_array<value_type> darray_type;
fixture_type fixture;
auto a = darray_type::create(shape_t{100,20,30});
std::generate(a.begin(),a.end(),fixture.generator);
auto view = a(slice(0,2),slice(0,3),slice(0,5));
AT target(view);
auto view_shape = view.template shape<shape_t>();
auto target_shape = target.template shape<shape_t>();
BOOST_CHECK_EQUAL_COLLECTIONS(view_shape.begin(),view_shape.end(),
target_shape.begin(),target_shape.end());
BOOST_CHECK_EQUAL(view.size(),target.size());
BOOST_CHECK_EQUAL(view.rank(),target.rank());
BOOST_CHECK_EQUAL_COLLECTIONS(view.begin(),view.end(),
target.begin(),target.end());
}
//========================================================================
BOOST_AUTO_TEST_CASE(test_is_view_index)
{
BOOST_CHECK((is_view_index<size_t,size_t,size_t>::value==false));
BOOST_CHECK((is_view_index<slice,size_t,size_t>::value==true));
BOOST_CHECK((is_view_index<size_t,slice,size_t>::value==true));
BOOST_CHECK((is_view_index<size_t,size_t,slice>::value==true));
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_inquery,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
BOOST_CHECK_EQUAL(a.size(),30u);
BOOST_CHECK_EQUAL(a.rank(),3u);
BOOST_CHECK(AT::type_id == type_id_map<value_type>::type_id);
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_operator,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
const AT &ca = a;
for(size_t index=0;index<a.size();++index)
{
value_type v = fixture.generator();
a[index] = v;
BOOST_CHECK_EQUAL(a[index],v);
BOOST_CHECK_EQUAL(ca[index],v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_pointer,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
std::generate(a.begin(),a.end(),fixture.generator);
auto ptr = a.data();
for(size_t index=0;index<a.size();++index)
BOOST_CHECK_EQUAL(a[index],*(ptr++));
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_at,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
const AT &ca = a;
for(size_t index=0;index<a.size();++index)
{
value_type v = fixture.generator();
a.at(index) = v;
BOOST_CHECK_EQUAL(a.at(index),v);
BOOST_CHECK_EQUAL(ca.at(index),v);
}
BOOST_CHECK_THROW(a.at(a.size()),index_error);
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_iter,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
typename AT::iterator iter = a.begin();
typename AT::const_iterator citer = a.begin();
for(;iter!=a.end();++iter,++citer)
{
value_type v = fixture.generator();
*iter = v;
BOOST_CHECK_EQUAL(*iter,v);
BOOST_CHECK_EQUAL(*citer,v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_riter,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
typename AT::reverse_iterator iter = a.rbegin();
typename AT::const_reverse_iterator citer = a.rbegin();
for(;iter!=a.rend();++iter,++citer)
{
value_type v = fixture.generator();
*iter = v;
BOOST_CHECK_EQUAL(*iter,v);
BOOST_CHECK_EQUAL(*citer,v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_multiindex_access,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
for(size_t i=0;i<fixture.shape[0];i++)
for(size_t j=0;j<fixture.shape[1];j++)
for(size_t k=0;k<fixture.shape[2];k++)
{
value_type v = fixture.generator();
a(i,j,k) = v;
BOOST_CHECK_EQUAL(a(i,j,k),v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_muldiindex_access_container,AT,array_types)
{
test_multiindex_access_with_container<std::vector<size_t>,AT>();
test_multiindex_access_with_container<std::array<size_t,3>,AT>();
test_multiindex_access_with_container<std::list<size_t>,AT>();
test_multiindex_access_with_container<std::vector<uint64>,AT>();
test_multiindex_access_with_container<std::array<uint64,3>,AT>();
test_multiindex_access_with_container<std::list<uint64>,AT>();
}
BOOST_AUTO_TEST_SUITE_END()
| pni-libraries/libpniio | test/arrays/mdarray_test.cpp | C++ | gpl-2.0 | 9,878 |
/**
* Setup (required for Joomla! 3)
*/
if(typeof(akeeba) == 'undefined') {
var akeeba = {};
}
if(typeof(akeeba.jQuery) == 'undefined') {
akeeba.jQuery = jQuery.noConflict();
}
akeeba.jQuery(document).ready(function($){
function atsAssignmentClick()
{
var parent = akeeba.jQuery(this).parent('td');
var id = akeeba.jQuery(this).parents('td').find('input.ticket_id').val();
var hide = ['.loading img', '.loading .icon-warning-sign'];
var show = ['.loading .icon-ok'];
var assign_to = 0;
if(akeeba.jQuery(this).hasClass('assignme'))
{
assign_to = akeeba.jQuery('#user').val();
}
else if(akeeba.jQuery(this).parent('.assignto'))
{
assign_to = akeeba.jQuery(this).parent().find('input.assignto').val();
}
if(this.hasClass('unassign')){
hide.push('.unassign');
show.push('.assignme');
}
else{
hide.push('.assignme');
show.push('.unassign');
}
var structure = {
_rootElement: this,
type: "POST",
dataType: 'json',
url : ATS_ROOT_URL + 'index.php?option=com_ats&view=ticket&format=json&' + akeeba.jQuery('#token').attr('name') + '=1',
data: {
'task' : 'assign',
'id' : id,
'assigned_to' : assign_to
},
beforeSend: function() {
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.css('display','inline').find('i').css('display', 'none');
wait.find('img').css('display', 'inline-block');
},
success: function(responseJSON)
{
var assigned = akeeba.jQuery(this._rootElement).parents('td').find('.assigned_to');
var unassign = akeeba.jQuery(this._rootElement).hasClass('unassign');
if(responseJSON.result == true){
assigned.html(responseJSON.assigned);
unassign ? assigned.removeClass('badge-info') : assigned.addClass('badge-info');
for (var i = 0; i < hide.length; i++)
{
var elementDefinition = hide[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'none');
}
for (var i = 0; i < show.length; i++)
{
var elementDefinition = show[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'inline-block');
}
}
else
{
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.find('.icon-ok,img').css('display', 'none');
wait.find('.icon-warning-sign').show('fast');
}
}
};
akeeba.jQuery.ajax( structure );
}
akeeba.jQuery('.unassign a').click(atsAssignmentClick);
akeeba.jQuery('.assignme a').click(atsAssignmentClick);
akeeba.jQuery('.assignto li a').click(atsAssignmentClick);
akeeba.jQuery('.select-status li a').click(function(){
var image = akeeba.jQuery(this).parent().find('img');
var self = this;
akeeba.jQuery.ajax(ATS_ROOT_URL + 'index.php?option=com_ats&view=tickets&task=ajax_set_status&format=json&'+jQuery('#token').attr('name')+'=1',{
type : 'POST',
dataType : 'json',
data : {
'id' : akeeba.jQuery(this).parents('tr').find('.ats_ticket_id').val(),
'status' : akeeba.jQuery(this).data('status')
},
beforeSend : function(){
image.show();
},
success : function(responseJSON){
image.hide();
if(responseJSON.err){
alert(responseJSON.err);
}
else{
var label = akeeba.jQuery(self).parents('td').find('span[class*="label-"]');
label.attr('class', 'ats-status label pull-right ' + responseJSON.ats_class).html(responseJSON.msg);
}
}
})
})
}); | SirPiter/folk | www/media/com_ats/js/tickets.js | JavaScript | gpl-2.0 | 3,563 |
<?php
namespace Requests\Exception\HTTP;
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests
*/
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests
*/
class _505 extends \Requests\Exception\HTTP
{
/**
* HTTP status code
*
* @var integer
*/
protected $code = 505;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'HTTP Version Not Supported';
}
| CMS-RuDi/CMS-RuDi | includes/libs/Requests/Exception/HTTP/505.php | PHP | gpl-2.0 | 486 |
<?php
namespace webfilesframework\core\datasystem\file\system\dropbox;
use webfilesframework\core\datasystem\file\system\MFile;
/**
* description
*
* @author Sebastian Monzel < mail@sebastianmonzel.de >
* @since 0.1.7
*/
class MDropboxFile extends MFile
{
protected $dropboxAccount;
protected $fileMetadata;
protected $filePath;
/**
*
* Enter description here ...
* @param MDropboxAccount $account
* @param $filePath
* @param bool $initMetadata
* @internal param unknown_type $fileName
*/
public function __construct(MDropboxAccount $account, $filePath, $initMetadata = true)
{
parent::__construct($filePath);
$this->filePath = $filePath;
$this->dropboxAccount = $account;
if ($initMetadata) {
$this->initMetadata();
}
}
public function initMetadata()
{
$this->fileMetadata = $this->dropboxAccount->getDropboxApi()->metaData($this->filePath);
$lastSlash = strrpos($this->fileMetadata['body']->path, '/');
$fileName = substr($this->fileMetadata['body']->path, $lastSlash + 1);
$this->fileName = $fileName;
}
public function getContent()
{
$file = $this->dropboxAccount->getDropboxApi()->getFile($this->filePath);
return $file['data'];
}
public function writeContent($content, $overwrite = false)
{
// TODO
}
/**
*
* Enter description here ...
*/
public function upload()
{
}
/**
*
* Enter description here ...
* @param $overwriteIfExists
*/
public function download($overwriteIfExists)
{
$file = $this->dropboxAccount->getDropboxApi()->getFile($this->filePath);
if (!file_exists("." . $this->filePath)) {
$fp = fopen("." . $this->filePath, "w");
fputs($fp, $file['data']);
fclose($fp);
}
}
public function downloadImageAsThumbnail()
{
$file = $this->dropboxAccount->getDropbox()->thumbnails($this->filePath, 'JPEG', 'l');
if (!file_exists("." . $this->filePath)) {
$fp = fopen("." . $this->filePath, "w");
fputs($fp, $file['data']);
fclose($fp);
}
}
} | sebastianmonzel/webfiles-framework-php | source/core/datasystem/file/system/dropbox/MDropboxFile.php | PHP | gpl-2.0 | 2,375 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\SettingsWorkingDays */
$this->title = 'Update Settings Working Days: ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Settings Working Days', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="settings-working-days-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| mig0s/athena | backend/views/settings-working-days/update.php | PHP | gpl-2.0 | 579 |
package openra.server;
import openra.core.Unit;
public class UnitAnimEvent extends ActionEvent
{
private Unit un;
private UnitAnimEvent scheduled;
public UnitAnimEvent(int p, Unit un) {
super(p);
//logger->debug("UAE cons: this:%p un:%p\n",this,un);
this.un = un;
//un.referTo();
scheduled = null;
}
void destUnitAnimEvent()
{
//logger->debug("UAE dest: this:%p un:%p sch:%p\n",this,un,scheduled);
if (scheduled != null) {
this.getAequeue().scheduleEvent(scheduled);
}
//un->unrefer();
}
protected void setSchedule(UnitAnimEvent e)
{
//logger->debug("Scheduling an event. (this: %p, e: %p)\n",this,e);
if (scheduled != null) {
scheduled.setSchedule(null);
scheduled.stop();
}
scheduled = e;
}
void stopScheduled()
{
if (scheduled != null) {
scheduled.stop();
}
}
void update()
{
}
}
| damiencarol/openredalert | java/src/openra/server/UnitAnimEvent.java | Java | gpl-2.0 | 965 |
/**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of simpledeb.
*
* simpledeb is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* simpledeb 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 simpledeb; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.simpledeb.core.action;
import java.io.File;
import java.util.LinkedList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import com.moss.simpledeb.core.DebComponent;
import com.moss.simpledeb.core.DebState;
import com.moss.simpledeb.core.path.ArchivePath;
import com.moss.simpledeb.core.path.BytesArchivePath;
import com.moss.simpledeb.core.path.DirArchivePath;
@XmlAccessorType(XmlAccessType.FIELD)
public final class LaunchScriptAction extends DebAction {
@XmlAttribute(name="class-name")
private String className;
@XmlAttribute(name="target-file")
private String targetFile;
@XmlAttribute(name="path-level")
private int pathLevel;
@Override
public void run(DebState state) throws Exception {
{
File target = new File(targetFile).getParentFile();
LinkedList<File> pathsNeeded = new LinkedList<File>();
File f = target;
while (f != null) {
pathsNeeded.addFirst(f);
f = f.getParentFile();
}
for (int i=0; i<pathLevel; i++) {
pathsNeeded.removeFirst();
}
for (File e : pathsNeeded) {
String p = "./" + e.getPath();
if (!p.endsWith("/")) {
p = p + "/";
}
TarArchiveEntry tarEntry = new TarArchiveEntry(p);
tarEntry.setGroupId(0);
tarEntry.setGroupName("root");
tarEntry.setIds(0, 0);
tarEntry.setModTime(System.currentTimeMillis());
tarEntry.setSize(0);
tarEntry.setUserId(0);
tarEntry.setUserName("root");
tarEntry.setMode(Integer.parseInt("755", 8));
ArchivePath path = new DirArchivePath(tarEntry);
state.addPath(DebComponent.CONTENT, path);
}
}
String cp;
{
StringBuffer sb = new StringBuffer();
for (String path : state.classpath) {
if (sb.length() == 0) {
sb.append(path);
}
else {
sb.append(":");
sb.append(path);
}
}
cp = sb.toString();
}
StringBuilder sb = new StringBuilder();
sb.append("#!/bin/bash\n");
sb.append("CP=\"");
sb.append(cp);
sb.append("\"\n");
sb.append("/usr/bin/java -cp $CP ");
sb.append(className);
sb.append(" $@\n");
byte[] data = sb.toString().getBytes();
String entryName = "./" + targetFile;
TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
tarEntry.setGroupId(0);
tarEntry.setGroupName("root");
tarEntry.setIds(0, 0);
tarEntry.setModTime(System.currentTimeMillis());
tarEntry.setSize(data.length);
tarEntry.setUserId(0);
tarEntry.setUserName("root");
tarEntry.setMode(Integer.parseInt("755", 8));
ArchivePath path = new BytesArchivePath(tarEntry, data);
state.addPath(DebComponent.CONTENT, path);
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getTargetFile() {
return targetFile;
}
public void setTargetFile(String targetFile) {
this.targetFile = targetFile;
}
public int getPathLevel() {
return pathLevel;
}
public void setPathLevel(int assumedTargetPathLevel) {
this.pathLevel = assumedTargetPathLevel;
}
}
| mosscode/simpledeb | core/src/main/java/com/moss/simpledeb/core/action/LaunchScriptAction.java | Java | gpl-2.0 | 4,990 |
/*µü´úÆ÷ģʽ
*
* ±éÀú¼¯ºÏµÄÖ°Ôð·ÖÀë³öÀ´£»
*/
/**°×Ïä¾ÛºÏ+Íâµü´ú×Ó*/
public interface Iterator
{
public Object first();
public Object next();
//µÃµ½µ±Ç°¶ÔÏó
public Object currentItem();
//ÊÇ·ñµ½Á˽áβ
public boolean isDone();
}
//ÕýÐòµü´úÆ÷
public class ConcreteIterator implements Iterator
{
private int currentIndex = 0;
//¶¨ÒåÒ»¸ö¾ßÌ弯ºÏ¶ÔÏó
private Aggregate aggregate = null;
public ConcreteIterator(Aggregate aggregate)
{
this.aggregate = aggregate;
}
//ÖØÐ´¸¸Àà·½·¨
@Override
public Object first()
{
currentIndex = 0;
return vector.get(currentIndex);
}
@Override
public Object next()
{
if(currentIndex < aggregate.count())
currentIndex++;
return vector.get(currentIndex);
}
@Override
public Object currentItem()
{
return aggregate.getAt(currentIndex);
}
@Override
public boolean isDone()
{
return (currentIndex >= aggregate.count());
}
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
//°×Ïä¾ÛºÏÒªÇ󼯺ÏÀàÏòÍâ½çÌṩ·ÃÎÊ×Ô¼ºÄÚ²¿ÔªËصĽӿÚ
public interface Aggregat
{
public Iterator createIterator();
//»ñÈ¡¼¯ºÏÄÚ²¿ÔªËØ×ÜÊý
public int count();
//»ñȡָ¶¨Î»ÖÃÔªËØ
public Object getAt(int index);
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
//¾ßÌåµÄ¼¯ºÏÀà
public class ConcreteAggregat implements Aggregat
{
private Vector vector = null;
public Vector getVector()
{
return vector;
}
public void setVector(final Vector vector)
{
this.vector = vector;
}
public ConcreteAggregat()
{
vector = new Vector();
vector.add("item 1");
vector.add("item 2");
}
//»ñÈ¡¼¯ºÏÄÚ²¿ÔªËØ×ÜÊý
@Override
public int count()
{
return vector.size();
}
//»ñȡָ¶¨Î»ÖÃÔªËØ
@Override
public Object getAt(int index)
{
if(0 <= index && index < vector.size())
return vector[index];
else
return null;
}
//´´½¨Ò»¸ö¾ßÌåµü´úÆ÷¶ÔÏ󣬲¢°Ñ¸Ã¼¯ºÏ¶ÔÏó×ÔÉí½»¸ø¸Ãµü´úÆ÷
@Override
public Iterator createIterator()
{
//ÕâÀï¿ÉÒÔʹÓüòµ¥¹¤³§Ä£Ê½
return new ConcreteIterator(this);
}
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
public class Client
{
public static void main(final String[] args)
{
Aggregat agg = new ConcreteAggregat();
final Iterator iterator = agg.createIterator();
System.out.println(iterator.first());
while (!iterator.isDone())
{
//Item item = (Item)iterator.currentItem();
System.out.println(iterator.next());
}
}
}
| creary/company | document/设计模式/3行为型/3迭代器.java | Java | gpl-2.0 | 2,882 |
package yuka.detectors;
import yuka.containers.News;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by imyuka on 18/08/2016.
*/
public class FigureDetector {
private Map<String, Integer> cmap;
private Map<String, Integer> pmap;
private Map<String, Integer> dim;
//private int height = 0;
//private int height = 0;
public FigureDetector(Map<String, String> figure) {
String url = figure.get(News.IMAGE_URL);
dim = getDimension(url);
String caption = figure.get(News.IMAGE_CAPTION);
cmap = ClubDetector.count(caption);
PlayerDetector pd = new PlayerDetector(cmap.keySet());
pmap = pd.count(caption);
}
public int getHeight() {
return dim.get("height");
}
public int getWidth() {
return dim.get("width");
}
public double getPercentage (double totalHeight) {
return (double) getWidth() / HeightDetector.COLUMN_WIDTH
* (getHeight() / totalHeight);
}
public Map<String, Integer> getClubMap() {
return cmap;
}
public Map<String, Integer> getPlayerMap() {
return pmap;
}
public static Map<String, Integer> getDimension (String source) {
//int[] dim = new int[]{0,0};
Map<String, Integer> dim = new HashMap<>();
dim.put("width", 0);
dim.put("height", 0);
try {
URL url = new URL(source);
URLConnection conn = url.openConnection();
// now you get the content length
/////int contentLength = conn.getContentLength();
// you can check size here using contentLength
InputStream in = conn.getInputStream();
BufferedImage image = ImageIO.read(in);
// you can get size dimesion
//int width = image.getWidth();
//int height = image.getHeight();
dim.put("width", image.getWidth());
dim.put("height", image.getHeight());
} catch (IOException e) {
System.out.println();
}
return dim;
}
}
| imyuka/AFL | AFL/src/main/java/yuka/detectors/FigureDetector.java | Java | gpl-2.0 | 2,274 |
# Copyright 2014-2017 Red Hat, 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.
#
# 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
#
# Refer to the README and COPYING files for full details of the license
#
"""
When importing a VM a thread start with a new process of virt-v2v.
The way to feedback the information on the progress and the status of the
process (ie job) is via getVdsStats() with the fields progress and status.
progress is a number which represent percentage of a single disk copy,
status is a way to feedback information on the job (init, error etc)
"""
from __future__ import absolute_import
from collections import namedtuple
from contextlib import closing, contextmanager
import errno
import io
import logging
import os
import re
import subprocess
import tarfile
import time
import threading
import xml.etree.ElementTree as ET
import zipfile
import libvirt
from vdsm.cmdutils import wrap_command
from vdsm.commands import execCmd, BUFFSIZE
from vdsm.common import cmdutils
from vdsm.common.define import errCode, doneCode
from vdsm.common import response
from vdsm.common import zombiereaper
from vdsm.common.compat import CPopen
from vdsm.common.logutils import traceback
from vdsm.common.time import monotonic_time
from vdsm.constants import P_VDSM_LOG, P_VDSM_RUN, EXT_KVM_2_OVIRT
from vdsm import concurrent, libvirtconnection
from vdsm import password
from vdsm.utils import terminating, NICENESS, IOCLASS
try:
import ovirt_imageio_common
except ImportError:
ovirt_imageio_common = None
_lock = threading.Lock()
_jobs = {}
_V2V_DIR = os.path.join(P_VDSM_RUN, 'v2v')
_LOG_DIR = os.path.join(P_VDSM_LOG, 'import')
_VIRT_V2V = cmdutils.CommandPath('virt-v2v', '/usr/bin/virt-v2v')
_SSH_AGENT = cmdutils.CommandPath('ssh-agent', '/usr/bin/ssh-agent')
_SSH_ADD = cmdutils.CommandPath('ssh-add', '/usr/bin/ssh-add')
_XEN_SSH_PROTOCOL = 'xen+ssh'
_VMWARE_PROTOCOL = 'vpx'
_KVM_PROTOCOL = 'qemu'
_SSH_AUTH_RE = '(SSH_AUTH_SOCK)=([^;]+).*;\nSSH_AGENT_PID=(\d+)'
_OVF_RESOURCE_CPU = 3
_OVF_RESOURCE_MEMORY = 4
_OVF_RESOURCE_NETWORK = 10
_QCOW2_COMPAT_SUPPORTED = ('0.10', '1.1')
# OVF Specification:
# https://www.iso.org/obp/ui/#iso:std:iso-iec:17203:ed-1:v1:en
_OVF_NS = 'http://schemas.dmtf.org/ovf/envelope/1'
_RASD_NS = 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' \
'CIM_ResourceAllocationSettingData'
ImportProgress = namedtuple('ImportProgress',
['current_disk', 'disk_count', 'description'])
DiskProgress = namedtuple('DiskProgress', ['progress'])
class STATUS:
'''
STARTING: request granted and starting the import process
COPYING_DISK: copying disk in progress
ABORTED: user initiated aborted
FAILED: error during import process
DONE: convert process successfully finished
'''
STARTING = 'starting'
COPYING_DISK = 'copying_disk'
ABORTED = 'aborted'
FAILED = 'error'
DONE = 'done'
class V2VError(Exception):
''' Base class for v2v errors '''
err_name = 'unexpected' # TODO: use more specific error
class ClientError(Exception):
''' Base class for client error '''
err_name = 'unexpected'
class InvalidVMConfiguration(ValueError):
''' Unexpected error while parsing libvirt domain xml '''
class OutputParserError(V2VError):
''' Error while parsing virt-v2v output '''
class JobExistsError(ClientError):
''' Job already exists in _jobs collection '''
err_name = 'JobExistsError'
class VolumeError(ClientError):
''' Error preparing volume '''
class NoSuchJob(ClientError):
''' Job not exists in _jobs collection '''
err_name = 'NoSuchJob'
class JobNotDone(ClientError):
''' Import process still in progress '''
err_name = 'JobNotDone'
class NoSuchOvf(V2VError):
''' Ovf path is not exists in /var/run/vdsm/v2v/ '''
err_name = 'V2VNoSuchOvf'
class V2VProcessError(V2VError):
''' virt-v2v process had error in execution '''
class InvalidInputError(ClientError):
''' Invalid input received '''
def get_external_vms(uri, username, password, vm_names=None):
if vm_names is not None:
if not vm_names:
vm_names = None
else:
vm_names = frozenset(vm_names)
try:
conn = libvirtconnection.open_connection(uri=uri,
username=username,
passwd=password)
except libvirt.libvirtError as e:
logging.exception('error connecting to hypervisor')
return {'status': {'code': errCode['V2VConnection']['status']['code'],
'message': str(e)}}
with closing(conn):
vms = []
for vm in _list_domains(conn):
if vm_names is not None and vm.name() not in vm_names:
# Skip this VM.
continue
elif conn.getType() == "ESX" and _vm_has_snapshot(vm):
logging.error("vm %r has snapshots and therefore can not be "
"imported since snapshot conversion is not "
"supported for VMware", vm.name())
continue
_add_vm(conn, vms, vm)
return {'status': doneCode, 'vmList': vms}
def get_external_vm_names(uri, username, password):
try:
conn = libvirtconnection.open_connection(uri=uri,
username=username,
passwd=password)
except libvirt.libvirtError as e:
logging.exception('error connecting to hypervisor')
return response.error('V2VConnection', str(e))
with closing(conn):
vms = [vm.name() for vm in _list_domains(conn)]
return response.success(vmNames=vms)
def convert_external_vm(uri, username, password, vminfo, job_id, irs):
if uri.startswith(_XEN_SSH_PROTOCOL):
command = XenCommand(uri, vminfo, job_id, irs)
elif uri.startswith(_VMWARE_PROTOCOL):
command = LibvirtCommand(uri, username, password, vminfo, job_id,
irs)
elif uri.startswith(_KVM_PROTOCOL):
if ovirt_imageio_common is None:
raise V2VError('Unsupported protocol KVM, ovirt_imageio_common'
'package is needed for importing KVM images')
command = KVMCommand(uri, username, password, vminfo, job_id, irs)
else:
raise ClientError('Unknown protocol for Libvirt uri: %s', uri)
job = ImportVm(job_id, command)
job.start()
_add_job(job_id, job)
return {'status': doneCode}
def convert_ova(ova_path, vminfo, job_id, irs):
command = OvaCommand(ova_path, vminfo, job_id, irs)
job = ImportVm(job_id, command)
job.start()
_add_job(job_id, job)
return response.success()
def get_ova_info(ova_path):
ns = {'ovf': _OVF_NS, 'rasd': _RASD_NS}
try:
root = ET.fromstring(_read_ovf_from_ova(ova_path))
except ET.ParseError as e:
raise V2VError('Error reading ovf from ova, position: %r' % e.position)
vm = {}
_add_general_ovf_info(vm, root, ns, ova_path)
_add_disks_ovf_info(vm, root, ns)
_add_networks_ovf_info(vm, root, ns)
return response.success(vmList=vm)
def get_converted_vm(job_id):
try:
job = _get_job(job_id)
_validate_job_done(job)
ovf = _read_ovf(job_id)
except ClientError as e:
logging.info('Converted VM error %s', e)
return errCode[e.err_name]
except V2VError as e:
logging.error('Converted VM error %s', e)
return errCode[e.err_name]
return {'status': doneCode, 'ovf': ovf}
def delete_job(job_id):
try:
job = _get_job(job_id)
_validate_job_finished(job)
_remove_job(job_id)
except ClientError as e:
logging.info('Cannot delete job, error: %s', e)
return errCode[e.err_name]
return {'status': doneCode}
def abort_job(job_id):
try:
job = _get_job(job_id)
job.abort()
except ClientError as e:
logging.info('Cannot abort job, error: %s', e)
return errCode[e.err_name]
return {'status': doneCode}
def get_jobs_status():
ret = {}
with _lock:
items = tuple(_jobs.items())
for job_id, job in items:
ret[job_id] = {
'status': job.status,
'description': job.description,
'progress': job.progress
}
return ret
def _add_job(job_id, job):
with _lock:
if job_id in _jobs:
raise JobExistsError("Job %r exists" % job_id)
_jobs[job_id] = job
def _get_job(job_id):
with _lock:
if job_id not in _jobs:
raise NoSuchJob("No such job %r" % job_id)
return _jobs[job_id]
def _remove_job(job_id):
with _lock:
if job_id not in _jobs:
raise NoSuchJob("No such job %r" % job_id)
del _jobs[job_id]
def _validate_job_done(job):
if job.status != STATUS.DONE:
raise JobNotDone("Job %r is %s" % (job.id, job.status))
def _validate_job_finished(job):
if job.status not in (STATUS.DONE, STATUS.FAILED, STATUS.ABORTED):
raise JobNotDone("Job %r is %s" % (job.id, job.status))
def _read_ovf(job_id):
file_name = os.path.join(_V2V_DIR, "%s.ovf" % job_id)
try:
with open(file_name, 'r') as f:
return f.read()
except IOError as e:
if e.errno != errno.ENOENT:
raise
raise NoSuchOvf("No such ovf %r" % file_name)
class SSHAgent(object):
"""
virt-v2v uses ssh-agent for importing xen vms from libvirt,
after virt-v2v log in to the machine it needs to copy its disks
which ssh-agent let it handle without passwords while the session
is on.
for more information please refer to the virt-v2v man page:
http://libguestfs.org/virt-v2v.1.html
"""
def __init__(self):
self._auth = None
self._agent_pid = None
self._ssh_auth_re = re.compile(_SSH_AUTH_RE)
def __enter__(self):
rc, out, err = execCmd([_SSH_AGENT.cmd], raw=True)
if rc != 0:
raise V2VError('Error init ssh-agent, exit code: %r'
', out: %r, err: %r' %
(rc, out, err))
m = self._ssh_auth_re.match(out)
# looking for: SSH_AUTH_SOCK=/tmp/ssh-VEE74ObhTWBT/agent.29917
self._auth = {m.group(1): m.group(2)}
self._agent_pid = m.group(3)
try:
rc, out, err = execCmd([_SSH_ADD.cmd], env=self._auth)
except:
self._kill_agent()
raise
if rc != 0:
# 1 = general fail
# 2 = no agnet
if rc != 2:
self._kill_agent()
raise V2VError('Error init ssh-add, exit code: %r'
', out: %r, err: %r' %
(rc, out, err))
def __exit__(self, *args):
rc, out, err = execCmd([_SSH_ADD.cmd, '-d'], env=self._auth)
if rc != 0:
logging.error('Error deleting ssh-add, exit code: %r'
', out: %r, err: %r' %
(rc, out, err))
self._kill_agent()
def _kill_agent(self):
rc, out, err = execCmd([_SSH_AGENT.cmd, '-k'],
env={'SSH_AGENT_PID': self._agent_pid})
if rc != 0:
logging.error('Error killing ssh-agent (PID=%r), exit code: %r'
', out: %r, err: %r' %
(self._agent_pid, rc, out, err))
@property
def auth(self):
return self._auth
class V2VCommand(object):
def __init__(self, vminfo, vmid, irs):
self._vminfo = vminfo
self._vmid = vmid
self._irs = irs
self._prepared_volumes = []
self._passwd_file = os.path.join(_V2V_DIR, "%s.tmp" % vmid)
self._password = password.ProtectedPassword('')
self._base_command = [_VIRT_V2V.cmd, '-v', '-x']
self._query_v2v_caps()
if 'qcow2_compat' in vminfo:
qcow2_compat = vminfo['qcow2_compat']
if qcow2_compat not in _QCOW2_COMPAT_SUPPORTED:
logging.error('Invalid QCOW2 compat version %r' %
qcow2_compat)
raise ValueError('Invalid QCOW2 compat version %r' %
qcow2_compat)
if 'vdsm-compat-option' in self._v2v_caps:
self._base_command.extend(['--vdsm-compat', qcow2_compat])
elif qcow2_compat != '0.10':
# Note: qcow2 is only a suggestion from the engine
# if virt-v2v doesn't support it we fall back to default
logging.info('virt-v2v not supporting qcow2 compat version: '
'%r', qcow2_compat)
def execute(self):
raise NotImplementedError("Subclass must implement this")
def _command(self):
raise NotImplementedError("Subclass must implement this")
def _start_helper(self):
timestamp = time.strftime('%Y%m%dT%H%M%S')
log = os.path.join(_LOG_DIR,
"import-%s-%s.log" % (self._vmid, timestamp))
logging.info("Storing import log at: %r", log)
v2v = _simple_exec_cmd(self._command(),
nice=NICENESS.HIGH,
ioclass=IOCLASS.IDLE,
env=self._environment(),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
tee = _simple_exec_cmd(['tee', log],
nice=NICENESS.HIGH,
ioclass=IOCLASS.IDLE,
stdin=v2v.stdout,
stdout=subprocess.PIPE)
return PipelineProc(v2v, tee)
def _get_disk_format(self):
fmt = self._vminfo.get('format', 'raw').lower()
return "qcow2" if fmt == "cow" else fmt
def _disk_parameters(self):
parameters = []
for disk in self._vminfo['disks']:
try:
parameters.append('--vdsm-image-uuid')
parameters.append(disk['imageID'])
parameters.append('--vdsm-vol-uuid')
parameters.append(disk['volumeID'])
except KeyError as e:
raise InvalidInputError('Job %r missing required property: %s'
% (self._vmid, e))
return parameters
@contextmanager
def _volumes(self):
self._prepare_volumes()
try:
yield
finally:
self._teardown_volumes()
def _prepare_volumes(self):
if len(self._vminfo['disks']) < 1:
raise InvalidInputError('Job %r cannot import vm with no disk',
self._vmid)
for disk in self._vminfo['disks']:
drive = {'poolID': self._vminfo['poolID'],
'domainID': self._vminfo['domainID'],
'volumeID': disk['volumeID'],
'imageID': disk['imageID']}
res = self._irs.prepareImage(drive['domainID'],
drive['poolID'],
drive['imageID'],
drive['volumeID'])
if res['status']['code']:
raise VolumeError('Job %r bad volume specification: %s' %
(self._vmid, drive))
drive['path'] = res['path']
self._prepared_volumes.append(drive)
def _teardown_volumes(self):
for drive in self._prepared_volumes:
try:
self._irs.teardownImage(drive['domainID'],
drive['poolID'],
drive['imageID'])
except Exception as e:
logging.error('Job %r error tearing down drive: %s',
self._vmid, e)
def _get_storage_domain_path(self, path):
'''
prepareImage returns /prefix/sdUUID/images/imgUUID/volUUID
we need storage domain absolute path so we go up 3 levels
'''
return path.rsplit(os.sep, 3)[0]
def _environment(self):
# Provide some sane environment
env = os.environ.copy()
# virt-v2v specific variables
env['LIBGUESTFS_BACKEND'] = 'direct'
if 'virtio_iso_path' in self._vminfo:
env['VIRTIO_WIN'] = self._vminfo['virtio_iso_path']
return env
@contextmanager
def _password_file(self):
fd = os.open(self._passwd_file, os.O_WRONLY | os.O_CREAT, 0o600)
try:
if self._password.value is None:
os.write(fd, "")
else:
os.write(fd, self._password.value)
finally:
os.close(fd)
try:
yield
finally:
try:
os.remove(self._passwd_file)
except Exception:
logging.exception("Job %r error removing passwd file: %s",
self._vmid, self._passwd_file)
def _query_v2v_caps(self):
self._v2v_caps = frozenset()
p = _simple_exec_cmd([_VIRT_V2V.cmd, '--machine-readable'],
env=os.environ.copy(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
with terminating(p):
try:
out, err = p.communicate()
except Exception:
logging.exception('Terminating virt-v2v process after error')
raise
if p.returncode != 0:
raise V2VProcessError(
'virt-v2v exited with code: %d, stderr: %r' %
(p.returncode, err))
self._v2v_caps = frozenset(out.splitlines())
logging.debug("Detected virt-v2v capabilities: %r", self._v2v_caps)
class LibvirtCommand(V2VCommand):
def __init__(self, uri, username, password, vminfo, vmid, irs):
super(LibvirtCommand, self).__init__(vminfo, vmid, irs)
self._uri = uri
self._username = username
self._password = password
def _command(self):
cmd = self._base_command
cmd.extend(['-ic', self._uri,
'-o', 'vdsm',
'-of', self._get_disk_format(),
'-oa', self._vminfo.get('allocation', 'sparse').lower()])
cmd.extend(self._disk_parameters())
cmd.extend(['--password-file',
self._passwd_file,
'--vdsm-vm-uuid',
self._vmid,
'--vdsm-ovf-output',
_V2V_DIR,
'--machine-readable',
'-os',
self._get_storage_domain_path(
self._prepared_volumes[0]['path']),
self._vminfo['vmName']])
return cmd
@contextmanager
def execute(self):
with self._volumes(), self._password_file():
yield self._start_helper()
class OvaCommand(V2VCommand):
def __init__(self, ova_path, vminfo, vmid, irs):
super(OvaCommand, self).__init__(vminfo, vmid, irs)
self._ova_path = ova_path
def _command(self):
cmd = self._base_command
cmd.extend(['-i', 'ova', self._ova_path,
'-o', 'vdsm',
'-of', self._get_disk_format(),
'-oa', self._vminfo.get('allocation', 'sparse').lower(),
'--vdsm-vm-uuid',
self._vmid,
'--vdsm-ovf-output',
_V2V_DIR,
'--machine-readable',
'-os',
self._get_storage_domain_path(
self._prepared_volumes[0]['path'])])
cmd.extend(self._disk_parameters())
return cmd
@contextmanager
def execute(self):
with self._volumes():
yield self._start_helper()
class XenCommand(V2VCommand):
"""
Importing Xen via virt-v2v require to use xen+ssh protocol.
this requires:
- enable the vdsm user in /etc/passwd
- generate ssh keys via ssh-keygen
- public key exchange with the importing hosts user
- host must be in ~/.ssh/known_hosts (done automatically
by ssh to the host before importing vm)
"""
def __init__(self, uri, vminfo, job_id, irs):
super(XenCommand, self).__init__(vminfo, job_id, irs)
self._uri = uri
self._ssh_agent = SSHAgent()
def _command(self):
cmd = self._base_command
cmd.extend(['-ic', self._uri,
'-o', 'vdsm',
'-of', self._get_disk_format(),
'-oa', self._vminfo.get('allocation', 'sparse').lower()])
cmd.extend(self._disk_parameters())
cmd.extend(['--vdsm-vm-uuid',
self._vmid,
'--vdsm-ovf-output',
_V2V_DIR,
'--machine-readable',
'-os',
self._get_storage_domain_path(
self._prepared_volumes[0]['path']),
self._vminfo['vmName']])
return cmd
@contextmanager
def execute(self):
with self._volumes(), self._ssh_agent:
yield self._start_helper()
def _environment(self):
env = super(XenCommand, self)._environment()
env.update(self._ssh_agent.auth)
return env
class KVMCommand(V2VCommand):
def __init__(self, uri, username, password, vminfo, vmid, irs):
super(KVMCommand, self).__init__(vminfo, vmid, irs)
self._uri = uri
self._username = username
self._password = password
def _command(self):
cmd = [EXT_KVM_2_OVIRT,
'--uri', self._uri]
if self._username is not None:
cmd.extend([
'--username', self._username,
'--password-file', self._passwd_file])
src, fmt = self._source_images()
cmd.append('--source')
cmd.extend(src)
cmd.append('--dest')
cmd.extend(self._dest_images())
cmd.append('--storage-type')
cmd.extend(fmt)
cmd.append('--vm-name')
cmd.append(self._vminfo['vmName'])
return cmd
@contextmanager
def execute(self):
with self._volumes(), self._password_file():
yield self._start_helper()
def _source_images(self):
con = libvirtconnection.open_connection(uri=self._uri,
username=self._username,
passwd=self._password)
with closing(con):
vm = con.lookupByName(self._vminfo['vmName'])
if vm:
params = {}
root = ET.fromstring(vm.XMLDesc(0))
_add_disks(root, params)
src = []
fmt = []
for disk in params['disks']:
if 'alias' in disk:
src.append(disk['alias'])
fmt.append(disk['disktype'])
return src, fmt
def _dest_images(self):
ret = []
for vol in self._prepared_volumes:
ret.append(vol['path'])
return ret
class PipelineProc(object):
def __init__(self, proc1, proc2):
self._procs = (proc1, proc2)
self._stdout = proc2.stdout
def kill(self):
"""
Kill all processes in a pipeline.
Some of the processes may have already terminated, but some may be
still running. Regular kill() raises OSError if the process has already
terminated. Since we are dealing with multiple processes, to avoid any
confusion we do not raise OSError at all.
"""
for p in self._procs:
logging.debug("Killing pid=%d", p.pid)
try:
p.kill()
except OSError as e:
# Probably the process has already terminated
if e.errno != errno.ESRCH:
raise e
@property
def pids(self):
return [p.pid for p in self._procs]
@property
def returncode(self):
"""
Returns None if any of the processes is still running. Returns 0 if all
processes have finished with a zero exit code, otherwise return first
nonzero exit code.
"""
ret = 0
for p in self._procs:
p.poll()
if p.returncode is None:
return None
if p.returncode != 0 and ret == 0:
# One of the processes has failed
ret = p.returncode
# All processes have finished
return ret
@property
def stdout(self):
return self._stdout
def wait(self, timeout=None):
if timeout is not None:
deadline = monotonic_time() + timeout
else:
deadline = None
for p in self._procs:
if deadline is not None:
# NOTE: CPopen doesn't support timeout argument.
while monotonic_time() < deadline:
p.poll()
if p.returncode is not None:
break
time.sleep(1)
else:
p.wait()
if deadline is not None:
if deadline < monotonic_time() or self.returncode is None:
# Timed out
return False
return True
class ImportVm(object):
TERM_DELAY = 30
PROC_WAIT_TIMEOUT = 30
def __init__(self, job_id, command):
self._id = job_id
self._command = command
self._thread = None
self._status = STATUS.STARTING
self._description = ''
self._disk_progress = 0
self._disk_count = 1
self._current_disk = 1
self._aborted = False
self._proc = None
def start(self):
self._thread = concurrent.thread(self._run, name="v2v/" + self._id[:8])
self._thread.start()
def wait(self):
if self._thread is not None and self._thread.is_alive():
self._thread.join()
@property
def id(self):
return self._id
@property
def status(self):
return self._status
@property
def description(self):
return self._description
@property
def progress(self):
'''
progress is part of multiple disk_progress its
flat and not 100% accurate - each disk take its
portion ie if we have 2 disks the first will take
0-50 and the second 50-100
'''
completed = (self._disk_count - 1) * 100
return (completed + self._disk_progress) / self._disk_count
@traceback(msg="Error importing vm")
def _run(self):
try:
self._import()
except Exception as ex:
if self._aborted:
logging.debug("Job %r was aborted", self._id)
else:
logging.exception("Job %r failed", self._id)
self._status = STATUS.FAILED
self._description = str(ex)
try:
if self._proc is not None:
self._abort()
except Exception as e:
logging.exception('Job %r, error trying to abort: %r',
self._id, e)
def _import(self):
logging.info('Job %r starting import', self._id)
with self._command.execute() as self._proc:
self._watch_process_output()
self._wait_for_process()
if self._proc.returncode != 0:
raise V2VProcessError('Job %r process failed exit-code: %r' %
(self._id,
self._proc.returncode))
if self._status != STATUS.ABORTED:
self._status = STATUS.DONE
logging.info('Job %r finished import successfully',
self._id)
def _wait_for_process(self):
if self._proc.returncode is not None:
return
logging.debug("Job %r waiting for virt-v2v process", self._id)
if not self._proc.wait(timeout=self.PROC_WAIT_TIMEOUT):
raise V2VProcessError("Job %r timeout waiting for process pid=%s",
self._id, self._proc.pids)
def _watch_process_output(self):
out = io.BufferedReader(io.FileIO(self._proc.stdout.fileno(),
mode='r', closefd=False), BUFFSIZE)
parser = OutputParser()
for event in parser.parse(out):
if isinstance(event, ImportProgress):
self._status = STATUS.COPYING_DISK
logging.info("Job %r copying disk %d/%d",
self._id, event.current_disk, event.disk_count)
self._disk_progress = 0
self._current_disk = event.current_disk
self._disk_count = event.disk_count
self._description = event.description
elif isinstance(event, DiskProgress):
self._disk_progress = event.progress
if event.progress % 10 == 0:
logging.info("Job %r copy disk %d progress %d/100",
self._id, self._current_disk, event.progress)
else:
raise RuntimeError("Job %r got unexpected parser event: %s" %
(self._id, event))
def abort(self):
self._status = STATUS.ABORTED
logging.info('Job %r aborting...', self._id)
self._abort()
def _abort(self):
self._aborted = True
if self._proc is None:
logging.warning(
'Ignoring request to abort job %r; the job failed to start',
self._id)
return
if self._proc.returncode is None:
logging.debug('Job %r killing virt-v2v process', self._id)
try:
self._proc.kill()
except OSError as e:
if e.errno != errno.ESRCH:
raise
logging.debug('Job %r virt-v2v process not running',
self._id)
else:
logging.debug('Job %r virt-v2v process was killed',
self._id)
finally:
for pid in self._proc.pids:
zombiereaper.autoReapPID(pid)
class OutputParser(object):
COPY_DISK_RE = re.compile(r'.*(Copying disk (\d+)/(\d+)).*')
DISK_PROGRESS_RE = re.compile(r'\s+\((\d+).*')
def parse(self, stream):
for line in stream:
if 'Copying disk' in line:
description, current_disk, disk_count = self._parse_line(line)
yield ImportProgress(int(current_disk), int(disk_count),
description)
for chunk in self._iter_progress(stream):
progress = self._parse_progress(chunk)
if progress is not None:
yield DiskProgress(progress)
if progress == 100:
break
def _parse_line(self, line):
m = self.COPY_DISK_RE.match(line)
if m is None:
raise OutputParserError('unexpected format in "Copying disk"'
', line: %r' % line)
return m.group(1), m.group(2), m.group(3)
def _iter_progress(self, stream):
chunk = ''
while True:
c = stream.read(1)
if not c:
raise OutputParserError('copy-disk stream closed unexpectedly')
chunk += c
if c == '\r':
yield chunk
chunk = ''
def _parse_progress(self, chunk):
m = self.DISK_PROGRESS_RE.match(chunk)
if m is None:
return None
try:
return int(m.group(1))
except ValueError:
raise OutputParserError('error parsing progress regex: %r'
% m.groups)
def _mem_to_mib(size, unit):
lunit = unit.lower()
if lunit in ('bytes', 'b'):
return size / 1024 / 1024
elif lunit in ('kib', 'k'):
return size / 1024
elif lunit in ('mib', 'm'):
return size
elif lunit in ('gib', 'g'):
return size * 1024
elif lunit in ('tib', 't'):
return size * 1024 * 1024
else:
raise InvalidVMConfiguration("Invalid currentMemory unit attribute:"
" %r" % unit)
def _list_domains(conn):
try:
for vm in conn.listAllDomains():
yield vm
# TODO: use only the new API (no need to fall back to listDefinedDomains)
# when supported in Xen under RHEL 5.x
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_NO_SUPPORT:
raise
# Support for old libvirt clients
seen = set()
for name in conn.listDefinedDomains():
try:
vm = conn.lookupByName(name)
except libvirt.libvirtError as e:
logging.error("Error looking up vm %r: %s", name, e)
else:
seen.add(name)
yield vm
for domainId in conn.listDomainsID():
try:
vm = conn.lookupByID(domainId)
except libvirt.libvirtError as e:
logging.error("Error looking up vm by id %r: %s", domainId, e)
else:
if vm.name() not in seen:
yield vm
def _add_vm(conn, vms, vm):
params = {}
try:
_add_vm_info(vm, params)
except libvirt.libvirtError as e:
logging.error("error getting domain information: %s", e)
return
try:
xml = vm.XMLDesc(0)
except libvirt.libvirtError as e:
logging.error("error getting domain xml for vm %r: %s",
vm.name(), e)
return
try:
root = ET.fromstring(xml)
except ET.ParseError as e:
logging.error('error parsing domain xml: %s', e)
return
if not _block_disk_supported(conn, root):
return
try:
_add_general_info(root, params)
except InvalidVMConfiguration as e:
logging.error("error adding general info: %s", e)
return
_add_snapshot_info(conn, vm, params)
_add_networks(root, params)
_add_disks(root, params)
_add_graphics(root, params)
_add_video(root, params)
disk_info = None
for disk in params['disks']:
disk_info = _get_disk_info(conn, disk, vm)
if disk_info is None:
break
disk.update(disk_info)
if disk_info is not None:
vms.append(params)
else:
logging.warning('Cannot add VM %s due to disk storage error',
vm.name())
def _block_disk_supported(conn, root):
'''
Currently we do not support importing VMs with block device from
Xen on Rhel 5.x
'''
if conn.getType() == 'Xen':
block_disks = root.findall('.//disk[@type="block"]')
block_disks = [d for d in block_disks
if d.attrib.get('device', None) == "disk"]
return len(block_disks) == 0
return True
def _add_vm_info(vm, params):
params['vmName'] = vm.name()
# TODO: use new API: vm.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF
# when supported in Xen under RHEL 5.x
if vm.isActive():
params['status'] = "Up"
else:
params['status'] = "Down"
def _add_general_info(root, params):
e = root.find('./uuid')
if e is not None:
params['vmId'] = e.text
e = root.find('./currentMemory')
if e is not None:
try:
size = int(e.text)
except ValueError:
raise InvalidVMConfiguration("Invalid 'currentMemory' value: %r"
% e.text)
unit = e.get('unit', 'KiB')
params['memSize'] = _mem_to_mib(size, unit)
e = root.find('./vcpu')
if e is not None:
try:
params['smp'] = int(e.text)
except ValueError:
raise InvalidVMConfiguration("Invalid 'vcpu' value: %r" % e.text)
e = root.find('./os/type/[@arch]')
if e is not None:
params['arch'] = e.get('arch')
def _get_disk_info(conn, disk, vm):
if 'alias' in disk.keys():
try:
if disk['disktype'] == 'file':
vol = conn.storageVolLookupByPath(disk['alias'])
_, capacity, alloc = vol.info()
elif disk['disktype'] == 'block':
vol = vm.blockInfo(disk['alias'])
# We use the physical for allocation
# in blockInfo can report 0
capacity, _, alloc = vol
else:
logging.error('Unsupported disk type: %r', disk['disktype'])
except libvirt.libvirtError:
logging.exception("Error getting disk size")
return None
else:
return {'capacity': str(capacity), 'allocation': str(alloc)}
return {}
def _convert_disk_format(format):
# TODO: move to volume format when storage/volume.py
# will be accessible for /lib/vdsm/v2v.py
if format == 'qcow2':
return 'COW'
elif format == 'raw':
return 'RAW'
raise KeyError
def _add_disks(root, params):
params['disks'] = []
disks = root.findall('.//disk[@type="file"]')
disks = disks + root.findall('.//disk[@type="block"]')
for disk in disks:
d = {}
disktype = disk.get('type')
device = disk.get('device')
if device is not None:
if device == 'cdrom':
# Skip CD-ROM drives
continue
d['type'] = device
target = disk.find('./target/[@dev]')
if target is not None:
d['dev'] = target.get('dev')
if disktype == 'file':
d['disktype'] = 'file'
source = disk.find('./source/[@file]')
if source is not None:
d['alias'] = source.get('file')
elif disktype == 'block':
d['disktype'] = 'block'
source = disk.find('./source/[@dev]')
if source is not None:
d['alias'] = source.get('dev')
else:
logging.error('Unsupported disk type: %r', type)
driver = disk.find('./driver/[@type]')
if driver is not None:
try:
d["format"] = _convert_disk_format(driver.get('type'))
except KeyError:
logging.warning("Disk %s has unsupported format: %r", d,
format)
params['disks'].append(d)
def _add_graphics(root, params):
e = root.find('./devices/graphics/[@type]')
if e is not None:
params['graphics'] = e.get('type')
def _add_video(root, params):
e = root.find('./devices/video/model/[@type]')
if e is not None:
params['video'] = e.get('type')
def _add_networks(root, params):
params['networks'] = []
interfaces = root.findall('.//interface')
for iface in interfaces:
i = {}
if 'type' in iface.attrib:
i['type'] = iface.attrib['type']
mac = iface.find('./mac/[@address]')
if mac is not None:
i['macAddr'] = mac.get('address')
source = iface.find('./source/[@bridge]')
if source is not None:
i['bridge'] = source.get('bridge')
target = iface.find('./target/[@dev]')
if target is not None:
i['dev'] = target.get('dev')
model = iface.find('./model/[@type]')
if model is not None:
i['model'] = model.get('type')
params['networks'].append(i)
def _add_snapshot_info(conn, vm, params):
# Snapshot related API is not yet implemented in the libvirt's Xen driver
if conn.getType() == 'Xen':
return
try:
ret = vm.hasCurrentSnapshot()
except libvirt.libvirtError:
logging.exception('Error checking for existing snapshots.')
else:
params['has_snapshots'] = ret > 0
def _vm_has_snapshot(vm):
try:
return vm.hasCurrentSnapshot() == 1
except libvirt.libvirtError:
logging.exception('Error checking if snapshot exist for vm: %s.',
vm.name())
return False
def _read_ovf_from_ova(ova_path):
"""
virt-v2v support ova in tar, zip formats as well as
extracted directory
"""
if os.path.isdir(ova_path):
return _read_ovf_from_ova_dir(ova_path)
elif zipfile.is_zipfile(ova_path):
return _read_ovf_from_zip_ova(ova_path)
elif tarfile.is_tarfile(ova_path):
return _read_ovf_from_tar_ova(ova_path)
raise ClientError('Unknown ova format, supported formats:'
' tar, zip or a directory')
def _find_ovf(entries):
for entry in entries:
if '.ovf' == os.path.splitext(entry)[1].lower():
return entry
return None
def _read_ovf_from_ova_dir(ova_path):
files = os.listdir(ova_path)
name = _find_ovf(files)
if name is not None:
with open(os.path.join(ova_path, name), 'r') as ovf_file:
return ovf_file.read()
raise ClientError('OVA directory %s does not contain ovf file' % ova_path)
def _read_ovf_from_zip_ova(ova_path):
with open(ova_path, 'rb') as fh:
zf = zipfile.ZipFile(fh)
name = _find_ovf(zf.namelist())
if name is not None:
return zf.read(name)
raise ClientError('OVA does not contains file with .ovf suffix')
def _read_ovf_from_tar_ova(ova_path):
with tarfile.open(ova_path) as tar:
for member in tar:
if member.name.endswith('.ovf'):
with closing(tar.extractfile(member)) as ovf:
return ovf.read()
raise ClientError('OVA does not contains file with .ovf suffix')
def _add_general_ovf_info(vm, node, ns, ova_path):
vm['status'] = 'Down'
vmName = node.find('./ovf:VirtualSystem/ovf:Name', ns)
if vmName is not None:
vm['vmName'] = vmName.text
else:
vm['vmName'] = os.path.splitext(os.path.basename(ova_path))[0]
memSize = node.find('.//ovf:Item[rasd:ResourceType="%d"]/'
'rasd:VirtualQuantity' % _OVF_RESOURCE_MEMORY, ns)
if memSize is not None:
vm['memSize'] = int(memSize.text)
else:
raise V2VError('Error parsing ovf information: no memory size')
smp = node.find('.//ovf:Item[rasd:ResourceType="%d"]/'
'rasd:VirtualQuantity' % _OVF_RESOURCE_CPU, ns)
if smp is not None:
vm['smp'] = int(smp.text)
else:
raise V2VError('Error parsing ovf information: no cpu info')
def _get_max_disk_size(populated_size, size):
if populated_size is None:
return size
if size is None:
return populated_size
return str(max(int(populated_size), int(size)))
def _parse_allocation_units(units):
"""
Parse allocation units of the form "bytes * x * y^z"
The format is defined in:
DSP0004: Common Information Model (CIM) Infrastructure,
ANNEX C.1 Programmatic Units
We conform only to the subset of the format specification and
base-units must be bytes.
"""
# Format description
sp = '[ \t\n]?'
base_unit = 'byte'
operator = '[*]' # we support only multiplication
number = '[+]?[0-9]+' # we support only positive integers
exponent = '[+]?[0-9]+' # we support only positive integers
modifier1 = '(?P<m1>{op}{sp}(?P<m1_num>{num}))'.format(
op=operator,
num=number,
sp=sp)
modifier2 = \
'(?P<m2>{op}{sp}' \
'(?P<m2_base>[0-9]+){sp}\^{sp}(?P<m2_exp>{exp}))'.format(
op=operator,
exp=exponent,
sp=sp)
r = '^{base_unit}({sp}{mod1})?({sp}{mod2})?$'.format(
base_unit=base_unit,
mod1=modifier1,
mod2=modifier2,
sp=sp)
m = re.match(r, units, re.MULTILINE)
if m is None:
raise V2VError('Failed to parse allocation units: %r' % units)
g = m.groupdict()
ret = 1
if g['m1'] is not None:
try:
ret *= int(g['m1_num'])
except ValueError:
raise V2VError("Failed to parse allocation units: %r" % units)
if g['m2'] is not None:
try:
ret *= pow(int(g['m2_base']), int(g['m2_exp']))
except ValueError:
raise V2VError("Failed to parse allocation units: %r" % units)
return ret
def _add_disks_ovf_info(vm, node, ns):
vm['disks'] = []
for d in node.findall(".//ovf:DiskSection/ovf:Disk", ns):
disk = {'type': 'disk'}
capacity = int(d.attrib.get('{%s}capacity' % _OVF_NS))
if '{%s}capacityAllocationUnits' % _OVF_NS in d.attrib:
units = d.attrib.get('{%s}capacityAllocationUnits' % _OVF_NS)
capacity *= _parse_allocation_units(units)
disk['capacity'] = str(capacity)
fileref = d.attrib.get('{%s}fileRef' % _OVF_NS)
alias = node.find('.//ovf:References/ovf:File[@ovf:id="%s"]' %
fileref, ns)
if alias is not None:
disk['alias'] = alias.attrib.get('{%s}href' % _OVF_NS)
populated_size = d.attrib.get('{%s}populatedSize' % _OVF_NS, None)
size = alias.attrib.get('{%s}size' % _OVF_NS)
disk['allocation'] = _get_max_disk_size(populated_size, size)
else:
raise V2VError('Error parsing ovf information: disk href info')
vm['disks'].append(disk)
def _add_networks_ovf_info(vm, node, ns):
vm['networks'] = []
for n in node.findall('.//ovf:Item[rasd:ResourceType="%d"]'
% _OVF_RESOURCE_NETWORK, ns):
net = {}
dev = n.find('./rasd:ElementName', ns)
if dev is not None:
net['dev'] = dev.text
else:
raise V2VError('Error parsing ovf information: '
'network element name')
model = n.find('./rasd:ResourceSubType', ns)
if model is not None:
net['model'] = model.text
else:
raise V2VError('Error parsing ovf information: network model')
bridge = n.find('./rasd:Connection', ns)
if bridge is not None:
net['bridge'] = bridge.text
net['type'] = 'bridge'
else:
net['type'] = 'interface'
vm['networks'].append(net)
def _simple_exec_cmd(command, env=None, nice=None, ioclass=None,
stdin=None, stdout=None, stderr=None):
command = wrap_command(command, with_ioclass=ioclass,
ioclassdata=None, with_nice=nice,
with_setsid=False, with_sudo=False,
reset_cpu_affinity=True)
logging.debug(cmdutils.command_log_line(command, cwd=None))
p = CPopen(command, close_fds=True, cwd=None, env=env,
stdin=stdin, stdout=stdout, stderr=stderr)
return p
| EdDev/vdsm | lib/vdsm/v2v.py | Python | gpl-2.0 | 48,122 |
<?php
/**
* @file
* Template page for a promotion item.
*/
?>
<h2>
<a href="<?php print $item_url ?>"><?php print $title ?></a>
</h2>
<p><?php print t('Valid till'); ?> <?php print $cashingPeriodEnd ?> <?php print ($unlimited ? t('unlimited') : $unitsLeft . ' ' . t('x in stock')); ?></p>
<?php if (!empty($picture_url)): ?>
<p>
<img style="float: right;" width="100" src="<?php print $picture_url; ?>" />
<span><?php print $real_points ?></span>
</p>
<?php endif; ?>
| westtoer/intranet.westtoer.be | modules/culturefeed/culturefeed_userpoints_ui/theme/culturefeed-userpoints-ui-promotions-page-item.tpl.php | PHP | gpl-2.0 | 482 |
using System;
namespace Server.Items
{
public class ArachnidDoom : BaseInstrument
{
[Constructable]
public ArachnidDoom()
: base(0x0EB3)
{
RandomInstrument();
this.Hue = 1944;
this.Weight = 4;
this.Slayer = SlayerName.ArachnidDoom;
}
public ArachnidDoom(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1154724;
}
}// Arachnid Doom
public override int InitMinUses
{
get
{
return 450;
}
}
public override int InitMaxUses
{
get
{
return 450;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | tbewley10310/Land-of-Archon | Scripts/Services/CleanUpBritannia/Items/ArachnidDoom.cs | C# | gpl-2.0 | 1,190 |
<?php
/**
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();
/**
* Class syntax_plugin_data_entry
*/
class syntax_plugin_data_entry extends DokuWiki_Syntax_Plugin {
/**
* @var helper_plugin_data will hold the data helper plugin
*/
var $dthlp = null;
/**
* Constructor. Load helper plugin
*/
function __construct() {
$this->dthlp = plugin_load('helper', 'data');
if(!$this->dthlp) msg('Loading the data helper failed. Make sure the data plugin is installed.', -1);
}
/**
* What kind of syntax are we?
*/
function getType() {
return 'substition';
}
/**
* What about paragraphs?
*/
function getPType() {
return 'block';
}
/**
* Where to sort in?
*/
function getSort() {
return 155;
}
/**
* Connect pattern to lexer
*/
function connectTo($mode) {
$this->Lexer->addSpecialPattern('----+ *dataentry(?: [ a-zA-Z0-9_]*)?-+\n.*?\n----+', $mode, 'plugin_data_entry');
}
/**
* Handle the match - parse the data
*
* @param string $match The text matched by the patterns
* @param int $state The lexer state for the match
* @param int $pos The character position of the matched text
* @param Doku_Handler $handler The Doku_Handler object
* @return bool|array Return an array with all data you want to use in render, false don't add an instruction
*/
function handle($match, $state, $pos, Doku_Handler $handler) {
if(!$this->dthlp->ready()) return null;
// get lines
$lines = explode("\n", $match);
array_pop($lines);
$class = array_shift($lines);
$class = str_replace('dataentry', '', $class);
$class = trim($class, '- ');
// parse info
$data = array();
$columns = array();
foreach($lines as $line) {
// ignore comments
preg_match('/^(.*?(?<![&\\\\]))(?:#(.*))?$/', $line, $matches);
$line = $matches[1];
$line = str_replace('\\#', '#', $line);
$line = trim($line);
if(empty($line)) continue;
$line = preg_split('/\s*:\s*/', $line, 2);
$column = $this->dthlp->_column($line[0]);
if(isset($matches[2])) {
$column['comment'] = $matches[2];
}
if($column['multi']) {
if(!isset($data[$column['key']])) {
// init with empty array
// Note that multiple occurrences of the field are
// practically merged
$data[$column['key']] = array();
}
$vals = explode(',', $line[1]);
foreach($vals as $val) {
$val = trim($this->dthlp->_cleanData($val, $column['type']));
if($val == '') continue;
if(!in_array($val, $data[$column['key']])) {
$data[$column['key']][] = $val;
}
}
} else {
$data[$column['key']] = $this->dthlp->_cleanData($line[1], $column['type']);
}
$columns[$column['key']] = $column;
}
return array(
'data' => $data, 'cols' => $columns, 'classes' => $class,
'pos' => $pos, 'len' => strlen($match)
); // not utf8_strlen
}
/**
* Create output or save the data
*
* @param $format string output format being rendered
* @param $renderer Doku_Renderer the current renderer object
* @param $data array data created by handler()
* @return boolean rendered correctly?
*/
function render($format, Doku_Renderer $renderer, $data) {
if(is_null($data)) return false;
if(!$this->dthlp->ready()) return false;
global $ID;
switch($format) {
case 'xhtml':
/** @var $renderer Doku_Renderer_xhtml */
$this->_showData($data, $renderer);
return true;
case 'metadata':
/** @var $renderer Doku_Renderer_metadata */
$this->_saveData($data, $ID, $renderer->meta['title']);
return true;
case 'plugin_data_edit':
/** @var $renderer Doku_Renderer_plugin_data_edit */
$this->_editData($data, $renderer);
return true;
default:
return false;
}
}
/**
* Output the data in a table
*
* @param array $data
* @param Doku_Renderer_xhtml $R
*/
function _showData($data, $R) {
global $ID;
$ret = '';
$sectionEditData = ['target' => 'plugin_data'];
if (!defined('SEC_EDIT_PATTERN')) {
// backwards-compatibility for Frusterick Manners (2017-02-19)
$sectionEditData = 'plugin_data';
}
$data['classes'] .= ' ' . $R->startSectionEdit($data['pos'], $sectionEditData);
$ret .= '<div class="inline dataplugin_entry ' . $data['classes'] . '"><dl>';
$class_names = array();
foreach($data['data'] as $key => $val) {
if($val == '' || !count($val)) continue;
$type = $data['cols'][$key]['type'];
if(is_array($type)) {
$type = $type['type'];
}
if($type === 'hidden') continue;
$class_name = hsc(sectionID($key, $class_names));
$ret .= '<dt class="' . $class_name . '">' . hsc($data['cols'][$key]['title']) . '<span class="sep">: </span></dt>';
$ret .= '<dd class="' . $class_name . '">';
if(is_array($val)) {
$cnt = count($val);
for($i = 0; $i < $cnt; $i++) {
switch($type) {
case 'wiki':
$val[$i] = $ID . '|' . $val[$i];
break;
}
$ret .= $this->dthlp->_formatData($data['cols'][$key], $val[$i], $R);
if($i < $cnt - 1) {
$ret .= '<span class="sep">, </span>';
}
}
} else {
switch($type) {
case 'wiki':
$val = $ID . '|' . $val;
break;
}
$ret .= $this->dthlp->_formatData($data['cols'][$key], $val, $R);
}
$ret .= '</dd>';
}
$ret .= '</dl></div>';
$R->doc .= $ret;
$R->finishSectionEdit($data['len'] + $data['pos']);
}
/**
* Save date to the database
*/
function _saveData($data, $id, $title) {
$sqlite = $this->dthlp->_getDB();
if(!$sqlite) return false;
if(!$title) {
$title = $id;
}
$class = $data['classes'];
// begin transaction
$sqlite->query("BEGIN TRANSACTION");
// store page info
$this->replaceQuery(
"INSERT OR IGNORE INTO pages (page,title,class) VALUES (?,?,?)",
$id, $title, $class
);
// Update title if insert failed (record already saved before)
$revision = filemtime(wikiFN($id));
$this->replaceQuery(
"UPDATE pages SET title = ?, class = ?, lastmod = ? WHERE page = ?",
$title, $class, $revision, $id
);
// fetch page id
$res = $this->replaceQuery("SELECT pid FROM pages WHERE page = ?", $id);
$pid = (int) $sqlite->res2single($res);
$sqlite->res_close($res);
if(!$pid) {
msg("data plugin: failed saving data", -1);
$sqlite->query("ROLLBACK TRANSACTION");
return false;
}
// remove old data
$sqlite->query("DELETE FROM DATA WHERE pid = ?", $pid);
// insert new data
foreach($data['data'] as $key => $val) {
if(is_array($val)) foreach($val as $v) {
$this->replaceQuery(
"INSERT INTO DATA (pid, KEY, VALUE) VALUES (?, ?, ?)",
$pid, $key, $v
);
} else {
$this->replaceQuery(
"INSERT INTO DATA (pid, KEY, VALUE) VALUES (?, ?, ?)",
$pid, $key, $val
);
}
}
// finish transaction
$sqlite->query("COMMIT TRANSACTION");
return true;
}
/**
* @return bool|mixed
*/
function replaceQuery() {
$args = func_get_args();
$argc = func_num_args();
if($argc > 1) {
for($i = 1; $i < $argc; $i++) {
$data = array();
$data['sql'] = $args[$i];
$this->dthlp->_replacePlaceholdersInSQL($data);
$args[$i] = $data['sql'];
}
}
$sqlite = $this->dthlp->_getDB();
if(!$sqlite) return false;
return call_user_func_array(array(&$sqlite, 'query'), $args);
}
/**
* The custom editor for editing data entries
*
* Gets called from action_plugin_data::_editform() where also the form member is attached
*
* @param array $data
* @param Doku_Renderer_plugin_data_edit $renderer
*/
function _editData($data, &$renderer) {
$renderer->form->startFieldset($this->getLang('dataentry'));
$renderer->form->_content[count($renderer->form->_content) - 1]['class'] = 'plugin__data';
$renderer->form->addHidden('range', '0-0'); // Adora Belle bugfix
if($this->getConf('edit_content_only')) {
$renderer->form->addHidden('data_edit[classes]', $data['classes']);
$columns = array('title', 'value', 'comment');
$class = 'edit_content_only';
} else {
$renderer->form->addElement(form_makeField('text', 'data_edit[classes]', $data['classes'], $this->getLang('class'), 'data__classes'));
$columns = array('title', 'type', 'multi', 'value', 'comment');
$class = 'edit_all_content';
// New line
$data['data'][''] = '';
$data['cols'][''] = array('type' => '', 'multi' => false);
}
$renderer->form->addElement("<table class=\"$class\">");
//header
$header = '<tr>';
foreach($columns as $column) {
$header .= '<th class="' . $column . '">' . $this->getLang($column) . '</th>';
}
$header .= '</tr>';
$renderer->form->addElement($header);
//rows
$n = 0;
foreach($data['cols'] as $key => $vals) {
$fieldid = 'data_edit[data][' . $n++ . ']';
$content = $vals['multi'] ? implode(', ', $data['data'][$key]) : $data['data'][$key];
if(is_array($vals['type'])) {
$vals['basetype'] = $vals['type']['type'];
if(isset($vals['type']['enum'])) {
$vals['enum'] = $vals['type']['enum'];
}
$vals['type'] = $vals['origtype'];
} else {
$vals['basetype'] = $vals['type'];
}
if($vals['type'] === 'hidden') {
$renderer->form->addElement('<tr class="hidden">');
} else {
$renderer->form->addElement('<tr>');
}
if($this->getConf('edit_content_only')) {
if(isset($vals['enum'])) {
$values = preg_split('/\s*,\s*/', $vals['enum']);
if(!$vals['multi']) {
array_unshift($values, '');
}
$content = form_makeListboxField(
$fieldid . '[value][]',
$values,
$data['data'][$key],
$vals['title'],
'', '',
($vals['multi'] ? array('multiple' => 'multiple') : array())
);
} else {
$classes = 'data_type_' . $vals['type'] . ($vals['multi'] ? 's' : '') . ' '
. 'data_type_' . $vals['basetype'] . ($vals['multi'] ? 's' : '');
$attr = array();
if($vals['basetype'] == 'date' && !$vals['multi']) {
$attr['class'] = 'datepicker';
}
$content = form_makeField('text', $fieldid . '[value]', $content, $vals['title'], '', $classes, $attr);
}
$cells = array(
hsc($vals['title']) . ':',
$content,
'<span title="' . hsc($vals['comment']) . '">' . hsc($vals['comment']) . '</span>'
);
foreach(array('multi', 'comment', 'type') as $field) {
$renderer->form->addHidden($fieldid . "[$field]", $vals[$field]);
}
$renderer->form->addHidden($fieldid . "[title]", $vals['origkey']); //keep key as key, even if title is translated
} else {
$check_data = $vals['multi'] ? array('checked' => 'checked') : array();
$cells = array(
form_makeField('text', $fieldid . '[title]', $vals['origkey'], $this->getLang('title')), // when editable, always use the pure key, not a title
form_makeMenuField(
$fieldid . '[type]',
array_merge(
array(
'', 'page', 'nspage', 'title',
'img', 'mail', 'url', 'tag', 'wiki', 'dt', 'hidden'
),
array_keys($this->dthlp->_aliases())
),
$vals['type'],
$this->getLang('type')
),
form_makeCheckboxField($fieldid . '[multi]', array('1', ''), $this->getLang('multi'), '', '', $check_data),
form_makeField('text', $fieldid . '[value]', $content, $this->getLang('value')),
form_makeField('text', $fieldid . '[comment]', $vals['comment'], $this->getLang('comment'), '', 'data_comment', array('readonly' => 1, 'title' => $vals['comment']))
);
}
foreach($cells as $index => $cell) {
$renderer->form->addElement("<td class=\"{$columns[$index]}\">");
$renderer->form->addElement($cell);
$renderer->form->addElement('</td>');
}
$renderer->form->addElement('</tr>');
}
$renderer->form->addElement('</table>');
$renderer->form->endFieldset();
}
/**
* Escapes the given value against being handled as comment
*
* @todo bad naming
* @param $txt
* @return mixed
*/
public static function _normalize($txt) {
return str_replace('#', '\#', trim($txt));
}
/**
* Handles the data posted from the editor to recreate the entry syntax
*
* @param array $data data given via POST
* @return string
*/
public static function editToWiki($data) {
$nudata = array();
$len = 0; // we check the maximum lenght for nice alignment later
foreach($data['data'] as $field) {
if(is_array($field['value'])) {
$field['value'] = join(', ', $field['value']);
}
$field = array_map('trim', $field);
if($field['title'] === '') continue;
$name = syntax_plugin_data_entry::_normalize($field['title']);
if($field['type'] !== '') {
$name .= '_' . syntax_plugin_data_entry::_normalize($field['type']);
} elseif(substr($name, -1, 1) === 's') {
$name .= '_'; // when the field name ends in 's' we need to secure it against being assumed as multi
}
// 's' is added to either type or name for multi
if($field['multi'] === '1') {
$name .= 's';
}
$nudata[] = array($name, syntax_plugin_data_entry::_normalize($field['value']), $field['comment']);
$len = max($len, utf8_strlen($nudata[count($nudata) - 1][0]));
}
$ret = '---- dataentry ' . trim($data['classes']) . ' ----' . DOKU_LF;
foreach($nudata as $field) {
$ret .= $field[0] . str_repeat(' ', $len + 1 - utf8_strlen($field[0])) . ': ';
$ret .= $field[1];
if($field[2] !== '') {
$ret .= ' # ' . $field[2];
}
$ret .= DOKU_LF;
}
$ret .= "----\n";
return $ret;
}
}
| tsolucio/coreBOSDocumentation | lib/plugins/data/syntax/entry.php | PHP | gpl-2.0 | 17,100 |
/*****************************************************************************
Copyright (c) 2005, 2014, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2012, Facebook 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; 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 page/page0zip.cc
Compressed page interface
Created June 2005 by Marko Makela
*******************************************************/
// First include (the generated) my_config.h, to get correct platform defines.
#include "my_config.h"
#include <map>
using namespace std;
#define THIS_MODULE
#include "page0zip.h"
#ifdef UNIV_NONINL
# include "page0zip.ic"
#endif
#undef THIS_MODULE
#include "page0page.h"
#include "mtr0log.h"
#include "ut0sort.h"
#include "dict0dict.h"
#include "btr0cur.h"
#include "page0types.h"
#include "log0recv.h"
#ifndef UNIV_HOTBACKUP
# include "buf0buf.h"
# include "buf0lru.h"
# include "btr0sea.h"
# include "dict0boot.h"
# include "lock0lock.h"
# include "srv0mon.h"
# include "srv0srv.h"
# include "ut0crc32.h"
#else /* !UNIV_HOTBACKUP */
# include "buf0checksum.h"
# define lock_move_reorganize_page(block, temp_block) ((void) 0)
# define buf_LRU_stat_inc_unzip() ((void) 0)
#endif /* !UNIV_HOTBACKUP */
#include "blind_fwrite.h"
#ifndef UNIV_HOTBACKUP
/** Statistics on compression, indexed by page_zip_des_t::ssize - 1 */
UNIV_INTERN page_zip_stat_t page_zip_stat[PAGE_ZIP_SSIZE_MAX];
/** Statistics on compression, indexed by index->id */
UNIV_INTERN page_zip_stat_per_index_t page_zip_stat_per_index;
/** Mutex protecting page_zip_stat_per_index */
UNIV_INTERN ib_mutex_t page_zip_stat_per_index_mutex;
#ifdef HAVE_PSI_INTERFACE
UNIV_INTERN mysql_pfs_key_t page_zip_stat_per_index_mutex_key;
#endif /* HAVE_PSI_INTERFACE */
#endif /* !UNIV_HOTBACKUP */
/* Compression level to be used by zlib. Settable by user. */
UNIV_INTERN uint page_zip_level = DEFAULT_COMPRESSION_LEVEL;
/* Whether or not to log compressed page images to avoid possible
compression algorithm changes in zlib. */
UNIV_INTERN my_bool page_zip_log_pages = false;
/* Please refer to ../include/page0zip.ic for a description of the
compressed page format. */
/* The infimum and supremum records are omitted from the compressed page.
On compress, we compare that the records are there, and on uncompress we
restore the records. */
/** Extra bytes of an infimum record */
static const byte infimum_extra[] = {
0x01, /* info_bits=0, n_owned=1 */
0x00, 0x02 /* heap_no=0, status=2 */
/* ?, ? */ /* next=(first user rec, or supremum) */
};
/** Data bytes of an infimum record */
static const byte infimum_data[] = {
0x69, 0x6e, 0x66, 0x69,
0x6d, 0x75, 0x6d, 0x00 /* "infimum\0" */
};
/** Extra bytes and data bytes of a supremum record */
static const byte supremum_extra_data[] = {
/* 0x0?, */ /* info_bits=0, n_owned=1..8 */
0x00, 0x0b, /* heap_no=1, status=3 */
0x00, 0x00, /* next=0 */
0x73, 0x75, 0x70, 0x72,
0x65, 0x6d, 0x75, 0x6d /* "supremum" */
};
/** Assert that a block of memory is filled with zero bytes.
Compare at most sizeof(field_ref_zero) bytes.
@param b in: memory block
@param s in: size of the memory block, in bytes */
#define ASSERT_ZERO(b, s) \
ut_ad(!memcmp(b, field_ref_zero, ut_min(s, sizeof field_ref_zero)))
/** Assert that a BLOB pointer is filled with zero bytes.
@param b in: BLOB pointer */
#define ASSERT_ZERO_BLOB(b) \
ut_ad(!memcmp(b, field_ref_zero, sizeof field_ref_zero))
/* Enable some extra debugging output. This code can be enabled
independently of any UNIV_ debugging conditions. */
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
# include <stdarg.h>
__attribute__((format (printf, 1, 2)))
/**********************************************************************//**
Report a failure to decompress or compress.
@return number of characters printed */
static
int
page_zip_fail_func(
/*===============*/
const char* fmt, /*!< in: printf(3) format string */
...) /*!< in: arguments corresponding to fmt */
{
int res;
va_list ap;
ut_print_timestamp(stderr);
fputs(" InnoDB: ", stderr);
va_start(ap, fmt);
res = vfprintf(stderr, fmt, ap);
va_end(ap);
return(res);
}
/** Wrapper for page_zip_fail_func()
@param fmt_args in: printf(3) format string and arguments */
# define page_zip_fail(fmt_args) page_zip_fail_func fmt_args
#else /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
/** Dummy wrapper for page_zip_fail_func()
@param fmt_args ignored: printf(3) format string and arguments */
# define page_zip_fail(fmt_args) /* empty */
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
#ifndef UNIV_HOTBACKUP
/**********************************************************************//**
Determine the guaranteed free space on an empty page.
@return minimum payload size on the page */
UNIV_INTERN
ulint
page_zip_empty_size(
/*================*/
ulint n_fields, /*!< in: number of columns in the index */
ulint zip_size) /*!< in: compressed page size in bytes */
{
lint size = zip_size
/* subtract the page header and the longest
uncompressed data needed for one record */
- (PAGE_DATA
+ PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN
+ 1/* encoded heap_no==2 in page_zip_write_rec() */
+ 1/* end of modification log */
- REC_N_NEW_EXTRA_BYTES/* omitted bytes */)
/* subtract the space for page_zip_fields_encode() */
- compressBound(static_cast<uLong>(2 * (n_fields + 1)));
return(size > 0 ? (ulint) size : 0);
}
#endif /* !UNIV_HOTBACKUP */
/*************************************************************//**
Gets the number of elements in the dense page directory,
including deleted records (the free list).
@return number of elements in the dense page directory */
UNIV_INLINE
ulint
page_zip_dir_elems(
/*===============*/
const page_zip_des_t* page_zip) /*!< in: compressed page */
{
/* Exclude the page infimum and supremum from the record count. */
return(page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW);
}
/*************************************************************//**
Gets the size of the compressed page trailer (the dense page directory),
including deleted records (the free list).
@return length of dense page directory, in bytes */
UNIV_INLINE
ulint
page_zip_dir_size(
/*==============*/
const page_zip_des_t* page_zip) /*!< in: compressed page */
{
return(PAGE_ZIP_DIR_SLOT_SIZE * page_zip_dir_elems(page_zip));
}
/*************************************************************//**
Gets an offset to the compressed page trailer (the dense page directory),
including deleted records (the free list).
@return offset of the dense page directory */
UNIV_INLINE
ulint
page_zip_dir_start_offs(
/*====================*/
const page_zip_des_t* page_zip, /*!< in: compressed page */
ulint n_dense) /*!< in: directory size */
{
ut_ad(n_dense * PAGE_ZIP_DIR_SLOT_SIZE < page_zip_get_size(page_zip));
return(page_zip_get_size(page_zip) - n_dense * PAGE_ZIP_DIR_SLOT_SIZE);
}
/*************************************************************//**
Gets a pointer to the compressed page trailer (the dense page directory),
including deleted records (the free list).
@param[in] page_zip compressed page
@param[in] n_dense number of entries in the directory
@return pointer to the dense page directory */
#define page_zip_dir_start_low(page_zip, n_dense) \
((page_zip)->data + page_zip_dir_start_offs(page_zip, n_dense))
/*************************************************************//**
Gets a pointer to the compressed page trailer (the dense page directory),
including deleted records (the free list).
@param[in] page_zip compressed page
@return pointer to the dense page directory */
#define page_zip_dir_start(page_zip) \
page_zip_dir_start_low(page_zip, page_zip_dir_elems(page_zip))
/*************************************************************//**
Gets the size of the compressed page trailer (the dense page directory),
only including user records (excluding the free list).
@return length of dense page directory comprising existing records, in bytes */
UNIV_INLINE
ulint
page_zip_dir_user_size(
/*===================*/
const page_zip_des_t* page_zip) /*!< in: compressed page */
{
ulint size = PAGE_ZIP_DIR_SLOT_SIZE
* page_get_n_recs(page_zip->data);
ut_ad(size <= page_zip_dir_size(page_zip));
return(size);
}
/*************************************************************//**
Find the slot of the given record in the dense page directory.
@return dense directory slot, or NULL if record not found */
UNIV_INLINE
byte*
page_zip_dir_find_low(
/*==================*/
byte* slot, /*!< in: start of records */
byte* end, /*!< in: end of records */
ulint offset) /*!< in: offset of user record */
{
ut_ad(slot <= end);
for (; slot < end; slot += PAGE_ZIP_DIR_SLOT_SIZE) {
if ((mach_read_from_2(slot) & PAGE_ZIP_DIR_SLOT_MASK)
== offset) {
return(slot);
}
}
return(NULL);
}
/*************************************************************//**
Find the slot of the given non-free record in the dense page directory.
@return dense directory slot, or NULL if record not found */
UNIV_INLINE
byte*
page_zip_dir_find(
/*==============*/
page_zip_des_t* page_zip, /*!< in: compressed page */
ulint offset) /*!< in: offset of user record */
{
byte* end = page_zip->data + page_zip_get_size(page_zip);
ut_ad(page_zip_simple_validate(page_zip));
return(page_zip_dir_find_low(end - page_zip_dir_user_size(page_zip),
end,
offset));
}
/*************************************************************//**
Find the slot of the given free record in the dense page directory.
@return dense directory slot, or NULL if record not found */
UNIV_INLINE
byte*
page_zip_dir_find_free(
/*===================*/
page_zip_des_t* page_zip, /*!< in: compressed page */
ulint offset) /*!< in: offset of user record */
{
byte* end = page_zip->data + page_zip_get_size(page_zip);
ut_ad(page_zip_simple_validate(page_zip));
return(page_zip_dir_find_low(end - page_zip_dir_size(page_zip),
end - page_zip_dir_user_size(page_zip),
offset));
}
/*************************************************************//**
Read a given slot in the dense page directory.
@return record offset on the uncompressed page, possibly ORed with
PAGE_ZIP_DIR_SLOT_DEL or PAGE_ZIP_DIR_SLOT_OWNED */
UNIV_INLINE
ulint
page_zip_dir_get(
/*=============*/
const page_zip_des_t* page_zip, /*!< in: compressed page */
ulint slot) /*!< in: slot
(0=first user record) */
{
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(slot < page_zip_dir_size(page_zip) / PAGE_ZIP_DIR_SLOT_SIZE);
return(mach_read_from_2(page_zip->data + page_zip_get_size(page_zip)
- PAGE_ZIP_DIR_SLOT_SIZE * (slot + 1)));
}
#ifndef UNIV_HOTBACKUP
/**********************************************************************//**
Write a log record of compressing an index page. */
static
void
page_zip_compress_write_log(
/*========================*/
const page_zip_des_t* page_zip,/*!< in: compressed page */
const page_t* page, /*!< in: uncompressed page */
dict_index_t* index, /*!< in: index of the B-tree node */
mtr_t* mtr) /*!< in: mini-transaction */
{
byte* log_ptr;
ulint trailer_size;
ut_ad(!dict_index_is_ibuf(index));
log_ptr = mlog_open(mtr, 11 + 2 + 2);
if (!log_ptr) {
return;
}
/* Read the number of user records. */
trailer_size = page_dir_get_n_heap(page_zip->data)
- PAGE_HEAP_NO_USER_LOW;
/* Multiply by uncompressed of size stored per record */
if (!page_is_leaf(page)) {
trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE;
} else if (dict_index_is_clust(index)) {
trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
} else {
trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE;
}
/* Add the space occupied by BLOB pointers. */
trailer_size += page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
ut_a(page_zip->m_end > PAGE_DATA);
#if FIL_PAGE_DATA > PAGE_DATA
# error "FIL_PAGE_DATA > PAGE_DATA"
#endif
ut_a(page_zip->m_end + trailer_size <= page_zip_get_size(page_zip));
log_ptr = mlog_write_initial_log_record_fast((page_t*) page,
MLOG_ZIP_PAGE_COMPRESS,
log_ptr, mtr);
mach_write_to_2(log_ptr, page_zip->m_end - FIL_PAGE_TYPE);
log_ptr += 2;
mach_write_to_2(log_ptr, trailer_size);
log_ptr += 2;
mlog_close(mtr, log_ptr);
/* Write FIL_PAGE_PREV and FIL_PAGE_NEXT */
mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_PREV, 4);
mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_NEXT, 4);
/* Write most of the page header, the compressed stream and
the modification log. */
mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_TYPE,
page_zip->m_end - FIL_PAGE_TYPE);
/* Write the uncompressed trailer of the compressed page. */
mlog_catenate_string(mtr, page_zip->data + page_zip_get_size(page_zip)
- trailer_size, trailer_size);
}
#endif /* !UNIV_HOTBACKUP */
/******************************************************//**
Determine how many externally stored columns are contained
in existing records with smaller heap_no than rec. */
static
ulint
page_zip_get_n_prev_extern(
/*=======================*/
const page_zip_des_t* page_zip,/*!< in: dense page directory on
compressed page */
const rec_t* rec, /*!< in: compact physical record
on a B-tree leaf page */
const dict_index_t* index) /*!< in: record descriptor */
{
const page_t* page = page_align(rec);
ulint n_ext = 0;
ulint i;
ulint left;
ulint heap_no;
ulint n_recs = page_get_n_recs(page_zip->data);
ut_ad(page_is_leaf(page));
ut_ad(page_is_comp(page));
ut_ad(dict_table_is_comp(index->table));
ut_ad(dict_index_is_clust(index));
ut_ad(!dict_index_is_ibuf(index));
heap_no = rec_get_heap_no_new(rec);
ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW);
left = heap_no - PAGE_HEAP_NO_USER_LOW;
if (UNIV_UNLIKELY(!left)) {
return(0);
}
for (i = 0; i < n_recs; i++) {
const rec_t* r = page + (page_zip_dir_get(page_zip, i)
& PAGE_ZIP_DIR_SLOT_MASK);
if (rec_get_heap_no_new(r) < heap_no) {
n_ext += rec_get_n_extern_new(r, index,
ULINT_UNDEFINED);
if (!--left) {
break;
}
}
}
return(n_ext);
}
/**********************************************************************//**
Encode the length of a fixed-length column.
@return buf + length of encoded val */
static
byte*
page_zip_fixed_field_encode(
/*========================*/
byte* buf, /*!< in: pointer to buffer where to write */
ulint val) /*!< in: value to write */
{
ut_ad(val >= 2);
if (UNIV_LIKELY(val < 126)) {
/*
0 = nullable variable field of at most 255 bytes length;
1 = not null variable field of at most 255 bytes length;
126 = nullable variable field with maximum length >255;
127 = not null variable field with maximum length >255
*/
*buf++ = (byte) val;
} else {
*buf++ = (byte) (0x80 | val >> 8);
*buf++ = (byte) val;
}
return(buf);
}
/**********************************************************************//**
Write the index information for the compressed page.
@return used size of buf */
static
ulint
page_zip_fields_encode(
/*===================*/
ulint n, /*!< in: number of fields to compress */
dict_index_t* index, /*!< in: index comprising at least n fields */
ulint trx_id_pos,/*!< in: position of the trx_id column
in the index, or ULINT_UNDEFINED if
this is a non-leaf page */
byte* buf) /*!< out: buffer of (n + 1) * 2 bytes */
{
const byte* buf_start = buf;
ulint i;
ulint col;
ulint trx_id_col = 0;
/* sum of lengths of preceding non-nullable fixed fields, or 0 */
ulint fixed_sum = 0;
ut_ad(trx_id_pos == ULINT_UNDEFINED || trx_id_pos < n);
for (i = col = 0; i < n; i++) {
dict_field_t* field = dict_index_get_nth_field(index, i);
ulint val;
if (dict_field_get_col(field)->prtype & DATA_NOT_NULL) {
val = 1; /* set the "not nullable" flag */
} else {
val = 0; /* nullable field */
}
if (!field->fixed_len) {
/* variable-length field */
const dict_col_t* column
= dict_field_get_col(field);
if (UNIV_UNLIKELY(column->len > 255)
|| UNIV_UNLIKELY(column->mtype == DATA_BLOB)) {
val |= 0x7e; /* max > 255 bytes */
}
if (fixed_sum) {
/* write out the length of any
preceding non-nullable fields */
buf = page_zip_fixed_field_encode(
buf, fixed_sum << 1 | 1);
fixed_sum = 0;
col++;
}
*buf++ = (byte) val;
col++;
} else if (val) {
/* fixed-length non-nullable field */
if (fixed_sum && UNIV_UNLIKELY
(fixed_sum + field->fixed_len
> DICT_MAX_FIXED_COL_LEN)) {
/* Write out the length of the
preceding non-nullable fields,
to avoid exceeding the maximum
length of a fixed-length column. */
buf = page_zip_fixed_field_encode(
buf, fixed_sum << 1 | 1);
fixed_sum = 0;
col++;
}
if (i && UNIV_UNLIKELY(i == trx_id_pos)) {
if (fixed_sum) {
/* Write out the length of any
preceding non-nullable fields,
and start a new trx_id column. */
buf = page_zip_fixed_field_encode(
buf, fixed_sum << 1 | 1);
col++;
}
trx_id_col = col;
fixed_sum = field->fixed_len;
} else {
/* add to the sum */
fixed_sum += field->fixed_len;
}
} else {
/* fixed-length nullable field */
if (fixed_sum) {
/* write out the length of any
preceding non-nullable fields */
buf = page_zip_fixed_field_encode(
buf, fixed_sum << 1 | 1);
fixed_sum = 0;
col++;
}
buf = page_zip_fixed_field_encode(
buf, field->fixed_len << 1);
col++;
}
}
if (fixed_sum) {
/* Write out the lengths of last fixed-length columns. */
buf = page_zip_fixed_field_encode(buf, fixed_sum << 1 | 1);
}
if (trx_id_pos != ULINT_UNDEFINED) {
/* Write out the position of the trx_id column */
i = trx_id_col;
} else {
/* Write out the number of nullable fields */
i = index->n_nullable;
}
if (i < 128) {
*buf++ = (byte) i;
} else {
*buf++ = (byte) (0x80 | i >> 8);
*buf++ = (byte) i;
}
ut_ad((ulint) (buf - buf_start) <= (n + 2) * 2);
return((ulint) (buf - buf_start));
}
/**********************************************************************//**
Populate the dense page directory from the sparse directory. */
static
void
page_zip_dir_encode(
/*================*/
const page_t* page, /*!< in: compact page */
byte* buf, /*!< in: pointer to dense page directory[-1];
out: dense directory on compressed page */
const rec_t** recs) /*!< in: pointer to an array of 0, or NULL;
out: dense page directory sorted by ascending
address (and heap_no) */
{
const byte* rec;
ulint status;
ulint min_mark;
ulint heap_no;
ulint i;
ulint n_heap;
ulint offs;
min_mark = 0;
if (page_is_leaf(page)) {
status = REC_STATUS_ORDINARY;
} else {
status = REC_STATUS_NODE_PTR;
if (UNIV_UNLIKELY
(mach_read_from_4(page + FIL_PAGE_PREV) == FIL_NULL)) {
min_mark = REC_INFO_MIN_REC_FLAG;
}
}
n_heap = page_dir_get_n_heap(page);
/* Traverse the list of stored records in the collation order,
starting from the first user record. */
rec = page + PAGE_NEW_INFIMUM;
i = 0;
for (;;) {
ulint info_bits;
offs = rec_get_next_offs(rec, TRUE);
if (UNIV_UNLIKELY(offs == PAGE_NEW_SUPREMUM)) {
break;
}
rec = page + offs;
heap_no = rec_get_heap_no_new(rec);
ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW);
ut_a(heap_no < n_heap);
ut_a(offs < UNIV_PAGE_SIZE - PAGE_DIR);
ut_a(offs >= PAGE_ZIP_START);
#if PAGE_ZIP_DIR_SLOT_MASK & (PAGE_ZIP_DIR_SLOT_MASK + 1)
# error "PAGE_ZIP_DIR_SLOT_MASK is not 1 less than a power of 2"
#endif
#if PAGE_ZIP_DIR_SLOT_MASK < UNIV_PAGE_SIZE_MAX - 1
# error "PAGE_ZIP_DIR_SLOT_MASK < UNIV_PAGE_SIZE_MAX - 1"
#endif
if (UNIV_UNLIKELY(rec_get_n_owned_new(rec))) {
offs |= PAGE_ZIP_DIR_SLOT_OWNED;
}
info_bits = rec_get_info_bits(rec, TRUE);
if (info_bits & REC_INFO_DELETED_FLAG) {
info_bits &= ~REC_INFO_DELETED_FLAG;
offs |= PAGE_ZIP_DIR_SLOT_DEL;
}
ut_a(info_bits == min_mark);
/* Only the smallest user record can have
REC_INFO_MIN_REC_FLAG set. */
min_mark = 0;
mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs);
if (UNIV_LIKELY_NULL(recs)) {
/* Ensure that each heap_no occurs at most once. */
ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]);
/* exclude infimum and supremum */
recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec;
}
ut_a(rec_get_status(rec) == status);
}
offs = page_header_get_field(page, PAGE_FREE);
/* Traverse the free list (of deleted records). */
while (offs) {
ut_ad(!(offs & ~PAGE_ZIP_DIR_SLOT_MASK));
rec = page + offs;
heap_no = rec_get_heap_no_new(rec);
ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW);
ut_a(heap_no < n_heap);
ut_a(!rec[-REC_N_NEW_EXTRA_BYTES]); /* info_bits and n_owned */
ut_a(rec_get_status(rec) == status);
mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs);
if (UNIV_LIKELY_NULL(recs)) {
/* Ensure that each heap_no occurs at most once. */
ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]);
/* exclude infimum and supremum */
recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec;
}
offs = rec_get_next_offs(rec, TRUE);
}
/* Ensure that each heap no occurs at least once. */
ut_a(i + PAGE_HEAP_NO_USER_LOW == n_heap);
}
extern "C" {
/**********************************************************************//**
Allocate memory for zlib. */
static
void*
page_zip_zalloc(
/*============*/
void* opaque, /*!< in/out: memory heap */
uInt items, /*!< in: number of items to allocate */
uInt size) /*!< in: size of an item in bytes */
{
return(mem_heap_zalloc(static_cast<mem_heap_t*>(opaque), items * size));
}
/**********************************************************************//**
Deallocate memory for zlib. */
static
void
page_zip_free(
/*==========*/
void* opaque __attribute__((unused)), /*!< in: memory heap */
void* address __attribute__((unused)))/*!< in: object to free */
{
}
} /* extern "C" */
/**********************************************************************//**
Configure the zlib allocator to use the given memory heap. */
UNIV_INTERN
void
page_zip_set_alloc(
/*===============*/
void* stream, /*!< in/out: zlib stream */
mem_heap_t* heap) /*!< in: memory heap to use */
{
z_stream* strm = static_cast<z_stream*>(stream);
strm->zalloc = page_zip_zalloc;
strm->zfree = page_zip_free;
strm->opaque = heap;
}
#if 0 || defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
/** Symbol for enabling compression and decompression diagnostics */
# define PAGE_ZIP_COMPRESS_DBG
#endif
#ifdef PAGE_ZIP_COMPRESS_DBG
/** Set this variable in a debugger to enable
excessive logging in page_zip_compress(). */
UNIV_INTERN ibool page_zip_compress_dbg;
/** Set this variable in a debugger to enable
binary logging of the data passed to deflate().
When this variable is nonzero, it will act
as a log file name generator. */
UNIV_INTERN unsigned page_zip_compress_log;
/**********************************************************************//**
Wrapper for deflate(). Log the operation if page_zip_compress_dbg is set.
@return deflate() status: Z_OK, Z_BUF_ERROR, ... */
static
int
page_zip_compress_deflate(
/*======================*/
FILE* logfile,/*!< in: log file, or NULL */
z_streamp strm, /*!< in/out: compressed stream for deflate() */
int flush) /*!< in: deflate() flushing method */
{
int status;
if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
ut_print_buf(stderr, strm->next_in, strm->avail_in);
}
if (UNIV_LIKELY_NULL(logfile)) {
blind_fwrite(strm->next_in, 1, strm->avail_in, logfile);
}
status = deflate(strm, flush);
if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
fprintf(stderr, " -> %d\n", status);
}
return(status);
}
/* Redefine deflate(). */
# undef deflate
/** Debug wrapper for the zlib compression routine deflate().
Log the operation if page_zip_compress_dbg is set.
@param strm in/out: compressed stream
@param flush in: flushing method
@return deflate() status: Z_OK, Z_BUF_ERROR, ... */
# define deflate(strm, flush) page_zip_compress_deflate(logfile, strm, flush)
/** Declaration of the logfile parameter */
# define FILE_LOGFILE FILE* logfile,
/** The logfile parameter */
# define LOGFILE logfile,
#else /* PAGE_ZIP_COMPRESS_DBG */
/** Empty declaration of the logfile parameter */
# define FILE_LOGFILE
/** Missing logfile parameter */
# define LOGFILE
#endif /* PAGE_ZIP_COMPRESS_DBG */
/**********************************************************************//**
Compress the records of a node pointer page.
@return Z_OK, or a zlib error code */
static
int
page_zip_compress_node_ptrs(
/*========================*/
FILE_LOGFILE
z_stream* c_stream, /*!< in/out: compressed page stream */
const rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense, /*!< in: size of recs[] */
dict_index_t* index, /*!< in: the index of the page */
byte* storage, /*!< in: end of dense page directory */
mem_heap_t* heap) /*!< in: temporary memory heap */
{
int err = Z_OK;
ulint* offsets = NULL;
do {
const rec_t* rec = *recs++;
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
/* Only leaf nodes may contain externally stored columns. */
ut_ad(!rec_offs_any_extern(offsets));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
/* Compress the extra bytes. */
c_stream->avail_in = static_cast<uInt>(
rec - REC_N_NEW_EXTRA_BYTES - c_stream->next_in);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
break;
}
}
ut_ad(!c_stream->avail_in);
/* Compress the data bytes, except node_ptr. */
c_stream->next_in = (byte*) rec;
c_stream->avail_in = static_cast<uInt>(
rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
break;
}
}
ut_ad(!c_stream->avail_in);
memcpy(storage - REC_NODE_PTR_SIZE
* (rec_get_heap_no_new(rec) - 1),
c_stream->next_in, REC_NODE_PTR_SIZE);
c_stream->next_in += REC_NODE_PTR_SIZE;
} while (--n_dense);
return(err);
}
/**********************************************************************//**
Compress the records of a leaf node of a secondary index.
@return Z_OK, or a zlib error code */
static
int
page_zip_compress_sec(
/*==================*/
FILE_LOGFILE
z_stream* c_stream, /*!< in/out: compressed page stream */
const rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense) /*!< in: size of recs[] */
{
int err = Z_OK;
ut_ad(n_dense > 0);
do {
const rec_t* rec = *recs++;
/* Compress everything up to this record. */
c_stream->avail_in = static_cast<uInt>(
rec - REC_N_NEW_EXTRA_BYTES
- c_stream->next_in);
if (UNIV_LIKELY(c_stream->avail_in)) {
UNIV_MEM_ASSERT_RW(c_stream->next_in,
c_stream->avail_in);
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
break;
}
}
ut_ad(!c_stream->avail_in);
ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES);
/* Skip the REC_N_NEW_EXTRA_BYTES. */
c_stream->next_in = (byte*) rec;
} while (--n_dense);
return(err);
}
/**********************************************************************//**
Compress a record of a leaf node of a clustered index that contains
externally stored columns.
@return Z_OK, or a zlib error code */
static
int
page_zip_compress_clust_ext(
/*========================*/
FILE_LOGFILE
z_stream* c_stream, /*!< in/out: compressed page stream */
const rec_t* rec, /*!< in: record */
const ulint* offsets, /*!< in: rec_get_offsets(rec) */
ulint trx_id_col, /*!< in: position of of DB_TRX_ID */
byte* deleted, /*!< in: dense directory entry pointing
to the head of the free list */
byte* storage, /*!< in: end of dense page directory */
byte** externs, /*!< in/out: pointer to the next
available BLOB pointer */
ulint* n_blobs) /*!< in/out: number of
externally stored columns */
{
int err;
ulint i;
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
for (i = 0; i < rec_offs_n_fields(offsets); i++) {
ulint len;
const byte* src;
if (UNIV_UNLIKELY(i == trx_id_col)) {
ut_ad(!rec_offs_nth_extern(offsets, i));
/* Store trx_id and roll_ptr
in uncompressed form. */
src = rec_get_nth_field(rec, offsets, i, &len);
ut_ad(src + DATA_TRX_ID_LEN
== rec_get_nth_field(rec, offsets,
i + 1, &len));
ut_ad(len == DATA_ROLL_PTR_LEN);
/* Compress any preceding bytes. */
c_stream->avail_in = static_cast<uInt>(
src - c_stream->next_in);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
return(err);
}
}
ut_ad(!c_stream->avail_in);
ut_ad(c_stream->next_in == src);
memcpy(storage
- (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
* (rec_get_heap_no_new(rec) - 1),
c_stream->next_in,
DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
c_stream->next_in
+= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
/* Skip also roll_ptr */
i++;
} else if (rec_offs_nth_extern(offsets, i)) {
src = rec_get_nth_field(rec, offsets, i, &len);
ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);
src += len - BTR_EXTERN_FIELD_REF_SIZE;
c_stream->avail_in = static_cast<uInt>(
src - c_stream->next_in);
if (UNIV_LIKELY(c_stream->avail_in)) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
return(err);
}
}
ut_ad(!c_stream->avail_in);
ut_ad(c_stream->next_in == src);
/* Reserve space for the data at
the end of the space reserved for
the compressed data and the page
modification log. */
if (UNIV_UNLIKELY
(c_stream->avail_out
<= BTR_EXTERN_FIELD_REF_SIZE)) {
/* out of space */
return(Z_BUF_ERROR);
}
ut_ad(*externs == c_stream->next_out
+ c_stream->avail_out
+ 1/* end of modif. log */);
c_stream->next_in
+= BTR_EXTERN_FIELD_REF_SIZE;
/* Skip deleted records. */
if (UNIV_LIKELY_NULL
(page_zip_dir_find_low(
storage, deleted,
page_offset(rec)))) {
continue;
}
(*n_blobs)++;
c_stream->avail_out
-= BTR_EXTERN_FIELD_REF_SIZE;
*externs -= BTR_EXTERN_FIELD_REF_SIZE;
/* Copy the BLOB pointer */
memcpy(*externs, c_stream->next_in
- BTR_EXTERN_FIELD_REF_SIZE,
BTR_EXTERN_FIELD_REF_SIZE);
}
}
return(Z_OK);
}
/**********************************************************************//**
Compress the records of a leaf node of a clustered index.
@return Z_OK, or a zlib error code */
static
int
page_zip_compress_clust(
/*====================*/
FILE_LOGFILE
z_stream* c_stream, /*!< in/out: compressed page stream */
const rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense, /*!< in: size of recs[] */
dict_index_t* index, /*!< in: the index of the page */
ulint* n_blobs, /*!< in: 0; out: number of
externally stored columns */
ulint trx_id_col, /*!< index of the trx_id column */
byte* deleted, /*!< in: dense directory entry pointing
to the head of the free list */
byte* storage, /*!< in: end of dense page directory */
mem_heap_t* heap) /*!< in: temporary memory heap */
{
int err = Z_OK;
ulint* offsets = NULL;
/* BTR_EXTERN_FIELD_REF storage */
byte* externs = storage - n_dense
* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
ut_ad(*n_blobs == 0);
do {
const rec_t* rec = *recs++;
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
ut_ad(rec_offs_n_fields(offsets)
== dict_index_get_n_fields(index));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
/* Compress the extra bytes. */
c_stream->avail_in = static_cast<uInt>(
rec - REC_N_NEW_EXTRA_BYTES
- c_stream->next_in);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto func_exit;
}
}
ut_ad(!c_stream->avail_in);
ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES);
/* Compress the data bytes. */
c_stream->next_in = (byte*) rec;
/* Check if there are any externally stored columns.
For each externally stored column, store the
BTR_EXTERN_FIELD_REF separately. */
if (rec_offs_any_extern(offsets)) {
ut_ad(dict_index_is_clust(index));
err = page_zip_compress_clust_ext(
LOGFILE
c_stream, rec, offsets, trx_id_col,
deleted, storage, &externs, n_blobs);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto func_exit;
}
} else {
ulint len;
const byte* src;
/* Store trx_id and roll_ptr in uncompressed form. */
src = rec_get_nth_field(rec, offsets,
trx_id_col, &len);
ut_ad(src + DATA_TRX_ID_LEN
== rec_get_nth_field(rec, offsets,
trx_id_col + 1, &len));
ut_ad(len == DATA_ROLL_PTR_LEN);
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
/* Compress any preceding bytes. */
c_stream->avail_in = static_cast<uInt>(
src - c_stream->next_in);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
return(err);
}
}
ut_ad(!c_stream->avail_in);
ut_ad(c_stream->next_in == src);
memcpy(storage
- (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
* (rec_get_heap_no_new(rec) - 1),
c_stream->next_in,
DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
c_stream->next_in
+= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
/* Skip also roll_ptr */
ut_ad(trx_id_col + 1 < rec_offs_n_fields(offsets));
}
/* Compress the last bytes of the record. */
c_stream->avail_in = static_cast<uInt>(
rec + rec_offs_data_size(offsets) - c_stream->next_in);
if (c_stream->avail_in) {
err = deflate(c_stream, Z_NO_FLUSH);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto func_exit;
}
}
ut_ad(!c_stream->avail_in);
} while (--n_dense);
func_exit:
return(err);
}
my_bool page_zip_zlib_wrap = FALSE;
uint page_zip_zlib_strategy = Z_DEFAULT_STRATEGY;
/**********************************************************************//**
Compress a page.
@return TRUE on success, FALSE on failure; page_zip will be left
intact on failure. */
UNIV_INTERN
ibool
page_zip_compress(
/*==============*/
page_zip_des_t* page_zip,/*!< in: size; out: data, n_blobs,
m_start, m_end, m_nonempty */
const page_t* page, /*!< in: uncompressed page */
dict_index_t* index, /*!< in: index of the B-tree node */
uchar compression_flags, /*!< in: compression level
and other options */
mtr_t* mtr) /*!< in: mini-transaction, or NULL */
{
z_stream c_stream;
int err;
ulint n_fields;/* number of index fields needed */
byte* fields; /*!< index field information */
byte* buf; /*!< compressed payload of the page */
byte* buf_end;/* end of buf */
ulint n_dense;
ulint slot_size;/* amount of uncompressed bytes per record */
const rec_t** recs; /*!< dense page directory, sorted by address */
mem_heap_t* heap;
ulint trx_id_col;
ulint n_blobs = 0;
byte* storage;/* storage of uncompressed columns */
#ifndef UNIV_HOTBACKUP
ullint usec = ut_time_us(NULL);
uint level;
uint wrap;
uint strategy;
int window_bits;
page_zip_decode_compression_flags(compression_flags, &level,
&wrap, &strategy);
window_bits = wrap ? UNIV_PAGE_SIZE_SHIFT
: - ((int) UNIV_PAGE_SIZE_SHIFT);
#endif /* !UNIV_HOTBACKUP */
#ifdef PAGE_ZIP_COMPRESS_DBG
FILE* logfile = NULL;
#endif
/* A local copy of srv_cmp_per_index_enabled to avoid reading that
variable multiple times in this function since it can be changed at
anytime. */
my_bool cmp_per_index_enabled = srv_cmp_per_index_enabled;
ut_a(page_is_comp(page));
ut_a(fil_page_get_type(page) == FIL_PAGE_INDEX);
ut_ad(page_simple_validate_new((page_t*) page));
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(dict_table_is_comp(index->table));
ut_ad(!dict_index_is_ibuf(index));
UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE);
/* Check the data that will be omitted. */
ut_a(!memcmp(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES),
infimum_extra, sizeof infimum_extra));
ut_a(!memcmp(page + PAGE_NEW_INFIMUM,
infimum_data, sizeof infimum_data));
ut_a(page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES]
/* info_bits == 0, n_owned <= max */
<= PAGE_DIR_SLOT_MAX_N_OWNED);
ut_a(!memcmp(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1),
supremum_extra_data, sizeof supremum_extra_data));
if (page_is_empty(page)) {
ut_a(rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE)
== PAGE_NEW_SUPREMUM);
}
if (page_is_leaf(page)) {
n_fields = dict_index_get_n_fields(index);
} else {
n_fields = dict_index_get_n_unique_in_tree(index);
}
/* The dense directory excludes the infimum and supremum records. */
n_dense = page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW;
#ifdef PAGE_ZIP_COMPRESS_DBG
if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
fprintf(stderr, "compress %p %p %lu %lu %lu\n",
(void*) page_zip, (void*) page,
(ibool) page_is_leaf(page),
n_fields, n_dense);
}
if (UNIV_UNLIKELY(page_zip_compress_log)) {
/* Create a log file for every compression attempt. */
char logfilename[9];
ut_snprintf(logfilename, sizeof logfilename,
"%08x", page_zip_compress_log++);
logfile = fopen(logfilename, "wb");
if (logfile) {
/* Write the uncompressed page to the log. */
blind_fwrite(page, 1, UNIV_PAGE_SIZE, logfile);
/* Record the compressed size as zero.
This will be overwritten at successful exit. */
putc(0, logfile);
putc(0, logfile);
putc(0, logfile);
putc(0, logfile);
}
}
#endif /* PAGE_ZIP_COMPRESS_DBG */
#ifndef UNIV_HOTBACKUP
page_zip_stat[page_zip->ssize - 1].compressed++;
if (cmp_per_index_enabled) {
mutex_enter(&page_zip_stat_per_index_mutex);
page_zip_stat_per_index[index->id].compressed++;
mutex_exit(&page_zip_stat_per_index_mutex);
}
#endif /* !UNIV_HOTBACKUP */
if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE
>= page_zip_get_size(page_zip))) {
goto err_exit;
}
MONITOR_INC(MONITOR_PAGE_COMPRESS);
heap = mem_heap_create(page_zip_get_size(page_zip)
+ n_fields * (2 + sizeof(ulint))
+ REC_OFFS_HEADER_SIZE
+ n_dense * ((sizeof *recs)
- PAGE_ZIP_DIR_SLOT_SIZE)
+ UNIV_PAGE_SIZE * 4
+ (512 << MAX_MEM_LEVEL));
recs = static_cast<const rec_t**>(
mem_heap_zalloc(heap, n_dense * sizeof *recs));
fields = static_cast<byte*>(mem_heap_alloc(heap, (n_fields + 1) * 2));
buf = static_cast<byte*>(
mem_heap_alloc(heap, page_zip_get_size(page_zip) - PAGE_DATA));
buf_end = buf + page_zip_get_size(page_zip) - PAGE_DATA;
/* Compress the data payload. */
page_zip_set_alloc(&c_stream, heap);
err = deflateInit2(&c_stream, static_cast<int>(level),
Z_DEFLATED, window_bits,
MAX_MEM_LEVEL, strategy);
ut_a(err == Z_OK);
c_stream.next_out = buf;
/* Subtract the space reserved for uncompressed data. */
/* Page header and the end marker of the modification log */
c_stream.avail_out = static_cast<uInt>(buf_end - buf - 1);
/* Dense page directory and uncompressed columns, if any */
if (page_is_leaf(page)) {
if (dict_index_is_clust(index)) {
trx_id_col = dict_index_get_sys_col_pos(
index, DATA_TRX_ID);
ut_ad(trx_id_col > 0);
ut_ad(trx_id_col != ULINT_UNDEFINED);
slot_size = PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
} else {
/* Signal the absence of trx_id
in page_zip_fields_encode() */
ut_ad(dict_index_get_sys_col_pos(index, DATA_TRX_ID)
== ULINT_UNDEFINED);
trx_id_col = 0;
slot_size = PAGE_ZIP_DIR_SLOT_SIZE;
}
} else {
slot_size = PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE;
trx_id_col = ULINT_UNDEFINED;
}
if (UNIV_UNLIKELY(c_stream.avail_out <= n_dense * slot_size
+ 6/* sizeof(zlib header and footer) */)) {
goto zlib_error;
}
c_stream.avail_out -= static_cast<uInt>(n_dense * slot_size);
c_stream.avail_in = static_cast<uInt>(
page_zip_fields_encode(n_fields, index, trx_id_col, fields));
c_stream.next_in = fields;
if (UNIV_LIKELY(!trx_id_col)) {
trx_id_col = ULINT_UNDEFINED;
}
UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in);
err = deflate(&c_stream, Z_FULL_FLUSH);
if (err != Z_OK) {
goto zlib_error;
}
ut_ad(!c_stream.avail_in);
page_zip_dir_encode(page, buf_end, recs);
c_stream.next_in = (byte*) page + PAGE_ZIP_START;
storage = buf_end - n_dense * PAGE_ZIP_DIR_SLOT_SIZE;
/* Compress the records in heap_no order. */
if (UNIV_UNLIKELY(!n_dense)) {
} else if (!page_is_leaf(page)) {
/* This is a node pointer page. */
err = page_zip_compress_node_ptrs(LOGFILE
&c_stream, recs, n_dense,
index, storage, heap);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto zlib_error;
}
} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
/* This is a leaf page in a secondary index. */
err = page_zip_compress_sec(LOGFILE
&c_stream, recs, n_dense);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto zlib_error;
}
} else {
/* This is a leaf page in a clustered index. */
err = page_zip_compress_clust(LOGFILE
&c_stream, recs, n_dense,
index, &n_blobs, trx_id_col,
buf_end - PAGE_ZIP_DIR_SLOT_SIZE
* page_get_n_recs(page),
storage, heap);
if (UNIV_UNLIKELY(err != Z_OK)) {
goto zlib_error;
}
}
/* Finish the compression. */
ut_ad(!c_stream.avail_in);
/* Compress any trailing garbage, in case the last record was
allocated from an originally longer space on the free list,
or the data of the last record from page_zip_compress_sec(). */
c_stream.avail_in = static_cast<uInt>(
page_header_get_field(page, PAGE_HEAP_TOP)
- (c_stream.next_in - page));
ut_a(c_stream.avail_in <= UNIV_PAGE_SIZE - PAGE_ZIP_START - PAGE_DIR);
UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in);
err = deflate(&c_stream, Z_FINISH);
if (UNIV_UNLIKELY(err != Z_STREAM_END)) {
zlib_error:
deflateEnd(&c_stream);
mem_heap_free(heap);
err_exit:
#ifdef PAGE_ZIP_COMPRESS_DBG
if (logfile) {
fclose(logfile);
}
#endif /* PAGE_ZIP_COMPRESS_DBG */
#ifndef UNIV_HOTBACKUP
if (page_is_leaf(page)) {
dict_index_zip_failure(index);
}
ullint time_diff = ut_time_us(NULL) - usec;
page_zip_stat[page_zip->ssize - 1].compressed_usec
+= time_diff;
if (cmp_per_index_enabled) {
mutex_enter(&page_zip_stat_per_index_mutex);
page_zip_stat_per_index[index->id].compressed_usec
+= time_diff;
mutex_exit(&page_zip_stat_per_index_mutex);
}
#endif /* !UNIV_HOTBACKUP */
return(FALSE);
}
err = deflateEnd(&c_stream);
ut_a(err == Z_OK);
ut_ad(buf + c_stream.total_out == c_stream.next_out);
ut_ad((ulint) (storage - c_stream.next_out) >= c_stream.avail_out);
/* Valgrind believes that zlib does not initialize some bits
in the last 7 or 8 bytes of the stream. Make Valgrind happy. */
UNIV_MEM_VALID(buf, c_stream.total_out);
/* Zero out the area reserved for the modification log.
Space for the end marker of the modification log is not
included in avail_out. */
memset(c_stream.next_out, 0, c_stream.avail_out + 1/* end marker */);
#ifdef UNIV_DEBUG
page_zip->m_start =
#endif /* UNIV_DEBUG */
page_zip->m_end = PAGE_DATA + c_stream.total_out;
page_zip->m_nonempty = FALSE;
page_zip->n_blobs = n_blobs;
/* Copy those header fields that will not be written
in buf_flush_init_for_writing() */
memcpy(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
FIL_PAGE_LSN - FIL_PAGE_PREV);
memcpy(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2);
memcpy(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
PAGE_DATA - FIL_PAGE_DATA);
/* Copy the rest of the compressed page */
memcpy(page_zip->data + PAGE_DATA, buf,
page_zip_get_size(page_zip) - PAGE_DATA);
mem_heap_free(heap);
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
if (mtr) {
#ifndef UNIV_HOTBACKUP
page_zip_compress_write_log(page_zip, page, index, mtr);
#endif /* !UNIV_HOTBACKUP */
}
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
#ifdef PAGE_ZIP_COMPRESS_DBG
if (logfile) {
/* Record the compressed size of the block. */
byte sz[4];
mach_write_to_4(sz, c_stream.total_out);
fseek(logfile, UNIV_PAGE_SIZE, SEEK_SET);
blind_fwrite(sz, 1, sizeof sz, logfile);
fclose(logfile);
}
#endif /* PAGE_ZIP_COMPRESS_DBG */
#ifndef UNIV_HOTBACKUP
ullint time_diff = ut_time_us(NULL) - usec;
page_zip_stat[page_zip->ssize - 1].compressed_ok++;
page_zip_stat[page_zip->ssize - 1].compressed_usec += time_diff;
if (cmp_per_index_enabled) {
mutex_enter(&page_zip_stat_per_index_mutex);
page_zip_stat_per_index[index->id].compressed_ok++;
page_zip_stat_per_index[index->id].compressed_usec += time_diff;
mutex_exit(&page_zip_stat_per_index_mutex);
}
if (page_is_leaf(page)) {
dict_index_zip_success(index);
}
#endif /* !UNIV_HOTBACKUP */
return(TRUE);
}
/**********************************************************************//**
Compare two page directory entries.
@return positive if rec1 > rec2 */
UNIV_INLINE
ibool
page_zip_dir_cmp(
/*=============*/
const rec_t* rec1, /*!< in: rec1 */
const rec_t* rec2) /*!< in: rec2 */
{
return(rec1 > rec2);
}
/**********************************************************************//**
Sort the dense page directory by address (heap_no). */
static
void
page_zip_dir_sort(
/*==============*/
rec_t** arr, /*!< in/out: dense page directory */
rec_t** aux_arr,/*!< in/out: work area */
ulint low, /*!< in: lower bound of the sorting area, inclusive */
ulint high) /*!< in: upper bound of the sorting area, exclusive */
{
UT_SORT_FUNCTION_BODY(page_zip_dir_sort, arr, aux_arr, low, high,
page_zip_dir_cmp);
}
/**********************************************************************//**
Deallocate the index information initialized by page_zip_fields_decode(). */
static
void
page_zip_fields_free(
/*=================*/
dict_index_t* index) /*!< in: dummy index to be freed */
{
if (index) {
dict_table_t* table = index->table;
os_fast_mutex_free(&index->zip_pad.mutex);
mem_heap_free(index->heap);
dict_mem_table_free(table);
}
}
/**********************************************************************//**
Read the index information for the compressed page.
@return own: dummy index describing the page, or NULL on error */
static
dict_index_t*
page_zip_fields_decode(
/*===================*/
const byte* buf, /*!< in: index information */
const byte* end, /*!< in: end of buf */
ulint* trx_id_col)/*!< in: NULL for non-leaf pages;
for leaf pages, pointer to where to store
the position of the trx_id column */
{
const byte* b;
ulint n;
ulint i;
ulint val;
dict_table_t* table;
dict_index_t* index;
/* Determine the number of fields. */
for (b = buf, n = 0; b < end; n++) {
if (*b++ & 0x80) {
b++; /* skip the second byte */
}
}
n--; /* n_nullable or trx_id */
if (UNIV_UNLIKELY(n > REC_MAX_N_FIELDS)) {
page_zip_fail(("page_zip_fields_decode: n = %lu\n",
(ulong) n));
return(NULL);
}
if (UNIV_UNLIKELY(b > end)) {
page_zip_fail(("page_zip_fields_decode: %p > %p\n",
(const void*) b, (const void*) end));
return(NULL);
}
table = dict_mem_table_create("ZIP_DUMMY", DICT_HDR_SPACE, n,
DICT_TF_COMPACT, 0);
index = dict_mem_index_create("ZIP_DUMMY", "ZIP_DUMMY",
DICT_HDR_SPACE, 0, n);
index->table = table;
index->n_uniq = n;
/* avoid ut_ad(index->cached) in dict_index_get_n_unique_in_tree */
index->cached = TRUE;
/* Initialize the fields. */
for (b = buf, i = 0; i < n; i++) {
ulint mtype;
ulint len;
val = *b++;
if (UNIV_UNLIKELY(val & 0x80)) {
/* fixed length > 62 bytes */
val = (val & 0x7f) << 8 | *b++;
len = val >> 1;
mtype = DATA_FIXBINARY;
} else if (UNIV_UNLIKELY(val >= 126)) {
/* variable length with max > 255 bytes */
len = 0x7fff;
mtype = DATA_BINARY;
} else if (val <= 1) {
/* variable length with max <= 255 bytes */
len = 0;
mtype = DATA_BINARY;
} else {
/* fixed length < 62 bytes */
len = val >> 1;
mtype = DATA_FIXBINARY;
}
dict_mem_table_add_col(table, NULL, NULL, mtype,
val & 1 ? DATA_NOT_NULL : 0, len);
dict_index_add_col(index, table,
dict_table_get_nth_col(table, i), 0);
}
val = *b++;
if (UNIV_UNLIKELY(val & 0x80)) {
val = (val & 0x7f) << 8 | *b++;
}
/* Decode the position of the trx_id column. */
if (trx_id_col) {
if (!val) {
val = ULINT_UNDEFINED;
} else if (UNIV_UNLIKELY(val >= n)) {
page_zip_fields_free(index);
index = NULL;
} else {
index->type = DICT_CLUSTERED;
}
*trx_id_col = val;
} else {
/* Decode the number of nullable fields. */
if (UNIV_UNLIKELY(index->n_nullable > val)) {
page_zip_fields_free(index);
index = NULL;
} else {
index->n_nullable = val;
}
}
ut_ad(b == end);
return(index);
}
/**********************************************************************//**
Populate the sparse page directory from the dense directory.
@return TRUE on success, FALSE on failure */
static
ibool
page_zip_dir_decode(
/*================*/
const page_zip_des_t* page_zip,/*!< in: dense page directory on
compressed page */
page_t* page, /*!< in: compact page with valid header;
out: trailer and sparse page directory
filled in */
rec_t** recs, /*!< out: dense page directory sorted by
ascending address (and heap_no) */
rec_t** recs_aux,/*!< in/out: scratch area */
ulint n_dense)/*!< in: number of user records, and
size of recs[] and recs_aux[] */
{
ulint i;
ulint n_recs;
byte* slot;
n_recs = page_get_n_recs(page);
if (UNIV_UNLIKELY(n_recs > n_dense)) {
page_zip_fail(("page_zip_dir_decode 1: %lu > %lu\n",
(ulong) n_recs, (ulong) n_dense));
return(FALSE);
}
/* Traverse the list of stored records in the sorting order,
starting from the first user record. */
slot = page + (UNIV_PAGE_SIZE - PAGE_DIR - PAGE_DIR_SLOT_SIZE);
UNIV_PREFETCH_RW(slot);
/* Zero out the page trailer. */
memset(slot + PAGE_DIR_SLOT_SIZE, 0, PAGE_DIR);
mach_write_to_2(slot, PAGE_NEW_INFIMUM);
slot -= PAGE_DIR_SLOT_SIZE;
UNIV_PREFETCH_RW(slot);
/* Initialize the sparse directory and copy the dense directory. */
for (i = 0; i < n_recs; i++) {
ulint offs = page_zip_dir_get(page_zip, i);
if (offs & PAGE_ZIP_DIR_SLOT_OWNED) {
mach_write_to_2(slot, offs & PAGE_ZIP_DIR_SLOT_MASK);
slot -= PAGE_DIR_SLOT_SIZE;
UNIV_PREFETCH_RW(slot);
}
if (UNIV_UNLIKELY((offs & PAGE_ZIP_DIR_SLOT_MASK)
< PAGE_ZIP_START + REC_N_NEW_EXTRA_BYTES)) {
page_zip_fail(("page_zip_dir_decode 2: %u %u %lx\n",
(unsigned) i, (unsigned) n_recs,
(ulong) offs));
return(FALSE);
}
recs[i] = page + (offs & PAGE_ZIP_DIR_SLOT_MASK);
}
mach_write_to_2(slot, PAGE_NEW_SUPREMUM);
{
const page_dir_slot_t* last_slot = page_dir_get_nth_slot(
page, page_dir_get_n_slots(page) - 1);
if (UNIV_UNLIKELY(slot != last_slot)) {
page_zip_fail(("page_zip_dir_decode 3: %p != %p\n",
(const void*) slot,
(const void*) last_slot));
return(FALSE);
}
}
/* Copy the rest of the dense directory. */
for (; i < n_dense; i++) {
ulint offs = page_zip_dir_get(page_zip, i);
if (UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) {
page_zip_fail(("page_zip_dir_decode 4: %u %u %lx\n",
(unsigned) i, (unsigned) n_dense,
(ulong) offs));
return(FALSE);
}
recs[i] = page + offs;
}
if (UNIV_LIKELY(n_dense > 1)) {
page_zip_dir_sort(recs, recs_aux, 0, n_dense);
}
return(TRUE);
}
/**********************************************************************//**
Initialize the REC_N_NEW_EXTRA_BYTES of each record.
@return TRUE on success, FALSE on failure */
static
ibool
page_zip_set_extra_bytes(
/*=====================*/
const page_zip_des_t* page_zip,/*!< in: compressed page */
page_t* page, /*!< in/out: uncompressed page */
ulint info_bits)/*!< in: REC_INFO_MIN_REC_FLAG or 0 */
{
ulint n;
ulint i;
ulint n_owned = 1;
ulint offs;
rec_t* rec;
n = page_get_n_recs(page);
rec = page + PAGE_NEW_INFIMUM;
for (i = 0; i < n; i++) {
offs = page_zip_dir_get(page_zip, i);
if (offs & PAGE_ZIP_DIR_SLOT_DEL) {
info_bits |= REC_INFO_DELETED_FLAG;
}
if (UNIV_UNLIKELY(offs & PAGE_ZIP_DIR_SLOT_OWNED)) {
info_bits |= n_owned;
n_owned = 1;
} else {
n_owned++;
}
offs &= PAGE_ZIP_DIR_SLOT_MASK;
if (UNIV_UNLIKELY(offs < PAGE_ZIP_START
+ REC_N_NEW_EXTRA_BYTES)) {
page_zip_fail(("page_zip_set_extra_bytes 1:"
" %u %u %lx\n",
(unsigned) i, (unsigned) n,
(ulong) offs));
return(FALSE);
}
rec_set_next_offs_new(rec, offs);
rec = page + offs;
rec[-REC_N_NEW_EXTRA_BYTES] = (byte) info_bits;
info_bits = 0;
}
/* Set the next pointer of the last user record. */
rec_set_next_offs_new(rec, PAGE_NEW_SUPREMUM);
/* Set n_owned of the supremum record. */
page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES] = (byte) n_owned;
/* The dense directory excludes the infimum and supremum records. */
n = page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW;
if (i >= n) {
if (UNIV_LIKELY(i == n)) {
return(TRUE);
}
page_zip_fail(("page_zip_set_extra_bytes 2: %u != %u\n",
(unsigned) i, (unsigned) n));
return(FALSE);
}
offs = page_zip_dir_get(page_zip, i);
/* Set the extra bytes of deleted records on the free list. */
for (;;) {
if (UNIV_UNLIKELY(!offs)
|| UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) {
page_zip_fail(("page_zip_set_extra_bytes 3: %lx\n",
(ulong) offs));
return(FALSE);
}
rec = page + offs;
rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */
if (++i == n) {
break;
}
offs = page_zip_dir_get(page_zip, i);
rec_set_next_offs_new(rec, offs);
}
/* Terminate the free list. */
rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */
rec_set_next_offs_new(rec, 0);
return(TRUE);
}
/**********************************************************************//**
Apply the modification log to a record containing externally stored
columns. Do not copy the fields that are stored separately.
@return pointer to modification log, or NULL on failure */
static
const byte*
page_zip_apply_log_ext(
/*===================*/
rec_t* rec, /*!< in/out: record */
const ulint* offsets, /*!< in: rec_get_offsets(rec) */
ulint trx_id_col, /*!< in: position of of DB_TRX_ID */
const byte* data, /*!< in: modification log */
const byte* end) /*!< in: end of modification log */
{
ulint i;
ulint len;
byte* next_out = rec;
/* Check if there are any externally stored columns.
For each externally stored column, skip the
BTR_EXTERN_FIELD_REF. */
for (i = 0; i < rec_offs_n_fields(offsets); i++) {
byte* dst;
if (UNIV_UNLIKELY(i == trx_id_col)) {
/* Skip trx_id and roll_ptr */
dst = rec_get_nth_field(rec, offsets,
i, &len);
if (UNIV_UNLIKELY(dst - next_out >= end - data)
|| UNIV_UNLIKELY
(len < (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN))
|| rec_offs_nth_extern(offsets, i)) {
page_zip_fail(("page_zip_apply_log_ext:"
" trx_id len %lu,"
" %p - %p >= %p - %p\n",
(ulong) len,
(const void*) dst,
(const void*) next_out,
(const void*) end,
(const void*) data));
return(NULL);
}
memcpy(next_out, data, dst - next_out);
data += dst - next_out;
next_out = dst + (DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN);
} else if (rec_offs_nth_extern(offsets, i)) {
dst = rec_get_nth_field(rec, offsets,
i, &len);
ut_ad(len
>= BTR_EXTERN_FIELD_REF_SIZE);
len += dst - next_out
- BTR_EXTERN_FIELD_REF_SIZE;
if (UNIV_UNLIKELY(data + len >= end)) {
page_zip_fail(("page_zip_apply_log_ext: "
"ext %p+%lu >= %p\n",
(const void*) data,
(ulong) len,
(const void*) end));
return(NULL);
}
memcpy(next_out, data, len);
data += len;
next_out += len
+ BTR_EXTERN_FIELD_REF_SIZE;
}
}
/* Copy the last bytes of the record. */
len = rec_get_end(rec, offsets) - next_out;
if (UNIV_UNLIKELY(data + len >= end)) {
page_zip_fail(("page_zip_apply_log_ext: "
"last %p+%lu >= %p\n",
(const void*) data,
(ulong) len,
(const void*) end));
return(NULL);
}
memcpy(next_out, data, len);
data += len;
return(data);
}
/**********************************************************************//**
Apply the modification log to an uncompressed page.
Do not copy the fields that are stored separately.
@return pointer to end of modification log, or NULL on failure */
static
const byte*
page_zip_apply_log(
/*===============*/
const byte* data, /*!< in: modification log */
ulint size, /*!< in: maximum length of the log, in bytes */
rec_t** recs, /*!< in: dense page directory,
sorted by address (indexed by
heap_no - PAGE_HEAP_NO_USER_LOW) */
ulint n_dense,/*!< in: size of recs[] */
ulint trx_id_col,/*!< in: column number of trx_id in the index,
or ULINT_UNDEFINED if none */
ulint heap_status,
/*!< in: heap_no and status bits for
the next record to uncompress */
dict_index_t* index, /*!< in: index of the page */
ulint* offsets)/*!< in/out: work area for
rec_get_offsets_reverse() */
{
const byte* const end = data + size;
for (;;) {
ulint val;
rec_t* rec;
ulint len;
ulint hs;
val = *data++;
if (UNIV_UNLIKELY(!val)) {
return(data - 1);
}
if (val & 0x80) {
val = (val & 0x7f) << 8 | *data++;
if (UNIV_UNLIKELY(!val)) {
page_zip_fail(("page_zip_apply_log:"
" invalid val %x%x\n",
data[-2], data[-1]));
return(NULL);
}
}
if (UNIV_UNLIKELY(data >= end)) {
page_zip_fail(("page_zip_apply_log: %p >= %p\n",
(const void*) data,
(const void*) end));
return(NULL);
}
if (UNIV_UNLIKELY((val >> 1) > n_dense)) {
page_zip_fail(("page_zip_apply_log: %lu>>1 > %lu\n",
(ulong) val, (ulong) n_dense));
return(NULL);
}
/* Determine the heap number and status bits of the record. */
rec = recs[(val >> 1) - 1];
hs = ((val >> 1) + 1) << REC_HEAP_NO_SHIFT;
hs |= heap_status & ((1 << REC_HEAP_NO_SHIFT) - 1);
/* This may either be an old record that is being
overwritten (updated in place, or allocated from
the free list), or a new record, with the next
available_heap_no. */
if (UNIV_UNLIKELY(hs > heap_status)) {
page_zip_fail(("page_zip_apply_log: %lu > %lu\n",
(ulong) hs, (ulong) heap_status));
return(NULL);
} else if (hs == heap_status) {
/* A new record was allocated from the heap. */
if (UNIV_UNLIKELY(val & 1)) {
/* Only existing records may be cleared. */
page_zip_fail(("page_zip_apply_log:"
" attempting to create"
" deleted rec %lu\n",
(ulong) hs));
return(NULL);
}
heap_status += 1 << REC_HEAP_NO_SHIFT;
}
mach_write_to_2(rec - REC_NEW_HEAP_NO, hs);
if (val & 1) {
/* Clear the data bytes of the record. */
mem_heap_t* heap = NULL;
ulint* offs;
offs = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
memset(rec, 0, rec_offs_data_size(offs));
if (UNIV_LIKELY_NULL(heap)) {
mem_heap_free(heap);
}
continue;
}
#if REC_STATUS_NODE_PTR != TRUE
# error "REC_STATUS_NODE_PTR != TRUE"
#endif
rec_get_offsets_reverse(data, index,
hs & REC_STATUS_NODE_PTR,
offsets);
rec_offs_make_valid(rec, index, offsets);
/* Copy the extra bytes (backwards). */
{
byte* start = rec_get_start(rec, offsets);
byte* b = rec - REC_N_NEW_EXTRA_BYTES;
while (b != start) {
*--b = *data++;
}
}
/* Copy the data bytes. */
if (UNIV_UNLIKELY(rec_offs_any_extern(offsets))) {
/* Non-leaf nodes should not contain any
externally stored columns. */
if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) {
page_zip_fail(("page_zip_apply_log: "
"%lu&REC_STATUS_NODE_PTR\n",
(ulong) hs));
return(NULL);
}
data = page_zip_apply_log_ext(
rec, offsets, trx_id_col, data, end);
if (UNIV_UNLIKELY(!data)) {
return(NULL);
}
} else if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) {
len = rec_offs_data_size(offsets)
- REC_NODE_PTR_SIZE;
/* Copy the data bytes, except node_ptr. */
if (UNIV_UNLIKELY(data + len >= end)) {
page_zip_fail(("page_zip_apply_log: "
"node_ptr %p+%lu >= %p\n",
(const void*) data,
(ulong) len,
(const void*) end));
return(NULL);
}
memcpy(rec, data, len);
data += len;
} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
len = rec_offs_data_size(offsets);
/* Copy all data bytes of
a record in a secondary index. */
if (UNIV_UNLIKELY(data + len >= end)) {
page_zip_fail(("page_zip_apply_log: "
"sec %p+%lu >= %p\n",
(const void*) data,
(ulong) len,
(const void*) end));
return(NULL);
}
memcpy(rec, data, len);
data += len;
} else {
/* Skip DB_TRX_ID and DB_ROLL_PTR. */
ulint l = rec_get_nth_field_offs(offsets,
trx_id_col, &len);
byte* b;
if (UNIV_UNLIKELY(data + l >= end)
|| UNIV_UNLIKELY(len < (DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN))) {
page_zip_fail(("page_zip_apply_log: "
"trx_id %p+%lu >= %p\n",
(const void*) data,
(ulong) l,
(const void*) end));
return(NULL);
}
/* Copy any preceding data bytes. */
memcpy(rec, data, l);
data += l;
/* Copy any bytes following DB_TRX_ID, DB_ROLL_PTR. */
b = rec + l + (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
len = rec_get_end(rec, offsets) - b;
if (UNIV_UNLIKELY(data + len >= end)) {
page_zip_fail(("page_zip_apply_log: "
"clust %p+%lu >= %p\n",
(const void*) data,
(ulong) len,
(const void*) end));
return(NULL);
}
memcpy(b, data, len);
data += len;
}
}
}
/**********************************************************************//**
Set the heap_no in a record, and skip the fixed-size record header
that is not included in the d_stream.
@return TRUE on success, FALSE if d_stream does not end at rec */
static
ibool
page_zip_decompress_heap_no(
/*========================*/
z_stream* d_stream, /*!< in/out: compressed page stream */
rec_t* rec, /*!< in/out: record */
ulint& heap_status) /*!< in/out: heap_no and status bits */
{
if (d_stream->next_out != rec - REC_N_NEW_EXTRA_BYTES) {
/* n_dense has grown since the page was last compressed. */
return(FALSE);
}
/* Skip the REC_N_NEW_EXTRA_BYTES. */
d_stream->next_out = rec;
/* Set heap_no and the status bits. */
mach_write_to_2(rec - REC_NEW_HEAP_NO, heap_status);
heap_status += 1 << REC_HEAP_NO_SHIFT;
return(TRUE);
}
/**********************************************************************//**
Decompress the records of a node pointer page.
@return TRUE on success, FALSE on failure */
static
ibool
page_zip_decompress_node_ptrs(
/*==========================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
z_stream* d_stream, /*!< in/out: compressed page stream */
rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense, /*!< in: size of recs[] */
dict_index_t* index, /*!< in: the index of the page */
ulint* offsets, /*!< in/out: temporary offsets */
mem_heap_t* heap) /*!< in: temporary memory heap */
{
ulint heap_status = REC_STATUS_NODE_PTR
| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
ulint slot;
const byte* storage;
/* Subtract the space reserved for uncompressed data. */
d_stream->avail_in -= static_cast<uInt>(
n_dense * (PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE));
/* Decompress the records in heap_no order. */
for (slot = 0; slot < n_dense; slot++) {
rec_t* rec = recs[slot];
d_stream->avail_out = static_cast<uInt>(
rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
ut_ad(d_stream->avail_out < UNIV_PAGE_SIZE
- PAGE_ZIP_START - PAGE_DIR);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
page_zip_decompress_heap_no(
d_stream, rec, heap_status);
goto zlib_done;
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_node_ptrs:"
" 1 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
if (!page_zip_decompress_heap_no(
d_stream, rec, heap_status)) {
ut_ad(0);
}
/* Read the offsets. The status bits are needed here. */
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
/* Non-leaf nodes should not have any externally
stored columns. */
ut_ad(!rec_offs_any_extern(offsets));
/* Decompress the data bytes, except node_ptr. */
d_stream->avail_out =static_cast<uInt>(
rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
goto zlib_done;
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_node_ptrs:"
" 2 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
/* Clear the node pointer in case the record
will be deleted and the space will be reallocated
to a smaller record. */
memset(d_stream->next_out, 0, REC_NODE_PTR_SIZE);
d_stream->next_out += REC_NODE_PTR_SIZE;
ut_ad(d_stream->next_out == rec_get_end(rec, offsets));
}
/* Decompress any trailing garbage, in case the last record was
allocated from an originally longer space on the free list. */
d_stream->avail_out = static_cast<uInt>(
page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
- page_offset(d_stream->next_out));
if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE
- PAGE_ZIP_START - PAGE_DIR)) {
page_zip_fail(("page_zip_decompress_node_ptrs:"
" avail_out = %u\n",
d_stream->avail_out));
goto zlib_error;
}
if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
page_zip_fail(("page_zip_decompress_node_ptrs:"
" inflate(Z_FINISH)=%s\n",
d_stream->msg));
zlib_error:
inflateEnd(d_stream);
return(FALSE);
}
/* Note that d_stream->avail_out > 0 may hold here
if the modification log is nonempty. */
zlib_done:
if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
ut_error;
}
{
page_t* page = page_align(d_stream->next_out);
/* Clear the unused heap space on the uncompressed page. */
memset(d_stream->next_out, 0,
page_dir_get_nth_slot(page,
page_dir_get_n_slots(page) - 1)
- d_stream->next_out);
}
#ifdef UNIV_DEBUG
page_zip->m_start = PAGE_DATA + d_stream->total_in;
#endif /* UNIV_DEBUG */
/* Apply the modification log. */
{
const byte* mod_log_ptr;
mod_log_ptr = page_zip_apply_log(d_stream->next_in,
d_stream->avail_in + 1,
recs, n_dense,
ULINT_UNDEFINED, heap_status,
index, offsets);
if (UNIV_UNLIKELY(!mod_log_ptr)) {
return(FALSE);
}
page_zip->m_end = mod_log_ptr - page_zip->data;
page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
}
if (UNIV_UNLIKELY
(page_zip_get_trailer_len(page_zip,
dict_index_is_clust(index))
+ page_zip->m_end >= page_zip_get_size(page_zip))) {
page_zip_fail(("page_zip_decompress_node_ptrs:"
" %lu + %lu >= %lu, %lu\n",
(ulong) page_zip_get_trailer_len(
page_zip, dict_index_is_clust(index)),
(ulong) page_zip->m_end,
(ulong) page_zip_get_size(page_zip),
(ulong) dict_index_is_clust(index)));
return(FALSE);
}
/* Restore the uncompressed columns in heap_no order. */
storage = page_zip_dir_start_low(page_zip, n_dense);
for (slot = 0; slot < n_dense; slot++) {
rec_t* rec = recs[slot];
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
/* Non-leaf nodes should not have any externally
stored columns. */
ut_ad(!rec_offs_any_extern(offsets));
storage -= REC_NODE_PTR_SIZE;
memcpy(rec_get_end(rec, offsets) - REC_NODE_PTR_SIZE,
storage, REC_NODE_PTR_SIZE);
}
return(TRUE);
}
/**********************************************************************//**
Decompress the records of a leaf node of a secondary index.
@return TRUE on success, FALSE on failure */
static
ibool
page_zip_decompress_sec(
/*====================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
z_stream* d_stream, /*!< in/out: compressed page stream */
rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense, /*!< in: size of recs[] */
dict_index_t* index, /*!< in: the index of the page */
ulint* offsets) /*!< in/out: temporary offsets */
{
ulint heap_status = REC_STATUS_ORDINARY
| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
ulint slot;
ut_a(!dict_index_is_clust(index));
/* Subtract the space reserved for uncompressed data. */
d_stream->avail_in -= static_cast<uint>(
n_dense * PAGE_ZIP_DIR_SLOT_SIZE);
for (slot = 0; slot < n_dense; slot++) {
rec_t* rec = recs[slot];
/* Decompress everything up to this record. */
d_stream->avail_out = static_cast<uint>(
rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
if (UNIV_LIKELY(d_stream->avail_out)) {
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
page_zip_decompress_heap_no(
d_stream, rec, heap_status);
goto zlib_done;
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_sec:"
" inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
}
if (!page_zip_decompress_heap_no(
d_stream, rec, heap_status)) {
ut_ad(0);
}
}
/* Decompress the data of the last record and any trailing garbage,
in case the last record was allocated from an originally longer space
on the free list. */
d_stream->avail_out = static_cast<uInt>(
page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
- page_offset(d_stream->next_out));
if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE
- PAGE_ZIP_START - PAGE_DIR)) {
page_zip_fail(("page_zip_decompress_sec:"
" avail_out = %u\n",
d_stream->avail_out));
goto zlib_error;
}
if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
page_zip_fail(("page_zip_decompress_sec:"
" inflate(Z_FINISH)=%s\n",
d_stream->msg));
zlib_error:
inflateEnd(d_stream);
return(FALSE);
}
/* Note that d_stream->avail_out > 0 may hold here
if the modification log is nonempty. */
zlib_done:
if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
ut_error;
}
{
page_t* page = page_align(d_stream->next_out);
/* Clear the unused heap space on the uncompressed page. */
memset(d_stream->next_out, 0,
page_dir_get_nth_slot(page,
page_dir_get_n_slots(page) - 1)
- d_stream->next_out);
}
#ifdef UNIV_DEBUG
page_zip->m_start = PAGE_DATA + d_stream->total_in;
#endif /* UNIV_DEBUG */
/* Apply the modification log. */
{
const byte* mod_log_ptr;
mod_log_ptr = page_zip_apply_log(d_stream->next_in,
d_stream->avail_in + 1,
recs, n_dense,
ULINT_UNDEFINED, heap_status,
index, offsets);
if (UNIV_UNLIKELY(!mod_log_ptr)) {
return(FALSE);
}
page_zip->m_end = mod_log_ptr - page_zip->data;
page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
}
if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, FALSE)
+ page_zip->m_end >= page_zip_get_size(page_zip))) {
page_zip_fail(("page_zip_decompress_sec: %lu + %lu >= %lu\n",
(ulong) page_zip_get_trailer_len(
page_zip, FALSE),
(ulong) page_zip->m_end,
(ulong) page_zip_get_size(page_zip)));
return(FALSE);
}
/* There are no uncompressed columns on leaf pages of
secondary indexes. */
return(TRUE);
}
/**********************************************************************//**
Decompress a record of a leaf node of a clustered index that contains
externally stored columns.
@return TRUE on success */
static
ibool
page_zip_decompress_clust_ext(
/*==========================*/
z_stream* d_stream, /*!< in/out: compressed page stream */
rec_t* rec, /*!< in/out: record */
const ulint* offsets, /*!< in: rec_get_offsets(rec) */
ulint trx_id_col) /*!< in: position of of DB_TRX_ID */
{
ulint i;
for (i = 0; i < rec_offs_n_fields(offsets); i++) {
ulint len;
byte* dst;
if (UNIV_UNLIKELY(i == trx_id_col)) {
/* Skip trx_id and roll_ptr */
dst = rec_get_nth_field(rec, offsets, i, &len);
if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN)) {
page_zip_fail(("page_zip_decompress_clust_ext:"
" len[%lu] = %lu\n",
(ulong) i, (ulong) len));
return(FALSE);
}
if (rec_offs_nth_extern(offsets, i)) {
page_zip_fail(("page_zip_decompress_clust_ext:"
" DB_TRX_ID at %lu is ext\n",
(ulong) i));
return(FALSE);
}
d_stream->avail_out = static_cast<uInt>(
dst - d_stream->next_out);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_clust_ext:"
" 1 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
return(FALSE);
}
ut_ad(d_stream->next_out == dst);
/* Clear DB_TRX_ID and DB_ROLL_PTR in order to
avoid uninitialized bytes in case the record
is affected by page_zip_apply_log(). */
memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
d_stream->next_out += DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN;
} else if (rec_offs_nth_extern(offsets, i)) {
dst = rec_get_nth_field(rec, offsets, i, &len);
ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);
dst += len - BTR_EXTERN_FIELD_REF_SIZE;
d_stream->avail_out = static_cast<uInt>(
dst - d_stream->next_out);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_clust_ext:"
" 2 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
return(FALSE);
}
ut_ad(d_stream->next_out == dst);
/* Clear the BLOB pointer in case
the record will be deleted and the
space will not be reused. Note that
the final initialization of the BLOB
pointers (copying from "externs"
or clearing) will have to take place
only after the page modification log
has been applied. Otherwise, we
could end up with an uninitialized
BLOB pointer when a record is deleted,
reallocated and deleted. */
memset(d_stream->next_out, 0,
BTR_EXTERN_FIELD_REF_SIZE);
d_stream->next_out
+= BTR_EXTERN_FIELD_REF_SIZE;
}
}
return(TRUE);
}
/**********************************************************************//**
Compress the records of a leaf node of a clustered index.
@return TRUE on success, FALSE on failure */
static
ibool
page_zip_decompress_clust(
/*======================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
z_stream* d_stream, /*!< in/out: compressed page stream */
rec_t** recs, /*!< in: dense page directory
sorted by address */
ulint n_dense, /*!< in: size of recs[] */
dict_index_t* index, /*!< in: the index of the page */
ulint trx_id_col, /*!< index of the trx_id column */
ulint* offsets, /*!< in/out: temporary offsets */
mem_heap_t* heap) /*!< in: temporary memory heap */
{
int err;
ulint slot;
ulint heap_status = REC_STATUS_ORDINARY
| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
const byte* storage;
const byte* externs;
ut_a(dict_index_is_clust(index));
/* Subtract the space reserved for uncompressed data. */
d_stream->avail_in -= static_cast<uInt>(n_dense)
* (PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN);
/* Decompress the records in heap_no order. */
for (slot = 0; slot < n_dense; slot++) {
rec_t* rec = recs[slot];
d_stream->avail_out =static_cast<uInt>(
rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
ut_ad(d_stream->avail_out < UNIV_PAGE_SIZE
- PAGE_ZIP_START - PAGE_DIR);
err = inflate(d_stream, Z_SYNC_FLUSH);
switch (err) {
case Z_STREAM_END:
page_zip_decompress_heap_no(
d_stream, rec, heap_status);
goto zlib_done;
case Z_OK:
case Z_BUF_ERROR:
if (UNIV_LIKELY(!d_stream->avail_out)) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_clust:"
" 1 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
if (!page_zip_decompress_heap_no(
d_stream, rec, heap_status)) {
ut_ad(0);
}
/* Read the offsets. The status bits are needed here. */
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
/* This is a leaf page in a clustered index. */
/* Check if there are any externally stored columns.
For each externally stored column, restore the
BTR_EXTERN_FIELD_REF separately. */
if (rec_offs_any_extern(offsets)) {
if (UNIV_UNLIKELY
(!page_zip_decompress_clust_ext(
d_stream, rec, offsets, trx_id_col))) {
goto zlib_error;
}
} else {
/* Skip trx_id and roll_ptr */
ulint len;
byte* dst = rec_get_nth_field(rec, offsets,
trx_id_col, &len);
if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN)) {
page_zip_fail(("page_zip_decompress_clust:"
" len = %lu\n", (ulong) len));
goto zlib_error;
}
d_stream->avail_out = static_cast<uInt>(
dst - d_stream->next_out);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_clust:"
" 2 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
ut_ad(d_stream->next_out == dst);
/* Clear DB_TRX_ID and DB_ROLL_PTR in order to
avoid uninitialized bytes in case the record
is affected by page_zip_apply_log(). */
memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
d_stream->next_out += DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN;
}
/* Decompress the last bytes of the record. */
d_stream->avail_out = static_cast<uInt>(
rec_get_end(rec, offsets) - d_stream->next_out);
switch (inflate(d_stream, Z_SYNC_FLUSH)) {
case Z_STREAM_END:
case Z_OK:
case Z_BUF_ERROR:
if (!d_stream->avail_out) {
break;
}
/* fall through */
default:
page_zip_fail(("page_zip_decompress_clust:"
" 3 inflate(Z_SYNC_FLUSH)=%s\n",
d_stream->msg));
goto zlib_error;
}
}
/* Decompress any trailing garbage, in case the last record was
allocated from an originally longer space on the free list. */
d_stream->avail_out = static_cast<uInt>(
page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
- page_offset(d_stream->next_out));
if (UNIV_UNLIKELY(d_stream->avail_out > UNIV_PAGE_SIZE
- PAGE_ZIP_START - PAGE_DIR)) {
page_zip_fail(("page_zip_decompress_clust:"
" avail_out = %u\n",
d_stream->avail_out));
goto zlib_error;
}
if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
page_zip_fail(("page_zip_decompress_clust:"
" inflate(Z_FINISH)=%s\n",
d_stream->msg));
zlib_error:
inflateEnd(d_stream);
return(FALSE);
}
/* Note that d_stream->avail_out > 0 may hold here
if the modification log is nonempty. */
zlib_done:
if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
ut_error;
}
{
page_t* page = page_align(d_stream->next_out);
/* Clear the unused heap space on the uncompressed page. */
memset(d_stream->next_out, 0,
page_dir_get_nth_slot(page,
page_dir_get_n_slots(page) - 1)
- d_stream->next_out);
}
#ifdef UNIV_DEBUG
page_zip->m_start = PAGE_DATA + d_stream->total_in;
#endif /* UNIV_DEBUG */
/* Apply the modification log. */
{
const byte* mod_log_ptr;
mod_log_ptr = page_zip_apply_log(d_stream->next_in,
d_stream->avail_in + 1,
recs, n_dense,
trx_id_col, heap_status,
index, offsets);
if (UNIV_UNLIKELY(!mod_log_ptr)) {
return(FALSE);
}
page_zip->m_end = mod_log_ptr - page_zip->data;
page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
}
if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, TRUE)
+ page_zip->m_end >= page_zip_get_size(page_zip))) {
page_zip_fail(("page_zip_decompress_clust: %lu + %lu >= %lu\n",
(ulong) page_zip_get_trailer_len(
page_zip, TRUE),
(ulong) page_zip->m_end,
(ulong) page_zip_get_size(page_zip)));
return(FALSE);
}
storage = page_zip_dir_start_low(page_zip, n_dense);
externs = storage - n_dense
* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
/* Restore the uncompressed columns in heap_no order. */
for (slot = 0; slot < n_dense; slot++) {
ulint i;
ulint len;
byte* dst;
rec_t* rec = recs[slot];
ibool exists = !page_zip_dir_find_free(
page_zip, page_offset(rec));
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &heap);
dst = rec_get_nth_field(rec, offsets,
trx_id_col, &len);
ut_ad(len >= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
storage -= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
memcpy(dst, storage,
DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
/* Check if there are any externally stored
columns in this record. For each externally
stored column, restore or clear the
BTR_EXTERN_FIELD_REF. */
if (!rec_offs_any_extern(offsets)) {
continue;
}
for (i = 0; i < rec_offs_n_fields(offsets); i++) {
if (!rec_offs_nth_extern(offsets, i)) {
continue;
}
dst = rec_get_nth_field(rec, offsets, i, &len);
if (UNIV_UNLIKELY(len < BTR_EXTERN_FIELD_REF_SIZE)) {
page_zip_fail(("page_zip_decompress_clust:"
" %lu < 20\n",
(ulong) len));
return(FALSE);
}
dst += len - BTR_EXTERN_FIELD_REF_SIZE;
if (UNIV_LIKELY(exists)) {
/* Existing record:
restore the BLOB pointer */
externs -= BTR_EXTERN_FIELD_REF_SIZE;
if (UNIV_UNLIKELY
(externs < page_zip->data
+ page_zip->m_end)) {
page_zip_fail(("page_zip_"
"decompress_clust: "
"%p < %p + %lu\n",
(const void*) externs,
(const void*)
page_zip->data,
(ulong)
page_zip->m_end));
return(FALSE);
}
memcpy(dst, externs,
BTR_EXTERN_FIELD_REF_SIZE);
page_zip->n_blobs++;
} else {
/* Deleted record:
clear the BLOB pointer */
memset(dst, 0,
BTR_EXTERN_FIELD_REF_SIZE);
}
}
}
return(TRUE);
}
/**********************************************************************//**
This function determines the sign for window_bits and reads the zlib header
from the decompress stream. The data may have been compressed with a negative
(no adler32 headers) or a positive (with adler32 headers) window_bits.
Regardless of the current value of page_zip_zlib_wrap, we always
first try the positive window_bits then negative window_bits, because the
surest way to determine if the stream has adler32 headers is to see if the
stream begins with the zlib header together with the adler32 value of it.
This adds a tiny bit of overhead for the pages that were compressed without
adler32s.
@return TRUE if stream is initialized and zlib header was read, FALSE
if data can be decompressed with neither window_bits nor -window_bits */
UNIV_INTERN
ibool
page_zip_init_d_stream(
z_stream* strm,
int window_bits,
ibool read_zlib_header)
{
/* Save initial stream position, in case a reset is required. */
Bytef* next_in = strm->next_in;
Bytef* next_out = strm->next_out;
ulint avail_in = strm->avail_in;
ulint avail_out = strm->avail_out;
if (UNIV_UNLIKELY(inflateInit2(strm, window_bits) != Z_OK)) {
/* init must always succeed regardless of window_bits */
ut_error;
}
/* Try decoding a zlib header assuming adler32. */
if (inflate(strm, Z_BLOCK) == Z_OK)
/* A valid header was found, all is well. So, we return
with the stream positioned just after this header. */
return(TRUE);
/* A valid header was not found, so now we need to re-try this
read assuming there is *no* header (negative window_bits).
So, we need to reset the stream to the original position,
and change the window_bits to negative, with inflateReset2(). */
strm->next_in = next_in;
strm->next_out = next_out;
strm->avail_in = avail_in;
strm->avail_out = avail_out;
if (UNIV_UNLIKELY(inflateReset2(strm, -window_bits) != Z_OK)) {
/* init must always succeed regardless of window_bits */
ut_error;
}
if (read_zlib_header) {
/* No valid header was found, and we still want the header
read to have happened, with negative window_bits. */
return(inflate(strm, Z_BLOCK) == Z_OK);
}
/* Did not find a header, but didn't require one, so just return
with the stream position reset to where it originally was. */
return(TRUE);
}
/**********************************************************************//**
Decompress a page. This function should tolerate errors on the compressed
page. Instead of letting assertions fail, it will return FALSE if an
inconsistency is detected.
@return TRUE on success, FALSE on failure */
UNIV_INTERN
ibool
page_zip_decompress(
/*================*/
page_zip_des_t* page_zip,/*!< in: data, ssize;
out: m_start, m_end, m_nonempty, n_blobs */
page_t* page, /*!< out: uncompressed page, may be trashed */
ibool all) /*!< in: TRUE=decompress the whole page;
FALSE=verify but do not copy some
page header fields that should not change
after page creation */
{
z_stream d_stream;
dict_index_t* index = NULL;
rec_t** recs; /*!< dense page directory, sorted by address */
ulint n_dense;/* number of user records on the page */
ulint trx_id_col = ULINT_UNDEFINED;
mem_heap_t* heap;
ulint* offsets;
#ifndef UNIV_HOTBACKUP
ullint usec = ut_time_us(NULL);
#endif /* !UNIV_HOTBACKUP */
ut_ad(page_zip_simple_validate(page_zip));
UNIV_MEM_ASSERT_W(page, UNIV_PAGE_SIZE);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
/* The dense directory excludes the infimum and supremum records. */
n_dense = page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW;
if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE
>= page_zip_get_size(page_zip))) {
page_zip_fail(("page_zip_decompress 1: %lu %lu\n",
(ulong) n_dense,
(ulong) page_zip_get_size(page_zip)));
return(FALSE);
}
heap = mem_heap_create(n_dense * (3 * sizeof *recs) + UNIV_PAGE_SIZE);
recs = static_cast<rec_t**>(
mem_heap_alloc(heap, n_dense * (2 * sizeof *recs)));
if (all) {
/* Copy the page header. */
memcpy(page, page_zip->data, PAGE_DATA);
} else {
/* Check that the bytes that we skip are identical. */
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
ut_a(!memcmp(FIL_PAGE_TYPE + page,
FIL_PAGE_TYPE + page_zip->data,
PAGE_HEADER - FIL_PAGE_TYPE));
ut_a(!memcmp(PAGE_HEADER + PAGE_LEVEL + page,
PAGE_HEADER + PAGE_LEVEL + page_zip->data,
PAGE_DATA - (PAGE_HEADER + PAGE_LEVEL)));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
/* Copy the mutable parts of the page header. */
memcpy(page, page_zip->data, FIL_PAGE_TYPE);
memcpy(PAGE_HEADER + page, PAGE_HEADER + page_zip->data,
PAGE_LEVEL - PAGE_N_DIR_SLOTS);
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
/* Check that the page headers match after copying. */
ut_a(!memcmp(page, page_zip->data, PAGE_DATA));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
}
#ifdef UNIV_ZIP_DEBUG
/* Clear the uncompressed page, except the header. */
memset(PAGE_DATA + page, 0x55, UNIV_PAGE_SIZE - PAGE_DATA);
#endif /* UNIV_ZIP_DEBUG */
UNIV_MEM_INVALID(PAGE_DATA + page, UNIV_PAGE_SIZE - PAGE_DATA);
/* Copy the page directory. */
if (UNIV_UNLIKELY(!page_zip_dir_decode(page_zip, page, recs,
recs + n_dense, n_dense))) {
zlib_error:
mem_heap_free(heap);
return(FALSE);
}
/* Copy the infimum and supremum records. */
memcpy(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES),
infimum_extra, sizeof infimum_extra);
if (page_is_empty(page)) {
rec_set_next_offs_new(page + PAGE_NEW_INFIMUM,
PAGE_NEW_SUPREMUM);
} else {
rec_set_next_offs_new(page + PAGE_NEW_INFIMUM,
page_zip_dir_get(page_zip, 0)
& PAGE_ZIP_DIR_SLOT_MASK);
}
memcpy(page + PAGE_NEW_INFIMUM, infimum_data, sizeof infimum_data);
memcpy(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1),
supremum_extra_data, sizeof supremum_extra_data);
page_zip_set_alloc(&d_stream, heap);
d_stream.next_in = page_zip->data + PAGE_DATA;
/* Subtract the space reserved for
the page header and the end marker of the modification log. */
d_stream.avail_in = static_cast<uInt>(
page_zip_get_size(page_zip) - (PAGE_DATA + 1));
d_stream.next_out = page + PAGE_ZIP_START;
d_stream.avail_out = UNIV_PAGE_SIZE - PAGE_ZIP_START;
if (!page_zip_init_d_stream(&d_stream, UNIV_PAGE_SIZE_SHIFT, TRUE)) {
page_zip_fail(("page_zip_decompress:"
" 1 inflate(Z_BLOCK)=%s\n", d_stream.msg));
goto zlib_error;
}
if (UNIV_UNLIKELY(inflate(&d_stream, Z_BLOCK) != Z_OK)) {
page_zip_fail(("page_zip_decompress:"
" 2 inflate(Z_BLOCK)=%s\n", d_stream.msg));
goto zlib_error;
}
index = page_zip_fields_decode(
page + PAGE_ZIP_START, d_stream.next_out,
page_is_leaf(page) ? &trx_id_col : NULL);
if (UNIV_UNLIKELY(!index)) {
goto zlib_error;
}
/* Decompress the user records. */
page_zip->n_blobs = 0;
d_stream.next_out = page + PAGE_ZIP_START;
{
/* Pre-allocate the offsets for rec_get_offsets_reverse(). */
ulint n = 1 + 1/* node ptr */ + REC_OFFS_HEADER_SIZE
+ dict_index_get_n_fields(index);
offsets = static_cast<ulint*>(
mem_heap_alloc(heap, n * sizeof(ulint)));
*offsets = n;
}
/* Decompress the records in heap_no order. */
if (!page_is_leaf(page)) {
/* This is a node pointer page. */
ulint info_bits;
if (UNIV_UNLIKELY
(!page_zip_decompress_node_ptrs(page_zip, &d_stream,
recs, n_dense, index,
offsets, heap))) {
goto err_exit;
}
info_bits = mach_read_from_4(page + FIL_PAGE_PREV) == FIL_NULL
? REC_INFO_MIN_REC_FLAG : 0;
if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip, page,
info_bits))) {
goto err_exit;
}
} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
/* This is a leaf page in a secondary index. */
if (UNIV_UNLIKELY(!page_zip_decompress_sec(page_zip, &d_stream,
recs, n_dense,
index, offsets))) {
goto err_exit;
}
if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip,
page, 0))) {
err_exit:
page_zip_fields_free(index);
mem_heap_free(heap);
return(FALSE);
}
} else {
/* This is a leaf page in a clustered index. */
if (UNIV_UNLIKELY(!page_zip_decompress_clust(page_zip,
&d_stream, recs,
n_dense, index,
trx_id_col,
offsets, heap))) {
goto err_exit;
}
if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip,
page, 0))) {
goto err_exit;
}
}
ut_a(page_is_comp(page));
UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE);
page_zip_fields_free(index);
mem_heap_free(heap);
#ifndef UNIV_HOTBACKUP
ullint time_diff = ut_time_us(NULL) - usec;
page_zip_stat[page_zip->ssize - 1].decompressed++;
page_zip_stat[page_zip->ssize - 1].decompressed_usec += time_diff;
index_id_t index_id = btr_page_get_index_id(page);
if (srv_cmp_per_index_enabled) {
mutex_enter(&page_zip_stat_per_index_mutex);
page_zip_stat_per_index[index_id].decompressed++;
page_zip_stat_per_index[index_id].decompressed_usec += time_diff;
mutex_exit(&page_zip_stat_per_index_mutex);
}
#endif /* !UNIV_HOTBACKUP */
/* Update the stat counter for LRU policy. */
buf_LRU_stat_inc_unzip();
MONITOR_INC(MONITOR_PAGE_DECOMPRESS);
return(TRUE);
}
#ifdef UNIV_ZIP_DEBUG
/**********************************************************************//**
Dump a block of memory on the standard error stream. */
static
void
page_zip_hexdump_func(
/*==================*/
const char* name, /*!< in: name of the data structure */
const void* buf, /*!< in: data */
ulint size) /*!< in: length of the data, in bytes */
{
const byte* s = static_cast<const byte*>(buf);
ulint addr;
const ulint width = 32; /* bytes per line */
fprintf(stderr, "%s:\n", name);
for (addr = 0; addr < size; addr += width) {
ulint i;
fprintf(stderr, "%04lx ", (ulong) addr);
i = ut_min(width, size - addr);
while (i--) {
fprintf(stderr, "%02x", *s++);
}
putc('\n', stderr);
}
}
/** Dump a block of memory on the standard error stream.
@param buf in: data
@param size in: length of the data, in bytes */
#define page_zip_hexdump(buf, size) page_zip_hexdump_func(#buf, buf, size)
/** Flag: make page_zip_validate() compare page headers only */
UNIV_INTERN ibool page_zip_validate_header_only = FALSE;
/**********************************************************************//**
Check that the compressed and decompressed pages match.
@return TRUE if valid, FALSE if not */
UNIV_INTERN
ibool
page_zip_validate_low(
/*==================*/
const page_zip_des_t* page_zip,/*!< in: compressed page */
const page_t* page, /*!< in: uncompressed page */
const dict_index_t* index, /*!< in: index of the page, if known */
ibool sloppy) /*!< in: FALSE=strict,
TRUE=ignore the MIN_REC_FLAG */
{
page_zip_des_t temp_page_zip;
byte* temp_page_buf;
page_t* temp_page;
ibool valid;
if (memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
FIL_PAGE_LSN - FIL_PAGE_PREV)
|| memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2)
|| memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
PAGE_DATA - FIL_PAGE_DATA)) {
page_zip_fail(("page_zip_validate: page header\n"));
page_zip_hexdump(page_zip, sizeof *page_zip);
page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip));
page_zip_hexdump(page, UNIV_PAGE_SIZE);
return(FALSE);
}
ut_a(page_is_comp(page));
if (page_zip_validate_header_only) {
return(TRUE);
}
/* page_zip_decompress() expects the uncompressed page to be
UNIV_PAGE_SIZE aligned. */
temp_page_buf = static_cast<byte*>(ut_malloc(2 * UNIV_PAGE_SIZE));
temp_page = static_cast<byte*>(ut_align(temp_page_buf, UNIV_PAGE_SIZE));
UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
temp_page_zip = *page_zip;
valid = page_zip_decompress(&temp_page_zip, temp_page, TRUE);
if (!valid) {
fputs("page_zip_validate(): failed to decompress\n", stderr);
goto func_exit;
}
if (page_zip->n_blobs != temp_page_zip.n_blobs) {
page_zip_fail(("page_zip_validate: n_blobs: %u!=%u\n",
page_zip->n_blobs, temp_page_zip.n_blobs));
valid = FALSE;
}
#ifdef UNIV_DEBUG
if (page_zip->m_start != temp_page_zip.m_start) {
page_zip_fail(("page_zip_validate: m_start: %u!=%u\n",
page_zip->m_start, temp_page_zip.m_start));
valid = FALSE;
}
#endif /* UNIV_DEBUG */
if (page_zip->m_end != temp_page_zip.m_end) {
page_zip_fail(("page_zip_validate: m_end: %u!=%u\n",
page_zip->m_end, temp_page_zip.m_end));
valid = FALSE;
}
if (page_zip->m_nonempty != temp_page_zip.m_nonempty) {
page_zip_fail(("page_zip_validate(): m_nonempty: %u!=%u\n",
page_zip->m_nonempty,
temp_page_zip.m_nonempty));
valid = FALSE;
}
if (memcmp(page + PAGE_HEADER, temp_page + PAGE_HEADER,
UNIV_PAGE_SIZE - PAGE_HEADER - FIL_PAGE_DATA_END)) {
/* In crash recovery, the "minimum record" flag may be
set incorrectly until the mini-transaction is
committed. Let us tolerate that difference when we
are performing a sloppy validation. */
ulint* offsets;
mem_heap_t* heap;
const rec_t* rec;
const rec_t* trec;
byte info_bits_diff;
ulint offset
= rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE);
ut_a(offset >= PAGE_NEW_SUPREMUM);
offset -= 5/*REC_NEW_INFO_BITS*/;
info_bits_diff = page[offset] ^ temp_page[offset];
if (info_bits_diff == REC_INFO_MIN_REC_FLAG) {
temp_page[offset] = page[offset];
if (!memcmp(page + PAGE_HEADER,
temp_page + PAGE_HEADER,
UNIV_PAGE_SIZE - PAGE_HEADER
- FIL_PAGE_DATA_END)) {
/* Only the minimum record flag
differed. Let us ignore it. */
page_zip_fail(("page_zip_validate: "
"min_rec_flag "
"(%s"
"%lu,%lu,0x%02lx)\n",
sloppy ? "ignored, " : "",
page_get_space_id(page),
page_get_page_no(page),
(ulong) page[offset]));
valid = sloppy;
goto func_exit;
}
}
/* Compare the pointers in the PAGE_FREE list. */
rec = page_header_get_ptr(page, PAGE_FREE);
trec = page_header_get_ptr(temp_page, PAGE_FREE);
while (rec || trec) {
if (page_offset(rec) != page_offset(trec)) {
page_zip_fail(("page_zip_validate: "
"PAGE_FREE list: %u!=%u\n",
(unsigned) page_offset(rec),
(unsigned) page_offset(trec)));
valid = FALSE;
goto func_exit;
}
rec = page_rec_get_next_low(rec, TRUE);
trec = page_rec_get_next_low(trec, TRUE);
}
/* Compare the records. */
heap = NULL;
offsets = NULL;
rec = page_rec_get_next_low(
page + PAGE_NEW_INFIMUM, TRUE);
trec = page_rec_get_next_low(
temp_page + PAGE_NEW_INFIMUM, TRUE);
do {
if (page_offset(rec) != page_offset(trec)) {
page_zip_fail(("page_zip_validate: "
"record list: 0x%02x!=0x%02x\n",
(unsigned) page_offset(rec),
(unsigned) page_offset(trec)));
valid = FALSE;
break;
}
if (index) {
/* Compare the data. */
offsets = rec_get_offsets(
rec, index, offsets,
ULINT_UNDEFINED, &heap);
if (memcmp(rec - rec_offs_extra_size(offsets),
trec - rec_offs_extra_size(offsets),
rec_offs_size(offsets))) {
page_zip_fail(
("page_zip_validate: "
"record content: 0x%02x",
(unsigned) page_offset(rec)));
valid = FALSE;
break;
}
}
rec = page_rec_get_next_low(rec, TRUE);
trec = page_rec_get_next_low(trec, TRUE);
} while (rec || trec);
if (heap) {
mem_heap_free(heap);
}
}
func_exit:
if (!valid) {
page_zip_hexdump(page_zip, sizeof *page_zip);
page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip));
page_zip_hexdump(page, UNIV_PAGE_SIZE);
page_zip_hexdump(temp_page, UNIV_PAGE_SIZE);
}
ut_free(temp_page_buf);
return(valid);
}
/**********************************************************************//**
Check that the compressed and decompressed pages match.
@return TRUE if valid, FALSE if not */
UNIV_INTERN
ibool
page_zip_validate(
/*==============*/
const page_zip_des_t* page_zip,/*!< in: compressed page */
const page_t* page, /*!< in: uncompressed page */
const dict_index_t* index) /*!< in: index of the page, if known */
{
return(page_zip_validate_low(page_zip, page, index,
recv_recovery_is_on()));
}
#endif /* UNIV_ZIP_DEBUG */
#ifdef UNIV_DEBUG
/**********************************************************************//**
Assert that the compressed and decompressed page headers match.
@return TRUE */
static
ibool
page_zip_header_cmp(
/*================*/
const page_zip_des_t* page_zip,/*!< in: compressed page */
const byte* page) /*!< in: uncompressed page */
{
ut_ad(!memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
FIL_PAGE_LSN - FIL_PAGE_PREV));
ut_ad(!memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE,
2));
ut_ad(!memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
PAGE_DATA - FIL_PAGE_DATA));
return(TRUE);
}
#endif /* UNIV_DEBUG */
/**********************************************************************//**
Write a record on the compressed page that contains externally stored
columns. The data must already have been written to the uncompressed page.
@return end of modification log */
static
byte*
page_zip_write_rec_ext(
/*===================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
const page_t* page, /*!< in: page containing rec */
const byte* rec, /*!< in: record being written */
dict_index_t* index, /*!< in: record descriptor */
const ulint* offsets, /*!< in: rec_get_offsets(rec, index) */
ulint create, /*!< in: nonzero=insert, zero=update */
ulint trx_id_col, /*!< in: position of DB_TRX_ID */
ulint heap_no, /*!< in: heap number of rec */
byte* storage, /*!< in: end of dense page directory */
byte* data) /*!< in: end of modification log */
{
const byte* start = rec;
ulint i;
ulint len;
byte* externs = storage;
ulint n_ext = rec_offs_n_extern(offsets);
ut_ad(rec_offs_validate(rec, index, offsets));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
externs -= (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
* (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW);
/* Note that this will not take into account
the BLOB columns of rec if create==TRUE. */
ut_ad(data + rec_offs_data_size(offsets)
- (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
- n_ext * BTR_EXTERN_FIELD_REF_SIZE
< externs - BTR_EXTERN_FIELD_REF_SIZE * page_zip->n_blobs);
{
ulint blob_no = page_zip_get_n_prev_extern(
page_zip, rec, index);
byte* ext_end = externs - page_zip->n_blobs
* BTR_EXTERN_FIELD_REF_SIZE;
ut_ad(blob_no <= page_zip->n_blobs);
externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE;
if (create) {
page_zip->n_blobs += static_cast<unsigned>(n_ext);
ASSERT_ZERO_BLOB(ext_end - n_ext
* BTR_EXTERN_FIELD_REF_SIZE);
memmove(ext_end - n_ext
* BTR_EXTERN_FIELD_REF_SIZE,
ext_end,
externs - ext_end);
}
ut_a(blob_no + n_ext <= page_zip->n_blobs);
}
for (i = 0; i < rec_offs_n_fields(offsets); i++) {
const byte* src;
if (UNIV_UNLIKELY(i == trx_id_col)) {
ut_ad(!rec_offs_nth_extern(offsets,
i));
ut_ad(!rec_offs_nth_extern(offsets,
i + 1));
/* Locate trx_id and roll_ptr. */
src = rec_get_nth_field(rec, offsets,
i, &len);
ut_ad(len == DATA_TRX_ID_LEN);
ut_ad(src + DATA_TRX_ID_LEN
== rec_get_nth_field(
rec, offsets,
i + 1, &len));
ut_ad(len == DATA_ROLL_PTR_LEN);
/* Log the preceding fields. */
ASSERT_ZERO(data, src - start);
memcpy(data, start, src - start);
data += src - start;
start = src + (DATA_TRX_ID_LEN
+ DATA_ROLL_PTR_LEN);
/* Store trx_id and roll_ptr. */
memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
* (heap_no - 1),
src, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
i++; /* skip also roll_ptr */
} else if (rec_offs_nth_extern(offsets, i)) {
src = rec_get_nth_field(rec, offsets,
i, &len);
ut_ad(dict_index_is_clust(index));
ut_ad(len
>= BTR_EXTERN_FIELD_REF_SIZE);
src += len - BTR_EXTERN_FIELD_REF_SIZE;
ASSERT_ZERO(data, src - start);
memcpy(data, start, src - start);
data += src - start;
start = src + BTR_EXTERN_FIELD_REF_SIZE;
/* Store the BLOB pointer. */
externs -= BTR_EXTERN_FIELD_REF_SIZE;
ut_ad(data < externs);
memcpy(externs, src, BTR_EXTERN_FIELD_REF_SIZE);
}
}
/* Log the last bytes of the record. */
len = rec_offs_data_size(offsets) - (start - rec);
ASSERT_ZERO(data, len);
memcpy(data, start, len);
data += len;
return(data);
}
/**********************************************************************//**
Write an entire record on the compressed page. The data must already
have been written to the uncompressed page. */
UNIV_INTERN
void
page_zip_write_rec(
/*===============*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
const byte* rec, /*!< in: record being written */
dict_index_t* index, /*!< in: the index the record belongs to */
const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
ulint create) /*!< in: nonzero=insert, zero=update */
{
const page_t* page;
byte* data;
byte* storage;
ulint heap_no;
byte* slot;
ut_ad(PAGE_ZIP_MATCH(rec, page_zip));
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(page_zip_get_size(page_zip)
> PAGE_DATA + page_zip_dir_size(page_zip));
ut_ad(rec_offs_comp(offsets));
ut_ad(rec_offs_validate(rec, index, offsets));
ut_ad(page_zip->m_start >= PAGE_DATA);
page = page_align(rec);
ut_ad(page_zip_header_cmp(page_zip, page));
ut_ad(page_simple_validate_new((page_t*) page));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
slot = page_zip_dir_find(page_zip, page_offset(rec));
ut_a(slot);
/* Copy the delete mark. */
if (rec_get_deleted_flag(rec, TRUE)) {
*slot |= PAGE_ZIP_DIR_SLOT_DEL >> 8;
} else {
*slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8);
}
ut_ad(rec_get_start((rec_t*) rec, offsets) >= page + PAGE_ZIP_START);
ut_ad(rec_get_end((rec_t*) rec, offsets) <= page + UNIV_PAGE_SIZE
- PAGE_DIR - PAGE_DIR_SLOT_SIZE
* page_dir_get_n_slots(page));
heap_no = rec_get_heap_no_new(rec);
ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW); /* not infimum or supremum */
ut_ad(heap_no < page_dir_get_n_heap(page));
/* Append to the modification log. */
data = page_zip->data + page_zip->m_end;
ut_ad(!*data);
/* Identify the record by writing its heap number - 1.
0 is reserved to indicate the end of the modification log. */
if (UNIV_UNLIKELY(heap_no - 1 >= 64)) {
*data++ = (byte) (0x80 | (heap_no - 1) >> 7);
ut_ad(!*data);
}
*data++ = (byte) ((heap_no - 1) << 1);
ut_ad(!*data);
{
const byte* start = rec - rec_offs_extra_size(offsets);
const byte* b = rec - REC_N_NEW_EXTRA_BYTES;
/* Write the extra bytes backwards, so that
rec_offs_extra_size() can be easily computed in
page_zip_apply_log() by invoking
rec_get_offsets_reverse(). */
while (b != start) {
*data++ = *--b;
ut_ad(!*data);
}
}
/* Write the data bytes. Store the uncompressed bytes separately. */
storage = page_zip_dir_start(page_zip);
if (page_is_leaf(page)) {
ulint len;
if (dict_index_is_clust(index)) {
ulint trx_id_col;
trx_id_col = dict_index_get_sys_col_pos(index,
DATA_TRX_ID);
ut_ad(trx_id_col != ULINT_UNDEFINED);
/* Store separately trx_id, roll_ptr and
the BTR_EXTERN_FIELD_REF of each BLOB column. */
if (rec_offs_any_extern(offsets)) {
data = page_zip_write_rec_ext(
page_zip, page,
rec, index, offsets, create,
trx_id_col, heap_no, storage, data);
} else {
/* Locate trx_id and roll_ptr. */
const byte* src
= rec_get_nth_field(rec, offsets,
trx_id_col, &len);
ut_ad(len == DATA_TRX_ID_LEN);
ut_ad(src + DATA_TRX_ID_LEN
== rec_get_nth_field(
rec, offsets,
trx_id_col + 1, &len));
ut_ad(len == DATA_ROLL_PTR_LEN);
/* Log the preceding fields. */
ASSERT_ZERO(data, src - rec);
memcpy(data, rec, src - rec);
data += src - rec;
/* Store trx_id and roll_ptr. */
memcpy(storage
- (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
* (heap_no - 1),
src,
DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
src += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
/* Log the last bytes of the record. */
len = rec_offs_data_size(offsets)
- (src - rec);
ASSERT_ZERO(data, len);
memcpy(data, src, len);
data += len;
}
} else {
/* Leaf page of a secondary index:
no externally stored columns */
ut_ad(dict_index_get_sys_col_pos(index, DATA_TRX_ID)
== ULINT_UNDEFINED);
ut_ad(!rec_offs_any_extern(offsets));
/* Log the entire record. */
len = rec_offs_data_size(offsets);
ASSERT_ZERO(data, len);
memcpy(data, rec, len);
data += len;
}
} else {
/* This is a node pointer page. */
ulint len;
/* Non-leaf nodes should not have any externally
stored columns. */
ut_ad(!rec_offs_any_extern(offsets));
/* Copy the data bytes, except node_ptr. */
len = rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE;
ut_ad(data + len < storage - REC_NODE_PTR_SIZE
* (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW));
ASSERT_ZERO(data, len);
memcpy(data, rec, len);
data += len;
/* Copy the node pointer to the uncompressed area. */
memcpy(storage - REC_NODE_PTR_SIZE
* (heap_no - 1),
rec + len,
REC_NODE_PTR_SIZE);
}
ut_a(!*data);
ut_ad((ulint) (data - page_zip->data) < page_zip_get_size(page_zip));
page_zip->m_end = data - page_zip->data;
page_zip->m_nonempty = TRUE;
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page_align(rec), index));
#endif /* UNIV_ZIP_DEBUG */
}
/***********************************************************//**
Parses a log record of writing a BLOB pointer of a record.
@return end of log record or NULL */
UNIV_INTERN
byte*
page_zip_parse_write_blob_ptr(
/*==========================*/
byte* ptr, /*!< in: redo log buffer */
byte* end_ptr,/*!< in: redo log buffer end */
page_t* page, /*!< in/out: uncompressed page */
page_zip_des_t* page_zip)/*!< in/out: compressed page */
{
ulint offset;
ulint z_offset;
ut_ad(!page == !page_zip);
if (UNIV_UNLIKELY
(end_ptr < ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE))) {
return(NULL);
}
offset = mach_read_from_2(ptr);
z_offset = mach_read_from_2(ptr + 2);
if (UNIV_UNLIKELY(offset < PAGE_ZIP_START)
|| UNIV_UNLIKELY(offset >= UNIV_PAGE_SIZE)
|| UNIV_UNLIKELY(z_offset >= UNIV_PAGE_SIZE)) {
corrupt:
recv_sys->found_corrupt_log = TRUE;
return(NULL);
}
if (page) {
if (UNIV_UNLIKELY(!page_zip)
|| UNIV_UNLIKELY(!page_is_leaf(page))) {
goto corrupt;
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
memcpy(page + offset,
ptr + 4, BTR_EXTERN_FIELD_REF_SIZE);
memcpy(page_zip->data + z_offset,
ptr + 4, BTR_EXTERN_FIELD_REF_SIZE);
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
}
return(ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE));
}
/**********************************************************************//**
Write a BLOB pointer of a record on the leaf page of a clustered index.
The information must already have been updated on the uncompressed page. */
UNIV_INTERN
void
page_zip_write_blob_ptr(
/*====================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
const byte* rec, /*!< in/out: record whose data is being
written */
dict_index_t* index, /*!< in: index of the page */
const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
ulint n, /*!< in: column index */
mtr_t* mtr) /*!< in: mini-transaction handle,
or NULL if no logging is needed */
{
const byte* field;
byte* externs;
const page_t* page = page_align(rec);
ulint blob_no;
ulint len;
ut_ad(PAGE_ZIP_MATCH(rec, page_zip));
ut_ad(page_simple_validate_new((page_t*) page));
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(page_zip_get_size(page_zip)
> PAGE_DATA + page_zip_dir_size(page_zip));
ut_ad(rec_offs_comp(offsets));
ut_ad(rec_offs_validate(rec, NULL, offsets));
ut_ad(rec_offs_any_extern(offsets));
ut_ad(rec_offs_nth_extern(offsets, n));
ut_ad(page_zip->m_start >= PAGE_DATA);
ut_ad(page_zip_header_cmp(page_zip, page));
ut_ad(page_is_leaf(page));
ut_ad(dict_index_is_clust(index));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
blob_no = page_zip_get_n_prev_extern(page_zip, rec, index)
+ rec_get_n_extern_new(rec, index, n);
ut_a(blob_no < page_zip->n_blobs);
externs = page_zip->data + page_zip_get_size(page_zip)
- (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW)
* (PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
field = rec_get_nth_field(rec, offsets, n, &len);
externs -= (blob_no + 1) * BTR_EXTERN_FIELD_REF_SIZE;
field += len - BTR_EXTERN_FIELD_REF_SIZE;
memcpy(externs, field, BTR_EXTERN_FIELD_REF_SIZE);
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
if (mtr) {
#ifndef UNIV_HOTBACKUP
byte* log_ptr = mlog_open(
mtr, 11 + 2 + 2 + BTR_EXTERN_FIELD_REF_SIZE);
if (UNIV_UNLIKELY(!log_ptr)) {
return;
}
log_ptr = mlog_write_initial_log_record_fast(
(byte*) field, MLOG_ZIP_WRITE_BLOB_PTR, log_ptr, mtr);
mach_write_to_2(log_ptr, page_offset(field));
log_ptr += 2;
mach_write_to_2(log_ptr, externs - page_zip->data);
log_ptr += 2;
memcpy(log_ptr, externs, BTR_EXTERN_FIELD_REF_SIZE);
log_ptr += BTR_EXTERN_FIELD_REF_SIZE;
mlog_close(mtr, log_ptr);
#endif /* !UNIV_HOTBACKUP */
}
}
/***********************************************************//**
Parses a log record of writing the node pointer of a record.
@return end of log record or NULL */
UNIV_INTERN
byte*
page_zip_parse_write_node_ptr(
/*==========================*/
byte* ptr, /*!< in: redo log buffer */
byte* end_ptr,/*!< in: redo log buffer end */
page_t* page, /*!< in/out: uncompressed page */
page_zip_des_t* page_zip)/*!< in/out: compressed page */
{
ulint offset;
ulint z_offset;
ut_ad(!page == !page_zip);
if (UNIV_UNLIKELY(end_ptr < ptr + (2 + 2 + REC_NODE_PTR_SIZE))) {
return(NULL);
}
offset = mach_read_from_2(ptr);
z_offset = mach_read_from_2(ptr + 2);
if (UNIV_UNLIKELY(offset < PAGE_ZIP_START)
|| UNIV_UNLIKELY(offset >= UNIV_PAGE_SIZE)
|| UNIV_UNLIKELY(z_offset >= UNIV_PAGE_SIZE)) {
corrupt:
recv_sys->found_corrupt_log = TRUE;
return(NULL);
}
if (page) {
byte* storage_end;
byte* field;
byte* storage;
ulint heap_no;
if (UNIV_UNLIKELY(!page_zip)
|| UNIV_UNLIKELY(page_is_leaf(page))) {
goto corrupt;
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
field = page + offset;
storage = page_zip->data + z_offset;
storage_end = page_zip_dir_start(page_zip);
heap_no = 1 + (storage_end - storage) / REC_NODE_PTR_SIZE;
if (UNIV_UNLIKELY((storage_end - storage) % REC_NODE_PTR_SIZE)
|| UNIV_UNLIKELY(heap_no < PAGE_HEAP_NO_USER_LOW)
|| UNIV_UNLIKELY(heap_no >= page_dir_get_n_heap(page))) {
goto corrupt;
}
memcpy(field, ptr + 4, REC_NODE_PTR_SIZE);
memcpy(storage, ptr + 4, REC_NODE_PTR_SIZE);
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
}
return(ptr + (2 + 2 + REC_NODE_PTR_SIZE));
}
/**********************************************************************//**
Write the node pointer of a record on a non-leaf compressed page. */
UNIV_INTERN
void
page_zip_write_node_ptr(
/*====================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
byte* rec, /*!< in/out: record */
ulint size, /*!< in: data size of rec */
ulint ptr, /*!< in: node pointer */
mtr_t* mtr) /*!< in: mini-transaction, or NULL */
{
byte* field;
byte* storage;
#ifdef UNIV_DEBUG
page_t* page = page_align(rec);
#endif /* UNIV_DEBUG */
ut_ad(PAGE_ZIP_MATCH(rec, page_zip));
ut_ad(page_simple_validate_new(page));
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(page_zip_get_size(page_zip)
> PAGE_DATA + page_zip_dir_size(page_zip));
ut_ad(page_rec_is_comp(rec));
ut_ad(page_zip->m_start >= PAGE_DATA);
ut_ad(page_zip_header_cmp(page_zip, page));
ut_ad(!page_is_leaf(page));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(rec, size);
storage = page_zip_dir_start(page_zip)
- (rec_get_heap_no_new(rec) - 1) * REC_NODE_PTR_SIZE;
field = rec + size - REC_NODE_PTR_SIZE;
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
ut_a(!memcmp(storage, field, REC_NODE_PTR_SIZE));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
#if REC_NODE_PTR_SIZE != 4
# error "REC_NODE_PTR_SIZE != 4"
#endif
mach_write_to_4(field, ptr);
memcpy(storage, field, REC_NODE_PTR_SIZE);
if (mtr) {
#ifndef UNIV_HOTBACKUP
byte* log_ptr = mlog_open(mtr,
11 + 2 + 2 + REC_NODE_PTR_SIZE);
if (UNIV_UNLIKELY(!log_ptr)) {
return;
}
log_ptr = mlog_write_initial_log_record_fast(
field, MLOG_ZIP_WRITE_NODE_PTR, log_ptr, mtr);
mach_write_to_2(log_ptr, page_offset(field));
log_ptr += 2;
mach_write_to_2(log_ptr, storage - page_zip->data);
log_ptr += 2;
memcpy(log_ptr, field, REC_NODE_PTR_SIZE);
log_ptr += REC_NODE_PTR_SIZE;
mlog_close(mtr, log_ptr);
#endif /* !UNIV_HOTBACKUP */
}
}
/**********************************************************************//**
Write the trx_id and roll_ptr of a record on a B-tree leaf node page. */
UNIV_INTERN
void
page_zip_write_trx_id_and_roll_ptr(
/*===============================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
byte* rec, /*!< in/out: record */
const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
ulint trx_id_col,/*!< in: column number of TRX_ID in rec */
trx_id_t trx_id, /*!< in: transaction identifier */
roll_ptr_t roll_ptr)/*!< in: roll_ptr */
{
byte* field;
byte* storage;
#ifdef UNIV_DEBUG
page_t* page = page_align(rec);
#endif /* UNIV_DEBUG */
ulint len;
ut_ad(PAGE_ZIP_MATCH(rec, page_zip));
ut_ad(page_simple_validate_new(page));
ut_ad(page_zip_simple_validate(page_zip));
ut_ad(page_zip_get_size(page_zip)
> PAGE_DATA + page_zip_dir_size(page_zip));
ut_ad(rec_offs_validate(rec, NULL, offsets));
ut_ad(rec_offs_comp(offsets));
ut_ad(page_zip->m_start >= PAGE_DATA);
ut_ad(page_zip_header_cmp(page_zip, page));
ut_ad(page_is_leaf(page));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
storage = page_zip_dir_start(page_zip)
- (rec_get_heap_no_new(rec) - 1)
* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
#if DATA_TRX_ID + 1 != DATA_ROLL_PTR
# error "DATA_TRX_ID + 1 != DATA_ROLL_PTR"
#endif
field = rec_get_nth_field(rec, offsets, trx_id_col, &len);
ut_ad(len == DATA_TRX_ID_LEN);
ut_ad(field + DATA_TRX_ID_LEN
== rec_get_nth_field(rec, offsets, trx_id_col + 1, &len));
ut_ad(len == DATA_ROLL_PTR_LEN);
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
ut_a(!memcmp(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
#if DATA_TRX_ID_LEN != 6
# error "DATA_TRX_ID_LEN != 6"
#endif
mach_write_to_6(field, trx_id);
#if DATA_ROLL_PTR_LEN != 7
# error "DATA_ROLL_PTR_LEN != 7"
#endif
mach_write_to_7(field + DATA_TRX_ID_LEN, roll_ptr);
memcpy(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
}
/**********************************************************************//**
Clear an area on the uncompressed and compressed page.
Do not clear the data payload, as that would grow the modification log. */
static
void
page_zip_clear_rec(
/*===============*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
byte* rec, /*!< in: record to clear */
const dict_index_t* index, /*!< in: index of rec */
const ulint* offsets) /*!< in: rec_get_offsets(rec, index) */
{
ulint heap_no;
page_t* page = page_align(rec);
byte* storage;
byte* field;
ulint len;
/* page_zip_validate() would fail here if a record
containing externally stored columns is being deleted. */
ut_ad(rec_offs_validate(rec, index, offsets));
ut_ad(!page_zip_dir_find(page_zip, page_offset(rec)));
ut_ad(page_zip_dir_find_free(page_zip, page_offset(rec)));
ut_ad(page_zip_header_cmp(page_zip, page));
heap_no = rec_get_heap_no_new(rec);
ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
if (!page_is_leaf(page)) {
/* Clear node_ptr. On the compressed page,
there is an array of node_ptr immediately before the
dense page directory, at the very end of the page. */
storage = page_zip_dir_start(page_zip);
ut_ad(dict_index_get_n_unique_in_tree(index) ==
rec_offs_n_fields(offsets) - 1);
field = rec_get_nth_field(rec, offsets,
rec_offs_n_fields(offsets) - 1,
&len);
ut_ad(len == REC_NODE_PTR_SIZE);
ut_ad(!rec_offs_any_extern(offsets));
memset(field, 0, REC_NODE_PTR_SIZE);
memset(storage - (heap_no - 1) * REC_NODE_PTR_SIZE,
0, REC_NODE_PTR_SIZE);
} else if (dict_index_is_clust(index)) {
/* Clear trx_id and roll_ptr. On the compressed page,
there is an array of these fields immediately before the
dense page directory, at the very end of the page. */
const ulint trx_id_pos
= dict_col_get_clust_pos(
dict_table_get_sys_col(
index->table, DATA_TRX_ID), index);
storage = page_zip_dir_start(page_zip);
field = rec_get_nth_field(rec, offsets, trx_id_pos, &len);
ut_ad(len == DATA_TRX_ID_LEN);
memset(field, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
memset(storage - (heap_no - 1)
* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN),
0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
if (rec_offs_any_extern(offsets)) {
ulint i;
for (i = rec_offs_n_fields(offsets); i--; ) {
/* Clear all BLOB pointers in order to make
page_zip_validate() pass. */
if (rec_offs_nth_extern(offsets, i)) {
field = rec_get_nth_field(
rec, offsets, i, &len);
ut_ad(len
== BTR_EXTERN_FIELD_REF_SIZE);
memset(field + len
- BTR_EXTERN_FIELD_REF_SIZE,
0, BTR_EXTERN_FIELD_REF_SIZE);
}
}
}
} else {
ut_ad(!rec_offs_any_extern(offsets));
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
}
/**********************************************************************//**
Write the "deleted" flag of a record on a compressed page. The flag must
already have been written on the uncompressed page. */
UNIV_INTERN
void
page_zip_rec_set_deleted(
/*=====================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
const byte* rec, /*!< in: record on the uncompressed page */
ulint flag) /*!< in: the deleted flag (nonzero=TRUE) */
{
byte* slot = page_zip_dir_find(page_zip, page_offset(rec));
ut_a(slot);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
if (flag) {
*slot |= (PAGE_ZIP_DIR_SLOT_DEL >> 8);
} else {
*slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8);
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page_align(rec), NULL));
#endif /* UNIV_ZIP_DEBUG */
}
/**********************************************************************//**
Write the "owned" flag of a record on a compressed page. The n_owned field
must already have been written on the uncompressed page. */
UNIV_INTERN
void
page_zip_rec_set_owned(
/*===================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
const byte* rec, /*!< in: record on the uncompressed page */
ulint flag) /*!< in: the owned flag (nonzero=TRUE) */
{
byte* slot = page_zip_dir_find(page_zip, page_offset(rec));
ut_a(slot);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
if (flag) {
*slot |= (PAGE_ZIP_DIR_SLOT_OWNED >> 8);
} else {
*slot &= ~(PAGE_ZIP_DIR_SLOT_OWNED >> 8);
}
}
/**********************************************************************//**
Insert a record to the dense page directory. */
UNIV_INTERN
void
page_zip_dir_insert(
/*================*/
page_zip_des_t* page_zip,/*!< in/out: compressed page */
const byte* prev_rec,/*!< in: record after which to insert */
const byte* free_rec,/*!< in: record from which rec was
allocated, or NULL */
byte* rec) /*!< in: record to insert */
{
ulint n_dense;
byte* slot_rec;
byte* slot_free;
ut_ad(prev_rec != rec);
ut_ad(page_rec_get_next((rec_t*) prev_rec) == rec);
ut_ad(page_zip_simple_validate(page_zip));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
if (page_rec_is_infimum(prev_rec)) {
/* Use the first slot. */
slot_rec = page_zip->data + page_zip_get_size(page_zip);
} else {
byte* end = page_zip->data + page_zip_get_size(page_zip);
byte* start = end - page_zip_dir_user_size(page_zip);
if (UNIV_LIKELY(!free_rec)) {
/* PAGE_N_RECS was already incremented
in page_cur_insert_rec_zip(), but the
dense directory slot at that position
contains garbage. Skip it. */
start += PAGE_ZIP_DIR_SLOT_SIZE;
}
slot_rec = page_zip_dir_find_low(start, end,
page_offset(prev_rec));
ut_a(slot_rec);
}
/* Read the old n_dense (n_heap may have been incremented). */
n_dense = page_dir_get_n_heap(page_zip->data)
- (PAGE_HEAP_NO_USER_LOW + 1);
if (UNIV_LIKELY_NULL(free_rec)) {
/* The record was allocated from the free list.
Shift the dense directory only up to that slot.
Note that in this case, n_dense is actually
off by one, because page_cur_insert_rec_zip()
did not increment n_heap. */
ut_ad(rec_get_heap_no_new(rec) < n_dense + 1
+ PAGE_HEAP_NO_USER_LOW);
ut_ad(rec >= free_rec);
slot_free = page_zip_dir_find(page_zip, page_offset(free_rec));
ut_ad(slot_free);
slot_free += PAGE_ZIP_DIR_SLOT_SIZE;
} else {
/* The record was allocated from the heap.
Shift the entire dense directory. */
ut_ad(rec_get_heap_no_new(rec) == n_dense
+ PAGE_HEAP_NO_USER_LOW);
/* Shift to the end of the dense page directory. */
slot_free = page_zip->data + page_zip_get_size(page_zip)
- PAGE_ZIP_DIR_SLOT_SIZE * n_dense;
}
/* Shift the dense directory to allocate place for rec. */
memmove(slot_free - PAGE_ZIP_DIR_SLOT_SIZE, slot_free,
slot_rec - slot_free);
/* Write the entry for the inserted record.
The "owned" and "deleted" flags must be zero. */
mach_write_to_2(slot_rec - PAGE_ZIP_DIR_SLOT_SIZE, page_offset(rec));
}
/**********************************************************************//**
Shift the dense page directory and the array of BLOB pointers
when a record is deleted. */
UNIV_INTERN
void
page_zip_dir_delete(
/*================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
byte* rec, /*!< in: deleted record */
const dict_index_t* index, /*!< in: index of rec */
const ulint* offsets, /*!< in: rec_get_offsets(rec) */
const byte* free) /*!< in: previous start of
the free list */
{
byte* slot_rec;
byte* slot_free;
ulint n_ext;
page_t* page = page_align(rec);
ut_ad(rec_offs_validate(rec, index, offsets));
ut_ad(rec_offs_comp(offsets));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
rec_offs_extra_size(offsets));
slot_rec = page_zip_dir_find(page_zip, page_offset(rec));
ut_a(slot_rec);
/* This could not be done before page_zip_dir_find(). */
page_header_set_field(page, page_zip, PAGE_N_RECS,
(ulint)(page_get_n_recs(page) - 1));
if (UNIV_UNLIKELY(!free)) {
/* Make the last slot the start of the free list. */
slot_free = page_zip->data + page_zip_get_size(page_zip)
- PAGE_ZIP_DIR_SLOT_SIZE
* (page_dir_get_n_heap(page_zip->data)
- PAGE_HEAP_NO_USER_LOW);
} else {
slot_free = page_zip_dir_find_free(page_zip,
page_offset(free));
ut_a(slot_free < slot_rec);
/* Grow the free list by one slot by moving the start. */
slot_free += PAGE_ZIP_DIR_SLOT_SIZE;
}
if (UNIV_LIKELY(slot_rec > slot_free)) {
memmove(slot_free + PAGE_ZIP_DIR_SLOT_SIZE,
slot_free,
slot_rec - slot_free);
}
/* Write the entry for the deleted record.
The "owned" and "deleted" flags will be cleared. */
mach_write_to_2(slot_free, page_offset(rec));
if (!page_is_leaf(page) || !dict_index_is_clust(index)) {
ut_ad(!rec_offs_any_extern(offsets));
goto skip_blobs;
}
n_ext = rec_offs_n_extern(offsets);
if (UNIV_UNLIKELY(n_ext)) {
/* Shift and zero fill the array of BLOB pointers. */
ulint blob_no;
byte* externs;
byte* ext_end;
blob_no = page_zip_get_n_prev_extern(page_zip, rec, index);
ut_a(blob_no + n_ext <= page_zip->n_blobs);
externs = page_zip->data + page_zip_get_size(page_zip)
- (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW)
* (PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
ext_end = externs - page_zip->n_blobs
* BTR_EXTERN_FIELD_REF_SIZE;
externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE;
page_zip->n_blobs -= static_cast<unsigned>(n_ext);
/* Shift and zero fill the array. */
memmove(ext_end + n_ext * BTR_EXTERN_FIELD_REF_SIZE, ext_end,
(page_zip->n_blobs - blob_no)
* BTR_EXTERN_FIELD_REF_SIZE);
memset(ext_end, 0, n_ext * BTR_EXTERN_FIELD_REF_SIZE);
}
skip_blobs:
/* The compression algorithm expects info_bits and n_owned
to be 0 for deleted records. */
rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */
page_zip_clear_rec(page_zip, rec, index, offsets);
}
/**********************************************************************//**
Add a slot to the dense page directory. */
UNIV_INTERN
void
page_zip_dir_add_slot(
/*==================*/
page_zip_des_t* page_zip, /*!< in/out: compressed page */
ulint is_clustered) /*!< in: nonzero for clustered index,
zero for others */
{
ulint n_dense;
byte* dir;
byte* stored;
ut_ad(page_is_comp(page_zip->data));
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
/* Read the old n_dense (n_heap has already been incremented). */
n_dense = page_dir_get_n_heap(page_zip->data)
- (PAGE_HEAP_NO_USER_LOW + 1);
dir = page_zip->data + page_zip_get_size(page_zip)
- PAGE_ZIP_DIR_SLOT_SIZE * n_dense;
if (!page_is_leaf(page_zip->data)) {
ut_ad(!page_zip->n_blobs);
stored = dir - n_dense * REC_NODE_PTR_SIZE;
} else if (is_clustered) {
/* Move the BLOB pointer array backwards to make space for the
roll_ptr and trx_id columns and the dense directory slot. */
byte* externs;
stored = dir - n_dense
* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
externs = stored
- page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
ASSERT_ZERO(externs
- (PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN),
PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
memmove(externs - (PAGE_ZIP_DIR_SLOT_SIZE
+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN),
externs, stored - externs);
} else {
stored = dir
- page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
ASSERT_ZERO(stored - PAGE_ZIP_DIR_SLOT_SIZE,
PAGE_ZIP_DIR_SLOT_SIZE);
}
/* Move the uncompressed area backwards to make space
for one directory slot. */
memmove(stored - PAGE_ZIP_DIR_SLOT_SIZE, stored, dir - stored);
}
/***********************************************************//**
Parses a log record of writing to the header of a page.
@return end of log record or NULL */
UNIV_INTERN
byte*
page_zip_parse_write_header(
/*========================*/
byte* ptr, /*!< in: redo log buffer */
byte* end_ptr,/*!< in: redo log buffer end */
page_t* page, /*!< in/out: uncompressed page */
page_zip_des_t* page_zip)/*!< in/out: compressed page */
{
ulint offset;
ulint len;
ut_ad(ptr && end_ptr);
ut_ad(!page == !page_zip);
if (UNIV_UNLIKELY(end_ptr < ptr + (1 + 1))) {
return(NULL);
}
offset = (ulint) *ptr++;
len = (ulint) *ptr++;
if (UNIV_UNLIKELY(!len) || UNIV_UNLIKELY(offset + len >= PAGE_DATA)) {
corrupt:
recv_sys->found_corrupt_log = TRUE;
return(NULL);
}
if (UNIV_UNLIKELY(end_ptr < ptr + len)) {
return(NULL);
}
if (page) {
if (UNIV_UNLIKELY(!page_zip)) {
goto corrupt;
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
memcpy(page + offset, ptr, len);
memcpy(page_zip->data + offset, ptr, len);
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
}
return(ptr + len);
}
#ifndef UNIV_HOTBACKUP
/**********************************************************************//**
Write a log record of writing to the uncompressed header portion of a page. */
UNIV_INTERN
void
page_zip_write_header_log(
/*======================*/
const byte* data, /*!< in: data on the uncompressed page */
ulint length, /*!< in: length of the data */
mtr_t* mtr) /*!< in: mini-transaction */
{
byte* log_ptr = mlog_open(mtr, 11 + 1 + 1);
ulint offset = page_offset(data);
ut_ad(offset < PAGE_DATA);
ut_ad(offset + length < PAGE_DATA);
#if PAGE_DATA > 255
# error "PAGE_DATA > 255"
#endif
ut_ad(length < 256);
/* If no logging is requested, we may return now */
if (UNIV_UNLIKELY(!log_ptr)) {
return;
}
log_ptr = mlog_write_initial_log_record_fast(
(byte*) data, MLOG_ZIP_WRITE_HEADER, log_ptr, mtr);
*log_ptr++ = (byte) offset;
*log_ptr++ = (byte) length;
mlog_close(mtr, log_ptr);
mlog_catenate_string(mtr, data, length);
}
#endif /* !UNIV_HOTBACKUP */
/**********************************************************************//**
Reorganize and compress a page. This is a low-level operation for
compressed pages, to be used when page_zip_compress() fails.
On success, a redo log entry MLOG_ZIP_PAGE_COMPRESS will be written.
The function btr_page_reorganize() should be preferred whenever possible.
IMPORTANT: if page_zip_reorganize() is invoked on a leaf page of a
non-clustered index, the caller must update the insert buffer free
bits in the same mini-transaction in such a way that the modification
will be redo-logged.
@return TRUE on success, FALSE on failure; page_zip will be left
intact on failure, but page will be overwritten. */
UNIV_INTERN
ibool
page_zip_reorganize(
/*================*/
buf_block_t* block, /*!< in/out: page with compressed page;
on the compressed page, in: size;
out: data, n_blobs,
m_start, m_end, m_nonempty */
dict_index_t* index, /*!< in: index of the B-tree node */
mtr_t* mtr) /*!< in: mini-transaction */
{
#ifndef UNIV_HOTBACKUP
buf_pool_t* buf_pool = buf_pool_from_block(block);
#endif /* !UNIV_HOTBACKUP */
page_zip_des_t* page_zip = buf_block_get_page_zip(block);
page_t* page = buf_block_get_frame(block);
buf_block_t* temp_block;
page_t* temp_page;
ulint log_mode;
ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
ut_ad(page_is_comp(page));
ut_ad(!dict_index_is_ibuf(index));
/* Note that page_zip_validate(page_zip, page, index) may fail here. */
UNIV_MEM_ASSERT_RW(page, UNIV_PAGE_SIZE);
UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
/* Disable logging */
log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE);
#ifndef UNIV_HOTBACKUP
temp_block = buf_block_alloc(buf_pool);
btr_search_drop_page_hash_index(block);
block->check_index_page_at_flush = TRUE;
#else /* !UNIV_HOTBACKUP */
ut_ad(block == back_block1);
temp_block = back_block2;
#endif /* !UNIV_HOTBACKUP */
temp_page = temp_block->frame;
/* Copy the old page to temporary space */
buf_frame_copy(temp_page, page);
btr_blob_dbg_remove(page, index, "zip_reorg");
/* Recreate the page: note that global data on page (possible
segment headers, next page-field, etc.) is preserved intact */
page_create(block, mtr, TRUE);
/* Copy the records from the temporary space to the recreated page;
do not copy the lock bits yet */
page_copy_rec_list_end_no_locks(block, temp_block,
page_get_infimum_rec(temp_page),
index, mtr);
if (!dict_index_is_clust(index) && page_is_leaf(temp_page)) {
/* Copy max trx id to recreated page */
trx_id_t max_trx_id = page_get_max_trx_id(temp_page);
page_set_max_trx_id(block, NULL, max_trx_id, NULL);
ut_ad(max_trx_id != 0);
}
/* Restore logging. */
mtr_set_log_mode(mtr, log_mode);
if (!page_zip_compress(page_zip, page, index,
page_zip_compression_flags, mtr)) {
#ifndef UNIV_HOTBACKUP
buf_block_free(temp_block);
#endif /* !UNIV_HOTBACKUP */
return(FALSE);
}
lock_move_reorganize_page(block, temp_block);
#ifndef UNIV_HOTBACKUP
buf_block_free(temp_block);
#endif /* !UNIV_HOTBACKUP */
return(TRUE);
}
#ifndef UNIV_HOTBACKUP
/**********************************************************************//**
Copy the records of a page byte for byte. Do not copy the page header
or trailer, except those B-tree header fields that are directly
related to the storage of records. Also copy PAGE_MAX_TRX_ID.
NOTE: The caller must update the lock table and the adaptive hash index. */
UNIV_INTERN
void
page_zip_copy_recs(
/*===============*/
page_zip_des_t* page_zip, /*!< out: copy of src_zip
(n_blobs, m_start, m_end,
m_nonempty, data[0..size-1]) */
page_t* page, /*!< out: copy of src */
const page_zip_des_t* src_zip, /*!< in: compressed page */
const page_t* src, /*!< in: page */
dict_index_t* index, /*!< in: index of the B-tree */
mtr_t* mtr) /*!< in: mini-transaction */
{
ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX));
ut_ad(mtr_memo_contains_page(mtr, src, MTR_MEMO_PAGE_X_FIX));
ut_ad(!dict_index_is_ibuf(index));
#ifdef UNIV_ZIP_DEBUG
/* The B-tree operations that call this function may set
FIL_PAGE_PREV or PAGE_LEVEL, causing a temporary min_rec_flag
mismatch. A strict page_zip_validate() will be executed later
during the B-tree operations. */
ut_a(page_zip_validate_low(src_zip, src, index, TRUE));
#endif /* UNIV_ZIP_DEBUG */
ut_a(page_zip_get_size(page_zip) == page_zip_get_size(src_zip));
if (UNIV_UNLIKELY(src_zip->n_blobs)) {
ut_a(page_is_leaf(src));
ut_a(dict_index_is_clust(index));
}
/* The PAGE_MAX_TRX_ID must be set on leaf pages of secondary
indexes. It does not matter on other pages. */
ut_a(dict_index_is_clust(index) || !page_is_leaf(src)
|| page_get_max_trx_id(src));
UNIV_MEM_ASSERT_W(page, UNIV_PAGE_SIZE);
UNIV_MEM_ASSERT_W(page_zip->data, page_zip_get_size(page_zip));
UNIV_MEM_ASSERT_RW(src, UNIV_PAGE_SIZE);
UNIV_MEM_ASSERT_RW(src_zip->data, page_zip_get_size(page_zip));
/* Copy those B-tree page header fields that are related to
the records stored in the page. Also copy the field
PAGE_MAX_TRX_ID. Skip the rest of the page header and
trailer. On the compressed page, there is no trailer. */
#if PAGE_MAX_TRX_ID + 8 != PAGE_HEADER_PRIV_END
# error "PAGE_MAX_TRX_ID + 8 != PAGE_HEADER_PRIV_END"
#endif
memcpy(PAGE_HEADER + page, PAGE_HEADER + src,
PAGE_HEADER_PRIV_END);
memcpy(PAGE_DATA + page, PAGE_DATA + src,
UNIV_PAGE_SIZE - PAGE_DATA - FIL_PAGE_DATA_END);
memcpy(PAGE_HEADER + page_zip->data, PAGE_HEADER + src_zip->data,
PAGE_HEADER_PRIV_END);
memcpy(PAGE_DATA + page_zip->data, PAGE_DATA + src_zip->data,
page_zip_get_size(page_zip) - PAGE_DATA);
/* Copy all fields of src_zip to page_zip, except the pointer
to the compressed data page. */
{
page_zip_t* data = page_zip->data;
memcpy(page_zip, src_zip, sizeof *page_zip);
page_zip->data = data;
}
ut_ad(page_zip_get_trailer_len(page_zip, dict_index_is_clust(index))
+ page_zip->m_end < page_zip_get_size(page_zip));
if (!page_is_leaf(src)
&& UNIV_UNLIKELY(mach_read_from_4(src + FIL_PAGE_PREV) == FIL_NULL)
&& UNIV_LIKELY(mach_read_from_4(page
+ FIL_PAGE_PREV) != FIL_NULL)) {
/* Clear the REC_INFO_MIN_REC_FLAG of the first user record. */
ulint offs = rec_get_next_offs(page + PAGE_NEW_INFIMUM,
TRUE);
if (UNIV_LIKELY(offs != PAGE_NEW_SUPREMUM)) {
rec_t* rec = page + offs;
ut_a(rec[-REC_N_NEW_EXTRA_BYTES]
& REC_INFO_MIN_REC_FLAG);
rec[-REC_N_NEW_EXTRA_BYTES] &= ~ REC_INFO_MIN_REC_FLAG;
}
}
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
btr_blob_dbg_add(page, index, "page_zip_copy_recs");
page_zip_compress_write_log(page_zip, page, index, mtr);
}
#endif /* !UNIV_HOTBACKUP */
/**********************************************************************//**
Parses a log record of compressing an index page.
@return end of log record or NULL */
UNIV_INTERN
byte*
page_zip_parse_compress(
/*====================*/
byte* ptr, /*!< in: buffer */
byte* end_ptr,/*!< in: buffer end */
page_t* page, /*!< out: uncompressed page */
page_zip_des_t* page_zip)/*!< out: compressed page */
{
ulint size;
ulint trailer_size;
ut_ad(ptr && end_ptr);
ut_ad(!page == !page_zip);
if (UNIV_UNLIKELY(ptr + (2 + 2) > end_ptr)) {
return(NULL);
}
size = mach_read_from_2(ptr);
ptr += 2;
trailer_size = mach_read_from_2(ptr);
ptr += 2;
if (UNIV_UNLIKELY(ptr + 8 + size + trailer_size > end_ptr)) {
return(NULL);
}
if (page) {
if (UNIV_UNLIKELY(!page_zip)
|| UNIV_UNLIKELY(page_zip_get_size(page_zip) < size)) {
corrupt:
recv_sys->found_corrupt_log = TRUE;
return(NULL);
}
memcpy(page_zip->data + FIL_PAGE_PREV, ptr, 4);
memcpy(page_zip->data + FIL_PAGE_NEXT, ptr + 4, 4);
memcpy(page_zip->data + FIL_PAGE_TYPE, ptr + 8, size);
memset(page_zip->data + FIL_PAGE_TYPE + size, 0,
page_zip_get_size(page_zip) - trailer_size
- (FIL_PAGE_TYPE + size));
memcpy(page_zip->data + page_zip_get_size(page_zip)
- trailer_size, ptr + 8 + size, trailer_size);
if (UNIV_UNLIKELY(!page_zip_decompress(page_zip, page,
TRUE))) {
goto corrupt;
}
}
return(ptr + 8 + size + trailer_size);
}
/**********************************************************************//**
Calculate the compressed page checksum.
@return page checksum */
UNIV_INTERN
ulint
page_zip_calc_checksum(
/*===================*/
const void* data, /*!< in: compressed page */
ulint size, /*!< in: size of compressed page */
srv_checksum_algorithm_t algo) /*!< in: algorithm to use */
{
uLong adler;
ib_uint32_t crc32;
const Bytef* s = static_cast<const byte*>(data);
/* Exclude FIL_PAGE_SPACE_OR_CHKSUM, FIL_PAGE_LSN,
and FIL_PAGE_FILE_FLUSH_LSN from the checksum. */
switch (algo) {
case SRV_CHECKSUM_ALGORITHM_CRC32:
case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
crc32 = ut_crc32(s + FIL_PAGE_OFFSET,
FIL_PAGE_LSN - FIL_PAGE_OFFSET)
^ ut_crc32(s + FIL_PAGE_TYPE, 2)
^ ut_crc32(s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
size - FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
return((ulint) crc32);
case SRV_CHECKSUM_ALGORITHM_INNODB:
case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
adler = adler32(0L, s + FIL_PAGE_OFFSET,
FIL_PAGE_LSN - FIL_PAGE_OFFSET);
adler = adler32(adler, s + FIL_PAGE_TYPE, 2);
adler = adler32(
adler, s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
static_cast<uInt>(size)
- FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
return((ulint) adler);
case SRV_CHECKSUM_ALGORITHM_NONE:
case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
return(BUF_NO_CHECKSUM_MAGIC);
/* no default so the compiler will emit a warning if new enum
is added and not handled here */
}
ut_error;
return(0);
}
/**********************************************************************//**
Verify a compressed page's checksum.
@return TRUE if the stored checksum is valid according to the value of
innodb_checksum_algorithm */
UNIV_INTERN
ibool
page_zip_verify_checksum(
/*=====================*/
const void* data, /*!< in: compressed page */
ulint size) /*!< in: size of compressed page */
{
ib_uint32_t stored;
ib_uint32_t calc;
ib_uint32_t crc32 = 0 /* silence bogus warning */;
ib_uint32_t innodb = 0 /* silence bogus warning */;
stored = static_cast<ib_uint32_t>(mach_read_from_4(
static_cast<const unsigned char*>(data) + FIL_PAGE_SPACE_OR_CHKSUM));
/* declare empty pages non-corrupted */
if (stored == 0) {
/* make sure that the page is really empty */
ulint i;
for (i = 0; i < size; i++) {
if (*((const char*) data + i) != 0) {
return(FALSE);
}
}
return(TRUE);
}
calc = static_cast<ib_uint32_t>(page_zip_calc_checksum(
data, size, static_cast<srv_checksum_algorithm_t>(
srv_checksum_algorithm)));
if (stored == calc) {
return(TRUE);
}
switch ((srv_checksum_algorithm_t) srv_checksum_algorithm) {
case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
return(stored == calc);
case SRV_CHECKSUM_ALGORITHM_CRC32:
if (stored == BUF_NO_CHECKSUM_MAGIC) {
return(TRUE);
}
crc32 = calc;
innodb = static_cast<ib_uint32_t>(page_zip_calc_checksum(
data, size, SRV_CHECKSUM_ALGORITHM_INNODB));
break;
case SRV_CHECKSUM_ALGORITHM_INNODB:
if (stored == BUF_NO_CHECKSUM_MAGIC) {
return(TRUE);
}
crc32 = static_cast<ib_uint32_t>(page_zip_calc_checksum(
data, size, SRV_CHECKSUM_ALGORITHM_CRC32));
innodb = calc;
break;
case SRV_CHECKSUM_ALGORITHM_NONE:
return(TRUE);
/* no default so the compiler will emit a warning if new enum
is added and not handled here */
}
return(stored == crc32 || stored == innodb);
}
| laurynas-biveinis/webscalesql-5.6 | storage/innobase/page/page0zip.cc | C++ | gpl-2.0 | 146,875 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pe.edu.upeu.modelo;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author hp
*/
@Entity
@Table(name = "conf_periodo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ConfPeriodo.findAll", query = "SELECT c FROM ConfPeriodo c")})
public class ConfPeriodo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_periodo")
private Integer idPeriodo;
@Basic(optional = false)
@Column(name = "periodo")
private String periodo;
@Basic(optional = false)
@Column(name = "descripcion")
private String descripcion;
@Basic(optional = false)
@Column(name = "fecha_inicio")
@Temporal(TemporalType.DATE)
private Date fechaInicio;
@Basic(optional = false)
@Column(name = "fecha_fin")
@Temporal(TemporalType.DATE)
private Date fechaFin;
@Basic(optional = false)
@Column(name = "estado")
private String estado;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloAreaEje> gloAreaEjeCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloEstadoArea> gloEstadoAreaCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloEstadoDepartamento> gloEstadoDepartamentoCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloEstadoFilial> gloEstadoFilialCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloDepartCoordinador> gloDepartCoordinadorCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloMeta> gloMetaCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<GloDepartareaCoordinador> gloDepartareaCoordinadorCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPeriodo")
private Collection<FinPartidapresupuestaria> finPartidapresupuestariaCollection;
@JoinColumn(name = "id_temporada", referencedColumnName = "id_temporada")
@ManyToOne(optional = false)
private ConfTemporada idTemporada;
public ConfPeriodo() {
}
public ConfPeriodo(Integer idPeriodo) {
this.idPeriodo = idPeriodo;
}
public ConfPeriodo(Integer idPeriodo, String periodo, String descripcion, Date fechaInicio, Date fechaFin, String estado) {
this.idPeriodo = idPeriodo;
this.periodo = periodo;
this.descripcion = descripcion;
this.fechaInicio = fechaInicio;
this.fechaFin = fechaFin;
this.estado = estado;
}
public Integer getIdPeriodo() {
return idPeriodo;
}
public void setIdPeriodo(Integer idPeriodo) {
this.idPeriodo = idPeriodo;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public Date getFechaFin() {
return fechaFin;
}
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
@XmlTransient
public Collection<GloAreaEje> getGloAreaEjeCollection() {
return gloAreaEjeCollection;
}
public void setGloAreaEjeCollection(Collection<GloAreaEje> gloAreaEjeCollection) {
this.gloAreaEjeCollection = gloAreaEjeCollection;
}
@XmlTransient
public Collection<GloEstadoArea> getGloEstadoAreaCollection() {
return gloEstadoAreaCollection;
}
public void setGloEstadoAreaCollection(Collection<GloEstadoArea> gloEstadoAreaCollection) {
this.gloEstadoAreaCollection = gloEstadoAreaCollection;
}
@XmlTransient
public Collection<GloEstadoDepartamento> getGloEstadoDepartamentoCollection() {
return gloEstadoDepartamentoCollection;
}
public void setGloEstadoDepartamentoCollection(Collection<GloEstadoDepartamento> gloEstadoDepartamentoCollection) {
this.gloEstadoDepartamentoCollection = gloEstadoDepartamentoCollection;
}
@XmlTransient
public Collection<GloEstadoFilial> getGloEstadoFilialCollection() {
return gloEstadoFilialCollection;
}
public void setGloEstadoFilialCollection(Collection<GloEstadoFilial> gloEstadoFilialCollection) {
this.gloEstadoFilialCollection = gloEstadoFilialCollection;
}
@XmlTransient
public Collection<GloDepartCoordinador> getGloDepartCoordinadorCollection() {
return gloDepartCoordinadorCollection;
}
public void setGloDepartCoordinadorCollection(Collection<GloDepartCoordinador> gloDepartCoordinadorCollection) {
this.gloDepartCoordinadorCollection = gloDepartCoordinadorCollection;
}
@XmlTransient
public Collection<GloMeta> getGloMetaCollection() {
return gloMetaCollection;
}
public void setGloMetaCollection(Collection<GloMeta> gloMetaCollection) {
this.gloMetaCollection = gloMetaCollection;
}
@XmlTransient
public Collection<GloDepartareaCoordinador> getGloDepartareaCoordinadorCollection() {
return gloDepartareaCoordinadorCollection;
}
public void setGloDepartareaCoordinadorCollection(Collection<GloDepartareaCoordinador> gloDepartareaCoordinadorCollection) {
this.gloDepartareaCoordinadorCollection = gloDepartareaCoordinadorCollection;
}
@XmlTransient
public Collection<FinPartidapresupuestaria> getFinPartidapresupuestariaCollection() {
return finPartidapresupuestariaCollection;
}
public void setFinPartidapresupuestariaCollection(Collection<FinPartidapresupuestaria> finPartidapresupuestariaCollection) {
this.finPartidapresupuestariaCollection = finPartidapresupuestariaCollection;
}
public ConfTemporada getIdTemporada() {
return idTemporada;
}
public void setIdTemporada(ConfTemporada idTemporada) {
this.idTemporada = idTemporada;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idPeriodo != null ? idPeriodo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ConfPeriodo)) {
return false;
}
ConfPeriodo other = (ConfPeriodo) object;
if ((this.idPeriodo == null && other.idPeriodo != null) || (this.idPeriodo != null && !this.idPeriodo.equals(other.idPeriodo))) {
return false;
}
return true;
}
@Override
public String toString() {
return "pe.edu.upeu.modelo.ConfPeriodo[ idPeriodo=" + idPeriodo + " ]";
}
}
| AngieChambi/ProFinal | WebSgeUPeU/src/java/pe/edu/upeu/modelo/ConfPeriodo.java | Java | gpl-2.0 | 8,395 |
package com.atlach.trafficdataloader;
import java.util.ArrayList;
/* Short Desc: Storage object for Trip info */
/* Trip Info > Trips > Routes */
public class TripInfo {
private int tripCount = 0;
public ArrayList<Trip> trips = null;
public String date;
public String origin;
public String destination;
public TripInfo() {
trips = new ArrayList<Trip>();
}
public int addTrip() {
Trip temp = new Trip();
if (trips.add(temp) == false) {
/* Failed */
return -1;
}
tripCount++;
return trips.indexOf(temp);
}
public int addRouteToTrip(int tripId, String routeName, String mode, String dist, String agency, String start, String end, String points) {
int result = -1;
Trip temp = trips.get(tripId);
if (temp != null) {
result = temp.addRoute(routeName, mode, dist, agency, start, end, points);
}
return result;
}
public int getTripCount() {
return tripCount;
}
public static class Trip {
public double totalDist = 0.0;
public double totalCost = 0.0;
public int totalTraffic = 0;
private int transfers = 0;
public ArrayList<Route> routes = null;
public Trip() {
routes = new ArrayList<Route>();
};
public int addRoute(String routeName, String mode, String dist, String agency, String start, String end, String points) {
Route temp = new Route();
temp.name = routeName;
temp.mode = mode;
temp.dist = dist;
temp.agency = agency;
temp.start = start;
temp.end = end;
temp.points = points;
if (routes.add(temp) == false) {
/* Failed */
return -1;
}
transfers++;
return routes.indexOf(temp);
}
public int getTransfers() {
return transfers;
}
}
public static class Route {
/* Object fields */
public String name = "";
public String mode = "";
public String dist = "0.0";
public String agency = "";
public String start = "";
public String end = "";
public String points = "";
public String cond = "";
//public String cost = "0.0";
public double costMatrix[] = {0.0, 0.0, 0.0, 0.0};
public double getRegularCost(boolean isDiscounted) {
if (isDiscounted) {
return costMatrix[1];
}
return costMatrix[0];
}
public double getSpecialCost(boolean isDiscounted) {
if (isDiscounted) {
return costMatrix[2];
}
return costMatrix[3];
}
}
}
| linusmotu/Viaje | ViajeUi/src/com/atlach/trafficdataloader/TripInfo.java | Java | gpl-2.0 | 2,363 |
package org.adastraeducation.liquiz.equation;
import java.util.*;
import java.util.regex.*;
import org.adastraeducation.liquiz.*;
/**
* Present equations with random variables.
* It has two ways to parse the equations in string[]. One is in infix, and the other is in the RPN.
* @author Yingzhu Wang
*
*/
public class Equation implements Displayable {
private Expression func;
private double correctAnswer;
private HashMap<String,Var> variables;
public Equation(String equation, HashMap<String,Var> variables){
this.variables=variables;
ArrayList<String> equationSplit = this.parseQuestion(equation);
this.func = this.parseInfix(equationSplit);
correctAnswer = func.eval();
}
public Equation(Expression func, HashMap<String,Var> variables){
this.func = func;
this.variables = variables;
correctAnswer=func.eval();
}
public Equation(Expression func){
this.func = func;
this.variables = new HashMap<String,Var>();
correctAnswer=func.eval();
}
public void setExpression(Expression e){
this.func=e;
correctAnswer=func.eval();
}
public void setVariables(HashMap<String,Var> variables){
this.variables = variables;
}
public String getTagName() { return "Equation"; }
public Expression parseInfix(ArrayList<String> s){
Tree t = new Tree(s);
ArrayList<String> rpn = t.traverse();
return parseRPN(rpn);
}
// Precompile all regular expressions used in parsing
private static final Pattern parseDigits =
Pattern.compile("^[0-9]+$");
private static final Pattern wordPattern =
Pattern.compile("[\\W]|([\\w]*)");
/*TODO: We can do much better than a switch statement,
* but it would require a hash map and lots of little objects
*/
//TODO: Check if binary ops are backgwards? a b - ????
public Expression parseRPN(ArrayList<String> s) {
Stack<Expression> stack = new Stack<Expression>();
for(int i = 0; i<s.size(); i++){
String temp = s.get(i);
if (Functions.MATHFUNCTIONS.contains(temp)) {
Expression op1 ;
Expression op2 ;
switch(temp){
case "+":
op2=stack.pop();
op1=stack.pop();
stack.push(new Plus(op1,op2));
break;
case "-":
op2=stack.pop();
op1=stack.pop();
stack.push( new Minus(op1,op2));
break;
case "*":
op2=stack.pop();
op1=stack.pop();
stack.push( new Multi(op1,op2));break;
case "/":
op2=stack.pop();
op1=stack.pop();
stack.push( new Div(op1,op2));break;
case "sin":
op1=stack.pop();
stack.push(new Sin(op1));break;
case "cos":
op1=stack.pop();
stack.push(new Cos(op1));break;
case "tan":
op1=stack.pop();
stack.push(new Tan(op1));break;
case "abs":
op1=stack.pop();
stack.push(new Abs(op1));break;
case "Asin":
op1=stack.pop();
stack.push(new Asin(op1));break;
case "Atan":
op1=stack.pop();
stack.push(new Atan(op1));break;
case "neg":
op1=stack.pop();
stack.push(new Neg(op1));break;
case "sqrt":
op1=stack.pop();
stack.push(new Sqrt(op1));break;
default:break;
}
}
//deal with the space
else if(temp.equals(""))
;
else{
Matcher m = parseDigits.matcher(temp);
if (m.matches()){
double x = Double.parseDouble(temp);
stack.push(new Constant(x));
}
else{
stack.push(variables.get(temp));
}
}
}
return stack.pop();
}
public ArrayList<String> parseQuestion(String question){
ArrayList<String> s = new ArrayList<String>();
Matcher m = wordPattern.matcher(question);
while(m.find()){
s.add(m.group());
}
return s;
}
// public ResultSet readDatabase(String sql){
// return DatabaseMgr.select(sql);
// }
//
// public void writeDatabase(String sql){
// DatabaseMgr.update(sql);
// }
public Expression getExpression(){
return func;
}
public double getCorrectAnswer(){
return correctAnswer;
}
@Override
public void writeHTML(StringBuilder b) {
func.infixReplaceVar(b);
}
@Override
public void writeXML(StringBuilder b) {
b.append("<Equation question='");
func.infix(b);
b.append("'></Equation>");
}
@Override
public void writeJS(StringBuilder b) {
}
}
| hydrodog/LiquiZ | LiquiZ/src/org/adastraeducation/liquiz/equation/Equation.java | Java | gpl-2.0 | 4,219 |
package com.github.luksdlt92;
import java.util.ArrayList;
/*
* DoubleJumpReload plugin
* Made by luksdlt92 and Abdalion
*/
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import com.github.luksdlt92.commands.DoubleJumpCommand;
import com.github.luksdlt92.listeners.JumpListener;
public class DoubleJumpReload extends JavaPlugin implements Listener {
public ArrayList<String> _players = new ArrayList<String>();
public ArrayList<String> _playersDisableJump = new ArrayList<String>();
@Override
public void onEnable()
{
new JumpListener(this);
this.getCommand("jumpdelay").setExecutor(new DoubleJumpCommand(this));
}
public ArrayList<String> getPlayers()
{
return _players;
}
public ArrayList<String> getPlayersDisableJump()
{
return _playersDisableJump;
}
}
| luksdlt92/doublejumpreload | DoubleJumpReload/src/main/java/com/github/luksdlt92/DoubleJumpReload.java | Java | gpl-2.0 | 871 |
package org.vidogram.messenger.g.a;
import java.io.ByteArrayOutputStream;
public class j extends ByteArrayOutputStream
{
private final b a;
public j(b paramb, int paramInt)
{
this.a = paramb;
this.buf = this.a.a(Math.max(paramInt, 256));
}
private void a(int paramInt)
{
if (this.count + paramInt <= this.buf.length)
return;
byte[] arrayOfByte = this.a.a((this.count + paramInt) * 2);
System.arraycopy(this.buf, 0, arrayOfByte, 0, this.count);
this.a.a(this.buf);
this.buf = arrayOfByte;
}
public void close()
{
this.a.a(this.buf);
this.buf = null;
super.close();
}
public void finalize()
{
this.a.a(this.buf);
}
public void write(int paramInt)
{
monitorenter;
try
{
a(1);
super.write(paramInt);
monitorexit;
return;
}
finally
{
localObject = finally;
monitorexit;
}
throw localObject;
}
public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
monitorenter;
try
{
a(paramInt2);
super.write(paramArrayOfByte, paramInt1, paramInt2);
monitorexit;
return;
}
finally
{
paramArrayOfByte = finally;
monitorexit;
}
throw paramArrayOfByte;
}
}
/* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar
* Qualified Name: org.vidogram.messenger.g.a.j
* JD-Core Version: 0.6.0
*/ | Robert0Trebor/robert | TMessagesProj/src/main/java/org/vidogram/messenger/g/a/j.java | Java | gpl-2.0 | 1,439 |
using UnityEngine;
using System.Collections;
/*
* Item to handle movements of rigibodies
*/
public class RigibodyMoveItem : MoveItem {
public enum Type {
ENEMY_SHIP_TYPE_1,
LASER_RED,
LASER_BLUE
};
public static RigibodyMoveItem create(Type type)
{
switch (type)
{
case Type.ENEMY_SHIP_TYPE_1:
return new EnemyShip1MoveItem();
case Type.LASER_RED:
return new LaserRedMoveItem();
case Type.LASER_BLUE:
return new LaserBlueMoveItem();
default:
throw new System.ArgumentException("Incorrect RigibodyMoveItem.Type " + type.ToString());
}
}
}
| adriwankenobi/space | Assets/Scripts/Level/Non Playable/Movement/Rigibody/RigibodyMoveItem.cs | C# | gpl-2.0 | 620 |
package it.polito.nexa.pc;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Statement;
import java.util.List;
/**
* Created by giuseppe on 19/05/15.
*/
public interface TriplesAdder {
public Model addTriples(Model model, List<Statement> statementList);
}
| giuseppefutia/rdf-public-contracts | src/main/java/it/polito/nexa/pc/TriplesAdder.java | Java | gpl-2.0 | 290 |
using UnityEngine;
using System.Collections;
public class ButtonNextImage : MonoBehaviour {
public GameObject nextImage;
public bool lastImage;
public string nextScene = "";
void OnMouseDown()
{
if(lastImage)
{
Application.LoadLevel(nextScene);
return;
}
gameObject.SetActive (false);
nextImage.SetActive (true);
}
}
| aindong/RobberGame | Assets/Scripts/Helpers/ButtonNextImage.cs | C# | gpl-2.0 | 347 |
/**
* Created by LPAC006013 on 23/11/14.
*/
/*
* wiring Super fish to menu
*/
var sfvar = jQuery('div.menu');
var phoneSize = 600;
jQuery(document).ready(function($) {
//if screen size is bigger than phone's screen (Tablet,Desktop)
if($(document).width() >= phoneSize) {
// enable superfish
sfvar.superfish({
delay: 500,
speed: 'slow'
});
jQuery("#menu-main-menu").addClass('clear');
var containerheight = jQuery("#menu-main-menu").height();
jQuery("#menu-main-menu").children().css("height",containerheight);
}
$(window).resize(function() {
if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) {
sfvar.superfish({
delay: 500,
speed: 'slow'
});
}
// phoneSize, disable superfish
else if($(document).width() < phoneSize) {
sfvar.superfish('destroy');
}
});
});
| dejanmarkovic/topcat-final | js/global.js | JavaScript | gpl-2.0 | 994 |
<?php
/**
* Multisite upgrade administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once(dirname(__FILE__) . '/admin.php');
if (!is_multisite())
wp_die(__('Multisite support is not enabled.'));
require_once(ABSPATH . WPINC . '/http.php');
$title = __('Upgrade Network');
$parent_file = 'upgrade.php';
get_current_screen()->add_help_tab(array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('Only use this screen once you have updated to a new version of WordPress through Updates/Available Updates (via the Network Administration navigation menu or the Toolbar). Clicking the Upgrade Network button will step through each site in the network, five at a time, and make sure any database updates are applied.') . '</p>' .
'<p>' . __('If a version update to core has not happened, clicking this button won’t affect anything.') . '</p>' .
'<p>' . __('If this process fails for any reason, users logging in to their sites will force the same update.') . '</p>'
));
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Updates_Screen" target="_blank">Documentation on Upgrade Network</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
require_once(ABSPATH . 'wp-admin/admin-header.php');
if (!current_user_can('manage_network'))
wp_die(__('You do not have permission to access this page.'));
echo '<div class="wrap">';
echo '<h2>' . __('Upgrade Network') . '</h2>';
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
case "upgrade":
$n = (isset($_GET['n'])) ? intval($_GET['n']) : 0;
if ($n < 5) {
global $wp_db_version;
update_site_option('wpmu_upgrade_site', $wp_db_version);
}
$blogs = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0' ORDER BY registered DESC LIMIT {$n}, 5", ARRAY_A);
if (empty($blogs)) {
echo '<p>' . __('All done!') . '</p>';
break;
}
echo "<ul>";
foreach ((array)$blogs as $details) {
switch_to_blog($details['blog_id']);
$siteurl = site_url();
$upgrade_url = admin_url('upgrade.php?step=upgrade_db');
restore_current_blog();
echo "<li>$siteurl</li>";
$response = wp_remote_get($upgrade_url, array('timeout' => 120, 'httpversion' => '1.1'));
if (is_wp_error($response))
wp_die(sprintf(__('Warning! Problem updating %1$s. Your server may not be able to connect to sites running on it. Error message: <em>%2$s</em>'), $siteurl, $response->get_error_message()));
/**
* Fires after the Multisite DB upgrade for each site is complete.
*
* @since MU
*
* @param array|WP_Error $response The upgrade response array or WP_Error on failure.
*/
do_action('after_mu_upgrade', $response);
/**
* Fires after each site has been upgraded.
*
* @since MU
*
* @param int $blog_id The id of the blog.
*/
do_action('wpmu_upgrade_site', $details['blog_id']);
}
echo "</ul>";
?><p><?php _e('If your browser doesn’t start loading the next page automatically, click this link:'); ?>
<a class="button" href="upgrade.php?action=upgrade&n=<?php echo($n + 5) ?>"><?php _e("Next Sites"); ?></a>
</p>
<script type="text/javascript">
<!--
function nextpage() {
location.href = "upgrade.php?action=upgrade&n=<?php echo ($n + 5) ?>";
}
setTimeout("nextpage()", 250);
//-->
</script><?php
break;
case 'show':
default:
if (get_site_option('wpmu_upgrade_site') != $GLOBALS['wp_db_version']) :
?>
<h3><?php _e('Database Upgrade Required'); ?></h3>
<p><?php _e('WordPress has been updated! Before we send you on your way, we need to individually upgrade the sites in your network.'); ?></p>
<?php endif; ?>
<p><?php _e('The database upgrade process may take a little while, so please be patient.'); ?></p>
<p><a class="button" href="upgrade.php?action=upgrade"><?php _e('Upgrade Network'); ?></a></p>
<?php
/**
* Fires before the footer on the network upgrade screen.
*
* @since MU
*/
do_action('wpmu_upgrade_page');
break;
}
?>
</div>
<?php include(ABSPATH . 'wp-admin/admin-footer.php'); ?>
| JeremyCarlsten/WordpressWork | wp-admin/network/upgrade.php | PHP | gpl-2.0 | 4,987 |
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
//
// file: rbbirb.cpp
//
// Copyright (C) 2002-2011, International Business Machines Corporation and others.
// All Rights Reserved.
//
// This file contains the RBBIRuleBuilder class implementation. This is the main class for
// building (compiling) break rules into the tables required by the runtime
// RBBI engine.
//
#include "unicode/utypes.h"
#if !UCONFIG_NO_BREAK_ITERATION
#include "unicode/brkiter.h"
#include "unicode/rbbi.h"
#include "unicode/ubrk.h"
#include "unicode/unistr.h"
#include "unicode/uniset.h"
#include "unicode/uchar.h"
#include "unicode/uchriter.h"
#include "unicode/parsepos.h"
#include "unicode/parseerr.h"
#include "cmemory.h"
#include "cstring.h"
#include "rbbirb.h"
#include "rbbinode.h"
#include "rbbiscan.h"
#include "rbbisetb.h"
#include "rbbitblb.h"
#include "rbbidata.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
//----------------------------------------------------------------------------------------
//
// Constructor.
//
//----------------------------------------------------------------------------------------
RBBIRuleBuilder::RBBIRuleBuilder(const UnicodeString &rules,
UParseError *parseErr,
UErrorCode &status)
: fRules(rules), fStrippedRules(rules)
{
fStatus = &status; // status is checked below
fParseError = parseErr;
fDebugEnv = NULL;
#ifdef RBBI_DEBUG
fDebugEnv = getenv("U_RBBIDEBUG");
#endif
fForwardTree = NULL;
fReverseTree = NULL;
fSafeFwdTree = NULL;
fSafeRevTree = NULL;
fDefaultTree = &fForwardTree;
fForwardTable = NULL;
fRuleStatusVals = NULL;
fChainRules = FALSE;
fLBCMNoChain = FALSE;
fLookAheadHardBreak = FALSE;
fUSetNodes = NULL;
fRuleStatusVals = NULL;
fScanner = NULL;
fSetBuilder = NULL;
if (parseErr) {
uprv_memset(parseErr, 0, sizeof(UParseError));
}
if (U_FAILURE(status)) {
return;
}
fUSetNodes = new UVector(status); // bcos status gets overwritten here
fRuleStatusVals = new UVector(status);
fScanner = new RBBIRuleScanner(this);
fSetBuilder = new RBBISetBuilder(this);
if (U_FAILURE(status)) {
return;
}
if(fSetBuilder == 0 || fScanner == 0 || fUSetNodes == 0 || fRuleStatusVals == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
}
}
//----------------------------------------------------------------------------------------
//
// Destructor
//
//----------------------------------------------------------------------------------------
RBBIRuleBuilder::~RBBIRuleBuilder() {
int i;
for (i=0; ; i++) {
RBBINode *n = (RBBINode *)fUSetNodes->elementAt(i);
if (n==NULL) {
break;
}
delete n;
}
delete fUSetNodes;
delete fSetBuilder;
delete fForwardTable;
delete fForwardTree;
delete fReverseTree;
delete fSafeFwdTree;
delete fSafeRevTree;
delete fScanner;
delete fRuleStatusVals;
}
//----------------------------------------------------------------------------------------
//
// flattenData() - Collect up the compiled RBBI rule data and put it into
// the format for saving in ICU data files,
// which is also the format needed by the RBBI runtime engine.
//
//----------------------------------------------------------------------------------------
static int32_t align8(int32_t i) {return (i+7) & 0xfffffff8;}
RBBIDataHeader *RBBIRuleBuilder::flattenData() {
int32_t i;
if (U_FAILURE(*fStatus)) {
return NULL;
}
// Remove whitespace from the rules to make it smaller.
// The rule parser has already removed comments.
fStrippedRules = fScanner->stripRules(fStrippedRules);
// Calculate the size of each section in the data.
// Sizes here are padded up to a multiple of 8 for better memory alignment.
// Sections sizes actually stored in the header are for the actual data
// without the padding.
//
int32_t headerSize = align8(sizeof(RBBIDataHeader));
int32_t forwardTableSize = align8(fForwardTable->getTableSize());
int32_t reverseTableSize = align8(fForwardTable->getSafeTableSize());
int32_t trieSize = align8(fSetBuilder->getTrieSize());
int32_t statusTableSize = align8(fRuleStatusVals->size() * sizeof(int32_t));
int32_t rulesSize = align8((fStrippedRules.length()+1) * sizeof(UChar));
int32_t totalSize = headerSize
+ forwardTableSize
+ reverseTableSize
+ statusTableSize + trieSize + rulesSize;
RBBIDataHeader *data = (RBBIDataHeader *)uprv_malloc(totalSize);
if (data == NULL) {
*fStatus = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
uprv_memset(data, 0, totalSize);
data->fMagic = 0xb1a0;
data->fFormatVersion[0] = RBBI_DATA_FORMAT_VERSION[0];
data->fFormatVersion[1] = RBBI_DATA_FORMAT_VERSION[1];
data->fFormatVersion[2] = RBBI_DATA_FORMAT_VERSION[2];
data->fFormatVersion[3] = RBBI_DATA_FORMAT_VERSION[3];
data->fLength = totalSize;
data->fCatCount = fSetBuilder->getNumCharCategories();
data->fFTable = headerSize;
data->fFTableLen = forwardTableSize;
data->fRTable = data->fFTable + data->fFTableLen;
data->fRTableLen = reverseTableSize;
data->fTrie = data->fRTable + data->fRTableLen;
data->fTrieLen = fSetBuilder->getTrieSize();
data->fStatusTable = data->fTrie + trieSize;
data->fStatusTableLen= statusTableSize;
data->fRuleSource = data->fStatusTable + statusTableSize;
data->fRuleSourceLen = fStrippedRules.length() * sizeof(UChar);
uprv_memset(data->fReserved, 0, sizeof(data->fReserved));
fForwardTable->exportTable((uint8_t *)data + data->fFTable);
fForwardTable->exportSafeTable((uint8_t *)data + data->fRTable);
fSetBuilder->serializeTrie ((uint8_t *)data + data->fTrie);
int32_t *ruleStatusTable = (int32_t *)((uint8_t *)data + data->fStatusTable);
for (i=0; i<fRuleStatusVals->size(); i++) {
ruleStatusTable[i] = fRuleStatusVals->elementAti(i);
}
fStrippedRules.extract((UChar *)((uint8_t *)data+data->fRuleSource), rulesSize/2+1, *fStatus);
return data;
}
//----------------------------------------------------------------------------------------
//
// createRuleBasedBreakIterator construct from source rules that are passed in
// in a UnicodeString
//
//----------------------------------------------------------------------------------------
BreakIterator *
RBBIRuleBuilder::createRuleBasedBreakIterator( const UnicodeString &rules,
UParseError *parseError,
UErrorCode &status)
{
//
// Read the input rules, generate a parse tree, symbol table,
// and list of all Unicode Sets referenced by the rules.
//
RBBIRuleBuilder builder(rules, parseError, status);
if (U_FAILURE(status)) { // status checked here bcos build below doesn't
return NULL;
}
RBBIDataHeader *data = builder.build(status);
if (U_FAILURE(status)) {
return nullptr;
}
//
// Create a break iterator from the compiled rules.
// (Identical to creation from stored pre-compiled rules)
//
// status is checked after init in construction.
RuleBasedBreakIterator *This = new RuleBasedBreakIterator(data, status);
if (U_FAILURE(status)) {
delete This;
This = NULL;
}
else if(This == NULL) { // test for NULL
status = U_MEMORY_ALLOCATION_ERROR;
}
return This;
}
RBBIDataHeader *RBBIRuleBuilder::build(UErrorCode &status) {
if (U_FAILURE(status)) {
return nullptr;
}
fScanner->parse();
if (U_FAILURE(status)) {
return nullptr;
}
//
// UnicodeSet processing.
// Munge the Unicode Sets to create a set of character categories.
// Generate the mapping tables (TRIE) from input code points to
// the character categories.
//
fSetBuilder->buildRanges();
//
// Generate the DFA state transition table.
//
fForwardTable = new RBBITableBuilder(this, &fForwardTree, status);
if (fForwardTable == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
fForwardTable->buildForwardTable();
optimizeTables();
fForwardTable->buildSafeReverseTable(status);
#ifdef RBBI_DEBUG
if (fDebugEnv && uprv_strstr(fDebugEnv, "states")) {
fForwardTable->printStates();
fForwardTable->printRuleStatusTable();
fForwardTable->printReverseTable();
}
#endif
fSetBuilder->buildTrie();
//
// Package up the compiled data into a memory image
// in the run-time format.
//
RBBIDataHeader *data = flattenData(); // returns NULL if error
if (U_FAILURE(status)) {
return nullptr;
}
return data;
}
void RBBIRuleBuilder::optimizeTables() {
// Begin looking for duplicates with char class 3.
// Classes 0, 1 and 2 are special; they are unused, {bof} and {eof} respectively,
// and should not have other categories merged into them.
IntPair duplPair = {3, 0};
while (fForwardTable->findDuplCharClassFrom(&duplPair)) {
fSetBuilder->mergeCategories(duplPair);
fForwardTable->removeColumn(duplPair.second);
}
fForwardTable->removeDuplicateStates();
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
| teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/ThirdParty/icu/source/common/rbbirb.cpp | C++ | gpl-2.0 | 9,976 |
<div class="clear left">
<div class="full-page-span33 home-island">
<div class="img-island isle1">
<h3>Isle Title 1</h3>
<p class="tl"> Mei duis denique nostrum et, in pro choro</p>
</div>
<div>
<p>Lorem ipsum Mei duis denique nostrum et, in pro choro consul, eam deterruisset definitionem te. Ne nam prima essent delicata, quie Sacto is. In fabellas technician.</p>
</div>
</div>
<div class="full-page-span33 home-island">
<div class="img-island isle2">
<h3>Isle Title 2</h3>
<p class="bl">Ne Nam Prima Essent Delicata</p>
</div>
<div>
<p>Ot usu ut oblique senserit, ne usu saepe affert definitiones, mel euripidis persequeris id. Pri ad iudico conceptam, nostro apeirian no has Roseville.</p>
</div>
</div>
<div class="full-page-span33 home-island">
<div class="img-island isle3">
<h3>Isle Title 3</h3>
<p class="tr">Ut Oratio Moleskine Quo Prezi</p>
</div>
<div>
<p> Ipsum cotidieque definitiones eos no, at dicant perfecto sea. At mollis definitionem duo, ludus primis sanctus id eam, an mei rebum debitis.</p>
</div>
</div>
</div>
<div class="clear left">
<div class="full-page-span33 home-facts">
<h3 class="med-body-headline">Our Services Include:</h3>
<ul>
<li>Fulli Assueverit</li>
<li>Centrant Ailey Redactio Athasn</li>
<li>Electric Oblique Senserit</li>
<li>Nec Ro Aperiam</li>
<li>At Mollis Definitionem Duo</li>
<li>Radirum A Denique Adversarium namei</li>
<ul>
</div>
<div class="full-page-span33 home-facts hf2nd-col">
<ul>
<li>Tel Hasadipsci & Ludis</li>
<li>Respado Cotidieque & Primus</li>
<li>PAVT Monestatis</li>
<li>Listaray, Billum & Inlused</li>
<li>24 Hour Elequist Sanktus</li>
<li>Fresca Estinastos</li>
<ul>
</div>
<div class="full-page-span33 home-facts hf2nd-col last-col">
<a href="#" class="frst-grn-btn tighten-text"><span class="subtext">Nov Ask Selen</span><br /> Falli Eloquentiam</a>
<a href="#" class="lt-grn-btn tighten-text">Eleifend Asservated<br /><span class="subtext">Utom Requiem</span></a>
</div>
</div>
| johnjlocke/rush-mechanical-theme | rush-mechanical/home-fw.php | PHP | gpl-2.0 | 2,288 |
<?php
/*
$Id$
osCmax e-Commerce
http://www.oscmax.com
Copyright 2000 - 2011 osCmax
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Chèques cadeaux envoyés');
define('TABLE_HEADING_SENDERS_NAME', 'Nom de l\'expéditeur');
define('TABLE_HEADING_VOUCHER_VALUE', 'Valeur du bon');
define('TABLE_HEADING_VOUCHER_CODE', 'Code du bon');
define('TABLE_HEADING_DATE_SENT', 'Date de l\'envoi');
define('TABLE_HEADING_ACTION', 'Action');
define('TEXT_INFO_SENDERS_ID', 'Identifiant de l\'expéditeur :');
define('TEXT_INFO_AMOUNT_SENT', 'Montant envoyé :');
define('TEXT_INFO_DATE_SENT', 'Date de l\'envoi :');
define('TEXT_INFO_VOUCHER_CODE', 'Code du chèque :');
define('TEXT_INFO_EMAIL_ADDRESS', 'Adresse email :');
define('TEXT_INFO_DATE_REDEEMED', 'Date de validation :');
define('TEXT_INFO_IP_ADDRESS', 'Adresse IP :');
define('TEXT_INFO_CUSTOMERS_ID', 'Identifiant du client :');
define('TEXT_INFO_NOT_REDEEMED', 'Non validé');
?> | osCmax/oscmax2 | catalog/admin/includes/languages/french/gv_sent.php | PHP | gpl-2.0 | 1,035 |
/*
* Copyright (C) 2005-2013 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "Log.h"
#include "UpdateMask.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Unit.h"
#include "Spell.h"
#include "DynamicObject.h"
#include "Group.h"
#include "UpdateData.h"
#include "ObjectAccessor.h"
#include "Policies/Singleton.h"
#include "Totem.h"
#include "Creature.h"
#include "Formulas.h"
#include "BattleGround/BattleGround.h"
#include "OutdoorPvP/OutdoorPvP.h"
#include "CreatureAI.h"
#include "ScriptMgr.h"
#include "Util.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "MapManager.h"
#define NULL_AURA_SLOT 0xFF
pAuraHandler AuraHandler[TOTAL_AURAS] =
{
&Aura::HandleNULL, // 0 SPELL_AURA_NONE
&Aura::HandleBindSight, // 1 SPELL_AURA_BIND_SIGHT
&Aura::HandleModPossess, // 2 SPELL_AURA_MOD_POSSESS
&Aura::HandlePeriodicDamage, // 3 SPELL_AURA_PERIODIC_DAMAGE
&Aura::HandleAuraDummy, // 4 SPELL_AURA_DUMMY
&Aura::HandleModConfuse, // 5 SPELL_AURA_MOD_CONFUSE
&Aura::HandleModCharm, // 6 SPELL_AURA_MOD_CHARM
&Aura::HandleModFear, // 7 SPELL_AURA_MOD_FEAR
&Aura::HandlePeriodicHeal, // 8 SPELL_AURA_PERIODIC_HEAL
&Aura::HandleModAttackSpeed, // 9 SPELL_AURA_MOD_ATTACKSPEED
&Aura::HandleModThreat, // 10 SPELL_AURA_MOD_THREAT
&Aura::HandleModTaunt, // 11 SPELL_AURA_MOD_TAUNT
&Aura::HandleAuraModStun, // 12 SPELL_AURA_MOD_STUN
&Aura::HandleModDamageDone, // 13 SPELL_AURA_MOD_DAMAGE_DONE
&Aura::HandleNoImmediateEffect, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellBaseDamageBonusTaken
&Aura::HandleNoImmediateEffect, // 15 SPELL_AURA_DAMAGE_SHIELD implemented in Unit::DealMeleeDamage
&Aura::HandleModStealth, // 16 SPELL_AURA_MOD_STEALTH
&Aura::HandleNoImmediateEffect, // 17 SPELL_AURA_MOD_STEALTH_DETECT implemented in Unit::isVisibleForOrDetect
&Aura::HandleInvisibility, // 18 SPELL_AURA_MOD_INVISIBILITY
&Aura::HandleInvisibilityDetect, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION
&Aura::HandleAuraModTotalHealthPercentRegen, // 20 SPELL_AURA_OBS_MOD_HEALTH
&Aura::HandleAuraModTotalManaPercentRegen, // 21 SPELL_AURA_OBS_MOD_MANA
&Aura::HandleAuraModResistance, // 22 SPELL_AURA_MOD_RESISTANCE
&Aura::HandlePeriodicTriggerSpell, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL
&Aura::HandlePeriodicEnergize, // 24 SPELL_AURA_PERIODIC_ENERGIZE
&Aura::HandleAuraModPacify, // 25 SPELL_AURA_MOD_PACIFY
&Aura::HandleAuraModRoot, // 26 SPELL_AURA_MOD_ROOT
&Aura::HandleAuraModSilence, // 27 SPELL_AURA_MOD_SILENCE
&Aura::HandleNoImmediateEffect, // 28 SPELL_AURA_REFLECT_SPELLS implement in Unit::SpellHitResult
&Aura::HandleAuraModStat, // 29 SPELL_AURA_MOD_STAT
&Aura::HandleAuraModSkill, // 30 SPELL_AURA_MOD_SKILL
&Aura::HandleAuraModIncreaseSpeed, // 31 SPELL_AURA_MOD_INCREASE_SPEED
&Aura::HandleAuraModIncreaseMountedSpeed, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED
&Aura::HandleAuraModDecreaseSpeed, // 33 SPELL_AURA_MOD_DECREASE_SPEED
&Aura::HandleAuraModIncreaseHealth, // 34 SPELL_AURA_MOD_INCREASE_HEALTH
&Aura::HandleAuraModIncreaseEnergy, // 35 SPELL_AURA_MOD_INCREASE_ENERGY
&Aura::HandleAuraModShapeshift, // 36 SPELL_AURA_MOD_SHAPESHIFT
&Aura::HandleAuraModEffectImmunity, // 37 SPELL_AURA_EFFECT_IMMUNITY
&Aura::HandleAuraModStateImmunity, // 38 SPELL_AURA_STATE_IMMUNITY
&Aura::HandleAuraModSchoolImmunity, // 39 SPELL_AURA_SCHOOL_IMMUNITY
&Aura::HandleAuraModDmgImmunity, // 40 SPELL_AURA_DAMAGE_IMMUNITY
&Aura::HandleAuraModDispelImmunity, // 41 SPELL_AURA_DISPEL_IMMUNITY
&Aura::HandleAuraProcTriggerSpell, // 42 SPELL_AURA_PROC_TRIGGER_SPELL implemented in Unit::ProcDamageAndSpellFor and Unit::HandleProcTriggerSpell
&Aura::HandleNoImmediateEffect, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE implemented in Unit::ProcDamageAndSpellFor
&Aura::HandleAuraTrackCreatures, // 44 SPELL_AURA_TRACK_CREATURES
&Aura::HandleAuraTrackResources, // 45 SPELL_AURA_TRACK_RESOURCES
&Aura::HandleUnused, // 46 SPELL_AURA_46
&Aura::HandleAuraModParryPercent, // 47 SPELL_AURA_MOD_PARRY_PERCENT
&Aura::HandleUnused, // 48 SPELL_AURA_48
&Aura::HandleAuraModDodgePercent, // 49 SPELL_AURA_MOD_DODGE_PERCENT
&Aura::HandleUnused, // 50 SPELL_AURA_MOD_BLOCK_SKILL obsolete?
&Aura::HandleAuraModBlockPercent, // 51 SPELL_AURA_MOD_BLOCK_PERCENT
&Aura::HandleAuraModCritPercent, // 52 SPELL_AURA_MOD_CRIT_PERCENT
&Aura::HandlePeriodicLeech, // 53 SPELL_AURA_PERIODIC_LEECH
&Aura::HandleModHitChance, // 54 SPELL_AURA_MOD_HIT_CHANCE
&Aura::HandleModSpellHitChance, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE
&Aura::HandleAuraTransform, // 56 SPELL_AURA_TRANSFORM
&Aura::HandleModSpellCritChance, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE
&Aura::HandleAuraModIncreaseSwimSpeed, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED
&Aura::HandleNoImmediateEffect, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE implemented in Unit::MeleeDamageBonusDone and Unit::SpellDamageBonusDone
&Aura::HandleAuraModPacifyAndSilence, // 60 SPELL_AURA_MOD_PACIFY_SILENCE
&Aura::HandleAuraModScale, // 61 SPELL_AURA_MOD_SCALE
&Aura::HandlePeriodicHealthFunnel, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL
&Aura::HandleUnused, // 63 SPELL_AURA_PERIODIC_MANA_FUNNEL obsolete?
&Aura::HandlePeriodicManaLeech, // 64 SPELL_AURA_PERIODIC_MANA_LEECH
&Aura::HandleModCastingSpeed, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK
&Aura::HandleFeignDeath, // 66 SPELL_AURA_FEIGN_DEATH
&Aura::HandleAuraModDisarm, // 67 SPELL_AURA_MOD_DISARM
&Aura::HandleAuraModStalked, // 68 SPELL_AURA_MOD_STALKED
&Aura::HandleSchoolAbsorb, // 69 SPELL_AURA_SCHOOL_ABSORB implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleUnused, // 70 SPELL_AURA_EXTRA_ATTACKS Useless, used by only one spell that has only visual effect
&Aura::HandleModSpellCritChanceShool, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL
&Aura::HandleModPowerCostPCT, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT
&Aura::HandleModPowerCost, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL
&Aura::HandleNoImmediateEffect, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL implemented in Unit::SpellHitResult
&Aura::HandleNoImmediateEffect, // 75 SPELL_AURA_MOD_LANGUAGE implemented in WorldSession::HandleMessagechatOpcode
&Aura::HandleFarSight, // 76 SPELL_AURA_FAR_SIGHT
&Aura::HandleModMechanicImmunity, // 77 SPELL_AURA_MECHANIC_IMMUNITY
&Aura::HandleAuraMounted, // 78 SPELL_AURA_MOUNTED
&Aura::HandleModDamagePercentDone, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
&Aura::HandleModPercentStat, // 80 SPELL_AURA_MOD_PERCENT_STAT
&Aura::HandleNoImmediateEffect, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleWaterBreathing, // 82 SPELL_AURA_WATER_BREATHING
&Aura::HandleModBaseResistance, // 83 SPELL_AURA_MOD_BASE_RESISTANCE
&Aura::HandleModRegen, // 84 SPELL_AURA_MOD_REGEN
&Aura::HandleModPowerRegen, // 85 SPELL_AURA_MOD_POWER_REGEN
&Aura::HandleChannelDeathItem, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM
&Aura::HandleNoImmediateEffect, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN implemented in Unit::MeleeDamageBonusTaken and Unit::SpellDamageBonusTaken
&Aura::HandleNoImmediateEffect, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT implemented in Player::RegenerateHealth
&Aura::HandlePeriodicDamagePCT, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT
&Aura::HandleUnused, // 90 SPELL_AURA_MOD_RESIST_CHANCE Useless
&Aura::HandleNoImmediateEffect, // 91 SPELL_AURA_MOD_DETECT_RANGE implemented in Creature::GetAttackDistance
&Aura::HandlePreventFleeing, // 92 SPELL_AURA_PREVENTS_FLEEING
&Aura::HandleModUnattackable, // 93 SPELL_AURA_MOD_UNATTACKABLE
&Aura::HandleNoImmediateEffect, // 94 SPELL_AURA_INTERRUPT_REGEN implemented in Player::RegenerateAll
&Aura::HandleAuraGhost, // 95 SPELL_AURA_GHOST
&Aura::HandleNoImmediateEffect, // 96 SPELL_AURA_SPELL_MAGNET implemented in Unit::SelectMagnetTarget
&Aura::HandleManaShield, // 97 SPELL_AURA_MANA_SHIELD implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleAuraModSkill, // 98 SPELL_AURA_MOD_SKILL_TALENT
&Aura::HandleAuraModAttackPower, // 99 SPELL_AURA_MOD_ATTACK_POWER
&Aura::HandleUnused, //100 SPELL_AURA_AURAS_VISIBLE obsolete? all player can see all auras now
&Aura::HandleModResistancePercent, //101 SPELL_AURA_MOD_RESISTANCE_PCT
&Aura::HandleNoImmediateEffect, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModTotalThreat, //103 SPELL_AURA_MOD_TOTAL_THREAT
&Aura::HandleAuraWaterWalk, //104 SPELL_AURA_WATER_WALK
&Aura::HandleAuraFeatherFall, //105 SPELL_AURA_FEATHER_FALL
&Aura::HandleAuraHover, //106 SPELL_AURA_HOVER
&Aura::HandleAddModifier, //107 SPELL_AURA_ADD_FLAT_MODIFIER
&Aura::HandleAddModifier, //108 SPELL_AURA_ADD_PCT_MODIFIER
&Aura::HandleNoImmediateEffect, //109 SPELL_AURA_ADD_TARGET_TRIGGER
&Aura::HandleModPowerRegenPCT, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT
&Aura::HandleNoImmediateEffect, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER implemented in Unit::SelectMagnetTarget
&Aura::HandleNoImmediateEffect, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS implemented in diff functions.
&Aura::HandleNoImmediateEffect, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //115 SPELL_AURA_MOD_HEALING implemented in Unit::SpellBaseHealingBonusTaken
&Aura::HandleNoImmediateEffect, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT imppemented in Player::RegenerateAll and Player::RegenerateHealth
&Aura::HandleNoImmediateEffect, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //118 SPELL_AURA_MOD_HEALING_PCT implemented in Unit::SpellHealingBonusTaken
&Aura::HandleUnused, //119 SPELL_AURA_SHARE_PET_TRACKING useless
&Aura::HandleAuraUntrackable, //120 SPELL_AURA_UNTRACKABLE
&Aura::HandleAuraEmpathy, //121 SPELL_AURA_EMPATHY
&Aura::HandleModOffhandDamagePercent, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT
&Aura::HandleModTargetResistance, //123 SPELL_AURA_MOD_TARGET_RESISTANCE
&Aura::HandleAuraModRangedAttackPower, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER
&Aura::HandleNoImmediateEffect, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonusTaken
&Aura::HandleNoImmediateEffect, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleModPossessPet, //128 SPELL_AURA_MOD_POSSESS_PET
&Aura::HandleAuraModIncreaseSpeed, //129 SPELL_AURA_MOD_SPEED_ALWAYS
&Aura::HandleAuraModIncreaseMountedSpeed, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS
&Aura::HandleNoImmediateEffect, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModIncreaseEnergyPercent, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT
&Aura::HandleAuraModIncreaseHealthPercent, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT
&Aura::HandleAuraModRegenInterrupt, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT
&Aura::HandleModHealingDone, //135 SPELL_AURA_MOD_HEALING_DONE
&Aura::HandleNoImmediateEffect, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT implemented in Unit::SpellHealingBonusDone
&Aura::HandleModTotalPercentStat, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE
&Aura::HandleModMeleeSpeedPct, //138 SPELL_AURA_MOD_MELEE_HASTE
&Aura::HandleForceReaction, //139 SPELL_AURA_FORCE_REACTION
&Aura::HandleAuraModRangedHaste, //140 SPELL_AURA_MOD_RANGED_HASTE
&Aura::HandleRangedAmmoHaste, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE
&Aura::HandleAuraModBaseResistancePCT, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT
&Aura::HandleAuraModResistanceExclusive, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE
&Aura::HandleAuraSafeFall, //144 SPELL_AURA_SAFE_FALL implemented in WorldSession::HandleMovementOpcodes
&Aura::HandleUnused, //145 SPELL_AURA_CHARISMA obsolete?
&Aura::HandleUnused, //146 SPELL_AURA_PERSUADED obsolete?
&Aura::HandleModMechanicImmunityMask, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect (check part)
&Aura::HandleAuraRetainComboPoints, //148 SPELL_AURA_RETAIN_COMBO_POINTS
&Aura::HandleNoImmediateEffect, //149 SPELL_AURA_RESIST_PUSHBACK implemented in Spell::Delayed and Spell::DelayedChannel
&Aura::HandleShieldBlockValue, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT
&Aura::HandleAuraTrackStealthed, //151 SPELL_AURA_TRACK_STEALTHED
&Aura::HandleNoImmediateEffect, //152 SPELL_AURA_MOD_DETECTED_RANGE implemented in Creature::GetAttackDistance
&Aura::HandleNoImmediateEffect, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT implemented in Unit::CalculateAbsorbAndResist
&Aura::HandleNoImmediateEffect, //154 SPELL_AURA_MOD_STEALTH_LEVEL implemented in Unit::isVisibleForOrDetect
&Aura::HandleNoImmediateEffect, //155 SPELL_AURA_MOD_WATER_BREATHING implemented in Player::getMaxTimer
&Aura::HandleNoImmediateEffect, //156 SPELL_AURA_MOD_REPUTATION_GAIN implemented in Player::CalculateReputationGain
&Aura::HandleUnused, //157 SPELL_AURA_PET_DAMAGE_MULTI (single test like spell 20782, also single for 214 aura)
&Aura::HandleShieldBlockValue, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE
&Aura::HandleNoImmediateEffect, //159 SPELL_AURA_NO_PVP_CREDIT implemented in Player::RewardHonor
&Aura::HandleNoImmediateEffect, //160 SPELL_AURA_MOD_AOE_AVOIDANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT implemented in Player::RegenerateAll and Player::RegenerateHealth
&Aura::HandleAuraPowerBurn, //162 SPELL_AURA_POWER_BURN_MANA
&Aura::HandleNoImmediateEffect, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleUnused, //164 useless, only one test spell
&Aura::HandleNoImmediateEffect, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonusDone
&Aura::HandleAuraModAttackPowerPercent, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT
&Aura::HandleAuraModRangedAttackPowerPercent, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT
&Aura::HandleNoImmediateEffect, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS implemented in Unit::SpellDamageBonusDone, Unit::MeleeDamageBonusDone
&Aura::HandleNoImmediateEffect, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS implemented in Unit::DealDamageBySchool, Unit::DoAttackDamage, Unit::SpellCriticalBonus
&Aura::HandleDetectAmore, //170 SPELL_AURA_DETECT_AMORE only for Detect Amore spell
&Aura::HandleAuraModIncreaseSpeed, //171 SPELL_AURA_MOD_SPEED_NOT_STACK
&Aura::HandleAuraModIncreaseMountedSpeed, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK
&Aura::HandleUnused, //173 SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell
&Aura::HandleModSpellDamagePercentFromStat, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT implemented in Unit::SpellBaseDamageBonusDone
&Aura::HandleModSpellHealingPercentFromStat, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT implemented in Unit::SpellBaseHealingBonusDone
&Aura::HandleSpiritOfRedemption, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end
&Aura::HandleNULL, //177 SPELL_AURA_AOE_CHARM
&Aura::HandleNoImmediateEffect, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE implemented in Unit::SpellCriticalBonus
&Aura::HandleNoImmediateEffect, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS implemented in Unit::SpellDamageBonusDone
&Aura::HandleUnused, //181 SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS unused
&Aura::HandleAuraModResistenceOfStatPercent, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT
&Aura::HandleNoImmediateEffect, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746, implemented in ThreatCalcHelper::CalcThreat
&Aura::HandleNoImmediateEffect, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNoImmediateEffect, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNoImmediateEffect, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance
&Aura::HandleNoImmediateEffect, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE implemented in Unit::GetUnitCriticalChance
&Aura::HandleModRating, //189 SPELL_AURA_MOD_RATING
&Aura::HandleNoImmediateEffect, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN implemented in Player::CalculateReputationGain
&Aura::HandleAuraModUseNormalSpeed, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED
&Aura::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_MOD_MELEE_RANGED_HASTE
&Aura::HandleModCombatSpeedPct, //193 SPELL_AURA_HASTE_ALL (in fact combat (any type attack) speed pct)
&Aura::HandleUnused, //194 SPELL_AURA_MOD_DEPRICATED_1 not used now (old SPELL_AURA_MOD_SPELL_DAMAGE_OF_INTELLECT)
&Aura::HandleUnused, //195 SPELL_AURA_MOD_DEPRICATED_2 not used now (old SPELL_AURA_MOD_SPELL_HEALING_OF_INTELLECT)
&Aura::HandleNULL, //196 SPELL_AURA_MOD_COOLDOWN
&Aura::HandleNoImmediateEffect, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE implemented in Unit::SpellCriticalBonus Unit::GetUnitCriticalChance
&Aura::HandleUnused, //198 SPELL_AURA_MOD_ALL_WEAPON_SKILLS
&Aura::HandleNoImmediateEffect, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT implemented in Unit::MagicSpellHitResult
&Aura::HandleNoImmediateEffect, //200 SPELL_AURA_MOD_XP_PCT implemented in Player::GiveXP
&Aura::HandleAuraAllowFlight, //201 SPELL_AURA_FLY this aura enable flight mode...
&Aura::HandleNoImmediateEffect, //202 SPELL_AURA_IGNORE_COMBAT_RESULT implemented in Unit::MeleeSpellHitResult
&Aura::HandleNoImmediateEffect, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleNoImmediateEffect, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE implemented in Unit::CalculateMeleeDamage and Unit::SpellCriticalDamageBonus
&Aura::HandleNoImmediateEffect, //205 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE implemented in Unit::SpellCriticalDamageBonus
&Aura::HandleAuraModIncreaseFlightSpeed, //206 SPELL_AURA_MOD_FLIGHT_SPEED
&Aura::HandleAuraModIncreaseFlightSpeed, //207 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED
&Aura::HandleAuraModIncreaseFlightSpeed, //208 SPELL_AURA_MOD_FLIGHT_SPEED_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //209 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //210 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING
&Aura::HandleAuraModIncreaseFlightSpeed, //211 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING
&Aura::HandleAuraModRangedAttackPowerOfStatPercent, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT
&Aura::HandleNoImmediateEffect, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage
&Aura::HandleNULL, //214 Tamed Pet Passive
&Aura::HandleArenaPreparation, //215 SPELL_AURA_ARENA_PREPARATION
&Aura::HandleModCastingSpeed, //216 SPELL_AURA_HASTE_SPELLS
&Aura::HandleUnused, //217 unused
&Aura::HandleAuraModRangedHaste, //218 SPELL_AURA_HASTE_RANGED
&Aura::HandleModManaRegen, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT
&Aura::HandleUnused, //220 SPELL_AURA_MOD_RATING_FROM_STAT
&Aura::HandleNULL, //221 ignored
&Aura::HandleUnused, //222 unused
&Aura::HandleNULL, //223 Cold Stare
&Aura::HandleUnused, //224 unused
&Aura::HandleNoImmediateEffect, //225 SPELL_AURA_PRAYER_OF_MENDING
&Aura::HandleAuraPeriodicDummy, //226 SPELL_AURA_PERIODIC_DUMMY
&Aura::HandlePeriodicTriggerSpellWithValue, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE
&Aura::HandleNoImmediateEffect, //228 SPELL_AURA_DETECT_STEALTH
&Aura::HandleNoImmediateEffect, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE implemented in Unit::SpellDamageBonusTaken
&Aura::HandleAuraModIncreaseMaxHealth, //230 Commanding Shout
&Aura::HandleNoImmediateEffect, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE
&Aura::HandleNoImmediateEffect, //232 SPELL_AURA_MECHANIC_DURATION_MOD implement in Unit::CalculateAuraDuration
&Aura::HandleNULL, //233 set model id to the one of the creature with id m_modifier.m_miscvalue
&Aura::HandleNoImmediateEffect, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK implement in Unit::CalculateAuraDuration
&Aura::HandleAuraModDispelResist, //235 SPELL_AURA_MOD_DISPEL_RESIST implement in Unit::MagicSpellHitResult
&Aura::HandleUnused, //236 unused
&Aura::HandleModSpellDamagePercentFromAttackPower, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER implemented in Unit::SpellBaseDamageBonusDone
&Aura::HandleModSpellHealingPercentFromAttackPower, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER implemented in Unit::SpellBaseHealingBonusDone
&Aura::HandleAuraModScale, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61
&Aura::HandleAuraModExpertise, //240 SPELL_AURA_MOD_EXPERTISE
&Aura::HandleForceMoveForward, //241 Forces the caster to move forward
&Aura::HandleUnused, //242 unused
&Aura::HandleUnused, //243 used by two test spells
&Aura::HandleComprehendLanguage, //244 SPELL_AURA_COMPREHEND_LANGUAGE
&Aura::HandleUnused, //245 unused
&Aura::HandleUnused, //246 unused
&Aura::HandleAuraMirrorImage, //247 SPELL_AURA_MIRROR_IMAGE target to become a clone of the caster
&Aura::HandleNoImmediateEffect, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE implemented in Unit::RollMeleeOutcomeAgainst
&Aura::HandleNULL, //249
&Aura::HandleAuraModIncreaseHealth, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2
&Aura::HandleNULL, //251 SPELL_AURA_MOD_ENEMY_DODGE
&Aura::HandleUnused, //252 unused
&Aura::HandleUnused, //253 unused
&Aura::HandleUnused, //254 unused
&Aura::HandleUnused, //255 unused
&Aura::HandleUnused, //256 unused
&Aura::HandleUnused, //257 unused
&Aura::HandleUnused, //258 unused
&Aura::HandleUnused, //259 unused
&Aura::HandleUnused, //260 unused
&Aura::HandleNULL //261 SPELL_AURA_261 some phased state (44856 spell)
};
static AuraType const frozenAuraTypes[] = { SPELL_AURA_MOD_ROOT, SPELL_AURA_MOD_STUN, SPELL_AURA_NONE };
Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) :
m_spellmod(NULL), m_periodicTimer(0), m_periodicTick(0), m_removeMode(AURA_REMOVE_BY_DEFAULT),
m_effIndex(eff), m_positive(false), m_isPeriodic(false), m_isAreaAura(false),
m_isPersistent(false), m_in_use(0), m_spellAuraHolder(holder)
{
MANGOS_ASSERT(target);
MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element");
m_currentBasePoints = currentBasePoints ? *currentBasePoints : spellproto->CalculateSimpleValue(eff);
m_positive = IsPositiveEffect(spellproto, m_effIndex);
m_applyTime = time(NULL);
int32 damage;
if (!caster)
damage = m_currentBasePoints;
else
{
damage = caster->CalculateSpellDamage(target, spellproto, m_effIndex, &m_currentBasePoints);
if (!damage && castItem && castItem->GetItemSuffixFactor())
{
ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(castItem->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < 3; ++k)
{
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(item_rand_suffix->enchant_id[k]);
if (pEnchant)
{
for (int t = 0; t < 3; ++t)
{
if (pEnchant->spellid[t] != spellproto->Id)
continue;
damage = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000);
break;
}
}
if (damage)
break;
}
}
}
}
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura: construct Spellid : %u, Aura : %u Target : %d Damage : %d", spellproto->Id, spellproto->EffectApplyAuraName[eff], spellproto->EffectImplicitTargetA[eff], damage);
SetModifier(AuraType(spellproto->EffectApplyAuraName[eff]), damage, spellproto->EffectAmplitude[eff], spellproto->EffectMiscValue[eff]);
Player* modOwner = caster ? caster->GetSpellModOwner() : NULL;
// Apply periodic time mod
if (modOwner && m_modifier.periodictime)
modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_ACTIVATION_TIME, m_modifier.periodictime);
// Start periodic on next tick or at aura apply
if (!spellproto->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY))
m_periodicTimer = m_modifier.periodictime;
}
Aura::~Aura()
{
}
AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
m_isAreaAura = true;
// caster==NULL in constructor args if target==caster in fact
Unit* caster_ptr = caster ? caster : target;
m_radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellproto->EffectRadiusIndex[m_effIndex]));
if (Player* modOwner = caster_ptr->GetSpellModOwner())
modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_RADIUS, m_radius);
switch (spellproto->Effect[eff])
{
case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
m_areaAuraType = AREA_AURA_PARTY;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
m_areaAuraType = AREA_AURA_FRIEND;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY:
m_areaAuraType = AREA_AURA_ENEMY;
if (target == caster_ptr)
m_modifier.m_auraname = SPELL_AURA_NONE; // Do not do any effect on self
break;
case SPELL_EFFECT_APPLY_AREA_AURA_PET:
m_areaAuraType = AREA_AURA_PET;
break;
case SPELL_EFFECT_APPLY_AREA_AURA_OWNER:
m_areaAuraType = AREA_AURA_OWNER;
if (target == caster_ptr)
m_modifier.m_auraname = SPELL_AURA_NONE;
break;
default:
sLog.outError("Wrong spell effect in AreaAura constructor");
MANGOS_ASSERT(false);
break;
}
// totems are immune to any kind of area auras
if (target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsTotem())
m_modifier.m_auraname = SPELL_AURA_NONE;
}
AreaAura::~AreaAura()
{
}
PersistentAreaAura::PersistentAreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
m_isPersistent = true;
}
PersistentAreaAura::~PersistentAreaAura()
{
}
SingleEnemyTargetAura::SingleEnemyTargetAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target,
Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem)
{
if (caster)
m_castersTargetGuid = caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)caster)->GetSelectionGuid() : caster->GetTargetGuid();
}
SingleEnemyTargetAura::~SingleEnemyTargetAura()
{
}
Unit* SingleEnemyTargetAura::GetTriggerTarget() const
{
return ObjectAccessor::GetUnit(*(m_spellAuraHolder->GetTarget()), m_castersTargetGuid);
}
Aura* CreateAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem)
{
if (IsAreaAuraEffect(spellproto->Effect[eff]))
return new AreaAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
uint32 triggeredSpellId = spellproto->EffectTriggerSpell[eff];
if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(triggeredSpellId))
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
if (triggeredSpellInfo->EffectImplicitTargetA[i] == TARGET_SINGLE_ENEMY)
return new SingleEnemyTargetAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
return new Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem);
}
SpellAuraHolder* CreateSpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem)
{
return new SpellAuraHolder(spellproto, target, caster, castItem);
}
void Aura::SetModifier(AuraType t, int32 a, uint32 pt, int32 miscValue)
{
m_modifier.m_auraname = t;
m_modifier.m_amount = a;
m_modifier.m_miscvalue = miscValue;
m_modifier.periodictime = pt;
}
void Aura::Update(uint32 diff)
{
if (m_isPeriodic)
{
m_periodicTimer -= diff;
if (m_periodicTimer <= 0) // tick also at m_periodicTimer==0 to prevent lost last tick in case max m_duration == (max m_periodicTimer)*N
{
// update before applying (aura can be removed in TriggerSpell or PeriodicTick calls)
m_periodicTimer += m_modifier.periodictime;
++m_periodicTick; // for some infinity auras in some cases can overflow and reset
PeriodicTick();
}
}
}
void AreaAura::Update(uint32 diff)
{
// update for the caster of the aura
if (GetCasterGuid() == GetTarget()->GetObjectGuid())
{
Unit* caster = GetTarget();
if (!caster->hasUnitState(UNIT_STAT_ISOLATED))
{
Unit* owner = caster->GetCharmerOrOwner();
if (!owner)
owner = caster;
Spell::UnitList targets;
switch (m_areaAuraType)
{
case AREA_AURA_PARTY:
{
Group* pGroup = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
pGroup = ((Player*)owner)->GetGroup();
if (pGroup)
{
uint8 subgroup = ((Player*)owner)->GetSubGroup();
for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
if (Target && Target->isAlive() && Target->GetSubGroup() == subgroup && caster->IsFriendlyTo(Target))
{
if (caster->IsWithinDistInMap(Target, m_radius))
targets.push_back(Target);
Pet* pet = Target->GetPet();
if (pet && pet->isAlive() && caster->IsWithinDistInMap(pet, m_radius))
targets.push_back(pet);
}
}
}
else
{
// add owner
if (owner != caster && caster->IsWithinDistInMap(owner, m_radius))
targets.push_back(owner);
// add caster's pet
Unit* pet = caster->GetPet();
if (pet && caster->IsWithinDistInMap(pet, m_radius))
targets.push_back(pet);
}
break;
}
case AREA_AURA_FRIEND:
{
MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(caster, m_radius);
MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
Cell::VisitAllObjects(caster, searcher, m_radius);
break;
}
case AREA_AURA_ENEMY:
{
MaNGOS::AnyAoETargetUnitInObjectRangeCheck u_check(caster, m_radius); // No GetCharmer in searcher
MaNGOS::UnitListSearcher<MaNGOS::AnyAoETargetUnitInObjectRangeCheck> searcher(targets, u_check);
Cell::VisitAllObjects(caster, searcher, m_radius);
break;
}
case AREA_AURA_OWNER:
case AREA_AURA_PET:
{
if (owner != caster && caster->IsWithinDistInMap(owner, m_radius))
targets.push_back(owner);
break;
}
}
for (Spell::UnitList::iterator tIter = targets.begin(); tIter != targets.end(); ++tIter)
{
// flag for seelction is need apply aura to current iteration target
bool apply = true;
// we need ignore present caster self applied are auras sometime
// in cases if this only auras applied for spell effect
Unit::SpellAuraHolderBounds spair = (*tIter)->GetSpellAuraHolderBounds(GetId());
for (Unit::SpellAuraHolderMap::const_iterator i = spair.first; i != spair.second; ++i)
{
if (i->second->IsDeleted())
continue;
Aura* aur = i->second->GetAuraByEffectIndex(m_effIndex);
if (!aur)
continue;
switch (m_areaAuraType)
{
case AREA_AURA_ENEMY:
// non caster self-casted auras (non stacked)
if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE)
apply = false;
break;
default:
// in generic case not allow stacking area auras
apply = false;
break;
}
if (!apply)
break;
}
if (!apply)
continue;
// Skip some targets (TODO: Might require better checks, also unclear how the actual caster must/can be handled)
if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX3_TARGET_ONLY_PLAYER) && (*tIter)->GetTypeId() != TYPEID_PLAYER)
continue;
if (SpellEntry const* actualSpellInfo = sSpellMgr.SelectAuraRankForLevel(GetSpellProto(), (*tIter)->getLevel()))
{
int32 actualBasePoints = m_currentBasePoints;
// recalculate basepoints for lower rank (all AreaAura spell not use custom basepoints?)
if (actualSpellInfo != GetSpellProto())
actualBasePoints = actualSpellInfo->CalculateSimpleValue(m_effIndex);
SpellAuraHolder* holder = (*tIter)->GetSpellAuraHolder(actualSpellInfo->Id, GetCasterGuid());
bool addedToExisting = true;
if (!holder)
{
holder = CreateSpellAuraHolder(actualSpellInfo, (*tIter), caster);
addedToExisting = false;
}
holder->SetAuraDuration(GetAuraDuration());
AreaAura* aur = new AreaAura(actualSpellInfo, m_effIndex, &actualBasePoints, holder, (*tIter), caster, NULL);
holder->AddAura(aur, m_effIndex);
if (addedToExisting)
{
(*tIter)->AddAuraToModList(aur);
holder->SetInUse(true);
aur->ApplyModifier(true, true);
holder->SetInUse(false);
}
else
(*tIter)->AddSpellAuraHolder(holder);
}
}
}
Aura::Update(diff);
}
else // aura at non-caster
{
Unit* caster = GetCaster();
Unit* target = GetTarget();
Aura::Update(diff);
// remove aura if out-of-range from caster (after teleport for example)
// or caster is isolated or caster no longer has the aura
// or caster is (no longer) friendly
bool needFriendly = (m_areaAuraType == AREA_AURA_ENEMY ? false : true);
if (!caster || caster->hasUnitState(UNIT_STAT_ISOLATED) ||
!caster->IsWithinDistInMap(target, m_radius) ||
!caster->HasAura(GetId(), GetEffIndex()) ||
caster->IsFriendlyTo(target) != needFriendly
)
{
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
else if (m_areaAuraType == AREA_AURA_PARTY) // check if in same sub group
{
// not check group if target == owner or target == pet
if (caster->GetCharmerOrOwnerGuid() != target->GetObjectGuid() && caster->GetObjectGuid() != target->GetCharmerOrOwnerGuid())
{
Player* check = caster->GetCharmerOrOwnerPlayerOrPlayerItself();
Group* pGroup = check ? check->GetGroup() : NULL;
if (pGroup)
{
Player* checkTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself();
if (!checkTarget || !pGroup->SameSubGroup(check, checkTarget))
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
else
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
}
else if (m_areaAuraType == AREA_AURA_PET || m_areaAuraType == AREA_AURA_OWNER)
{
if (target->GetObjectGuid() != caster->GetCharmerOrOwnerGuid())
target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid());
}
}
}
void PersistentAreaAura::Update(uint32 diff)
{
bool remove = false;
// remove the aura if its caster or the dynamic object causing it was removed
// or if the target moves too far from the dynamic object
if (Unit* caster = GetCaster())
{
DynamicObject* dynObj = caster->GetDynObject(GetId(), GetEffIndex());
if (dynObj)
{
if (!GetTarget()->IsWithinDistInMap(dynObj, dynObj->GetRadius()))
{
remove = true;
dynObj->RemoveAffected(GetTarget()); // let later reapply if target return to range
}
}
else
remove = true;
}
else
remove = true;
Aura::Update(diff);
if (remove)
GetTarget()->RemoveAura(GetId(), GetEffIndex());
}
void Aura::ApplyModifier(bool apply, bool Real)
{
AuraType aura = m_modifier.m_auraname;
GetHolder()->SetInUse(true);
SetInUse(true);
if (aura < TOTAL_AURAS)
(*this.*AuraHandler [aura])(apply, Real);
SetInUse(false);
GetHolder()->SetInUse(false);
}
bool Aura::isAffectedOnSpell(SpellEntry const* spell) const
{
if (m_spellmod)
return m_spellmod->isAffectedOnSpell(spell);
// Check family name
if (spell->SpellFamilyName != GetSpellProto()->SpellFamilyName)
return false;
ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex());
return spell->IsFitToFamilyMask(mask);
}
bool Aura::CanProcFrom(SpellEntry const* spell, uint32 EventProcEx, uint32 procEx, bool active, bool useClassMask) const
{
// Check EffectClassMask (in pre-3.x stored in spell_affect in fact)
ClassFamilyMask mask = sSpellMgr.GetSpellAffectMask(GetId(), GetEffIndex());
// if no class mask defined, or spell_proc_event has SpellFamilyName=0 - allow proc
if (!useClassMask || !mask)
{
if (!(EventProcEx & PROC_EX_EX_TRIGGER_ALWAYS))
{
// Check for extra req (if none) and hit/crit
if (EventProcEx == PROC_EX_NONE)
{
// No extra req, so can trigger only for active (damage/healing present) and hit/crit
if ((procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) && active)
return true;
else
return false;
}
else // Passive spells hits here only if resist/reflect/immune/evade
{
// Passive spells can`t trigger if need hit (exclude cases when procExtra include non-active flags)
if ((EventProcEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT) & procEx) && !active)
return false;
}
}
return true;
}
else
{
// SpellFamilyName check is performed in SpellMgr::IsSpellProcEventCanTriggeredBy and it is done once for whole holder
// note: SpellFamilyName is not checked if no spell_proc_event is defined
return mask.IsFitToFamilyMask(spell->SpellFamilyFlags);
}
}
void Aura::ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode)
{
// we need store cast item guids for self casted spells
// expected that not exist permanent auras from stackable auras from different items
std::map<uint32, ObjectGuid> affectedSelf;
std::set<uint32> affectedAuraCaster;
for (Unit::SpellAuraHolderMap::const_iterator itr = target->GetSpellAuraHolderMap().begin(); itr != target->GetSpellAuraHolderMap().end(); ++itr)
{
// permanent passive or permanent area aura
// passive spells can be affected only by own or owner spell mods)
if ((itr->second->IsPermanent() && ((owner_mode && itr->second->IsPassive()) || itr->second->IsAreaAura())) &&
// non deleted and not same aura (any with same spell id)
!itr->second->IsDeleted() && itr->second->GetId() != GetId() &&
// and affected by aura
isAffectedOnSpell(itr->second->GetSpellProto()))
{
// only applied by self or aura caster
if (itr->second->GetCasterGuid() == target->GetObjectGuid())
affectedSelf[itr->second->GetId()] = itr->second->GetCastItemGuid();
else if (itr->second->GetCasterGuid() == GetCasterGuid())
affectedAuraCaster.insert(itr->second->GetId());
}
}
if (!affectedSelf.empty())
{
Player* pTarget = target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : NULL;
for (std::map<uint32, ObjectGuid>::const_iterator map_itr = affectedSelf.begin(); map_itr != affectedSelf.end(); ++map_itr)
{
Item* item = pTarget && map_itr->second ? pTarget->GetItemByGuid(map_itr->second) : NULL;
target->RemoveAurasDueToSpell(map_itr->first);
target->CastSpell(target, map_itr->first, true, item);
}
}
if (!affectedAuraCaster.empty())
{
Unit* caster = GetCaster();
for (std::set<uint32>::const_iterator set_itr = affectedAuraCaster.begin(); set_itr != affectedAuraCaster.end(); ++set_itr)
{
target->RemoveAurasDueToSpell(*set_itr);
if (caster)
caster->CastSpell(GetTarget(), *set_itr, true);
}
}
}
struct ReapplyAffectedPassiveAurasHelper
{
explicit ReapplyAffectedPassiveAurasHelper(Aura* _aura) : aura(_aura) {}
void operator()(Unit* unit) const { aura->ReapplyAffectedPassiveAuras(unit, true); }
Aura* aura;
};
void Aura::ReapplyAffectedPassiveAuras()
{
// not reapply spell mods with charges (use original value because processed and at remove)
if (GetSpellProto()->procCharges)
return;
// not reapply some spell mods ops (mostly speedup case)
switch (m_modifier.m_miscvalue)
{
case SPELLMOD_DURATION:
case SPELLMOD_CHARGES:
case SPELLMOD_NOT_LOSE_CASTING_TIME:
case SPELLMOD_CASTING_TIME:
case SPELLMOD_COOLDOWN:
case SPELLMOD_COST:
case SPELLMOD_ACTIVATION_TIME:
case SPELLMOD_CASTING_TIME_OLD:
return;
}
// reapply talents to own passive persistent auras
ReapplyAffectedPassiveAuras(GetTarget(), true);
// re-apply talents/passives/area auras applied to pet/totems (it affected by player spellmods)
GetTarget()->CallForAllControlledUnits(ReapplyAffectedPassiveAurasHelper(this), CONTROLLED_PET | CONTROLLED_TOTEMS);
// re-apply talents/passives/area auras applied to group members (it affected by player spellmods)
if (Group* group = ((Player*)GetTarget())->GetGroup())
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* member = itr->getSource())
if (member != GetTarget() && member->IsInMap(GetTarget()))
ReapplyAffectedPassiveAuras(member, false);
}
/*********************************************************/
/*** BASIC AURA FUNCTION ***/
/*********************************************************/
void Aura::HandleAddModifier(bool apply, bool Real)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER || !Real)
return;
if (m_modifier.m_miscvalue >= MAX_SPELLMOD)
return;
if (apply)
{
SpellEntry const* spellProto = GetSpellProto();
// Add custom charges for some mod aura
switch (spellProto->Id)
{
case 17941: // Shadow Trance
case 22008: // Netherwind Focus
case 34936: // Backlash
GetHolder()->SetAuraCharges(1);
break;
}
m_spellmod = new SpellModifier(
SpellModOp(m_modifier.m_miscvalue),
SpellModType(m_modifier.m_auraname), // SpellModType value == spell aura types
m_modifier.m_amount,
this,
// prevent expire spell mods with (charges > 0 && m_stackAmount > 1)
// all this spell expected expire not at use but at spell proc event check
spellProto->StackAmount > 1 ? 0 : GetHolder()->GetAuraCharges());
}
((Player*)GetTarget())->AddSpellMod(m_spellmod, apply);
ReapplyAffectedPassiveAuras();
}
void Aura::TriggerSpell()
{
ObjectGuid casterGUID = GetCasterGuid();
Unit* triggerTarget = GetTriggerTarget();
if (!casterGUID || !triggerTarget)
return;
// generic casting code with custom spells and target/caster customs
uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex];
SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id);
SpellEntry const* auraSpellInfo = GetSpellProto();
uint32 auraId = auraSpellInfo->Id;
Unit* target = GetTarget();
Unit* triggerCaster = triggerTarget;
WorldObject* triggerTargetObject = NULL;
// specific code for cases with no trigger spell provided in field
if (triggeredSpellInfo == NULL)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (auraId)
{
// Firestone Passive (1-5 ranks)
case 758:
case 17945:
case 17947:
case 17949:
case 27252:
{
if (triggerTarget->GetTypeId() != TYPEID_PLAYER)
return;
Item* item = ((Player*)triggerTarget)->GetWeaponForAttack(BASE_ATTACK);
if (!item)
return;
uint32 enchant_id = 0;
switch (GetId())
{
case 758: enchant_id = 1803; break; // Rank 1
case 17945: enchant_id = 1823; break; // Rank 2
case 17947: enchant_id = 1824; break; // Rank 3
case 17949: enchant_id = 1825; break; // Rank 4
case 27252: enchant_id = 2645; break; // Rank 5
default:
return;
}
// remove old enchanting before applying new
((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false);
item->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, m_modifier.periodictime + 1000, 0);
// add new enchanting
((Player*)triggerTarget)->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, true);
return;
}
case 812: // Periodic Mana Burn
{
trigger_spell_id = 25779; // Mana Burn
if (GetTarget()->GetTypeId() != TYPEID_UNIT)
return;
triggerTarget = ((Creature*)GetTarget())->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, trigger_spell_id, SELECT_FLAG_POWER_MANA);
if (!triggerTarget)
return;
break;
}
// // Polymorphic Ray
// case 6965: break;
// // Fire Nova (1-7 ranks)
// case 8350:
// case 8508:
// case 8509:
// case 11312:
// case 11313:
// case 25540:
// case 25544:
// break;
case 9712: // Thaumaturgy Channel
trigger_spell_id = 21029;
break;
// // Egan's Blaster
// case 17368: break;
// // Haunted
// case 18347: break;
// // Ranshalla Waiting
// case 18953: break;
// // Inferno
// case 19695: break;
// // Frostwolf Muzzle DND
// case 21794: break;
// // Alterac Ram Collar DND
// case 21866: break;
// // Celebras Waiting
// case 21916: break;
case 23170: // Brood Affliction: Bronze
{
target->CastSpell(target, 23171, true, NULL, this);
return;
}
case 23184: // Mark of Frost
case 25041: // Mark of Nature
case 37125: // Mark of Death
{
std::list<Player*> targets;
// spells existed in 1.x.x; 23183 - mark of frost; 25042 - mark of nature; both had radius of 100.0 yards in 1.x.x DBC
// spells are used by Azuregos and the Emerald dragons in order to put a stun debuff on the players which resurrect during the encounter
// in order to implement the missing spells we need to make a grid search for hostile players and check their auras; if they are marked apply debuff
// spell 37127 used for the Mark of Death, is used server side, so it needs to be implemented here
uint32 markSpellId = 0;
uint32 debuffSpellId = 0;
switch (auraId)
{
case 23184:
markSpellId = 23182;
debuffSpellId = 23186;
break;
case 25041:
markSpellId = 25040;
debuffSpellId = 25043;
break;
case 37125:
markSpellId = 37128;
debuffSpellId = 37131;
break;
}
MaNGOS::AnyPlayerInObjectRangeWithAuraCheck u_check(GetTarget(), 100.0f, markSpellId);
MaNGOS::PlayerListSearcher<MaNGOS::AnyPlayerInObjectRangeWithAuraCheck > checker(targets, u_check);
Cell::VisitWorldObjects(GetTarget(), checker, 100.0f);
for (std::list<Player*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
(*itr)->CastSpell((*itr), debuffSpellId, true, NULL, NULL, casterGUID);
return;
}
case 23493: // Restoration
{
uint32 heal = triggerTarget->GetMaxHealth() / 10;
triggerTarget->DealHeal(triggerTarget, heal, auraSpellInfo);
if (int32 mana = triggerTarget->GetMaxPower(POWER_MANA))
{
mana /= 10;
triggerTarget->EnergizeBySpell(triggerTarget, 23493, mana, POWER_MANA);
}
return;
}
// // Stoneclaw Totem Passive TEST
// case 23792: break;
// // Axe Flurry
// case 24018: break;
case 24210: // Mark of Arlokk
{
// Replacement for (classic) spell 24211 (doesn't exist anymore)
std::list<Creature*> lList;
// Search for all Zulian Prowler in range
MaNGOS::AllCreaturesOfEntryInRangeCheck check(triggerTarget, 15101, 15.0f);
MaNGOS::CreatureListSearcher<MaNGOS::AllCreaturesOfEntryInRangeCheck> searcher(lList, check);
Cell::VisitGridObjects(triggerTarget, searcher, 15.0f);
for (std::list<Creature*>::const_iterator itr = lList.begin(); itr != lList.end(); ++itr)
if ((*itr)->isAlive())
(*itr)->AddThreat(triggerTarget, float(5000));
return;
}
// // Restoration
// case 24379: break;
// // Happy Pet
// case 24716: break;
case 24780: // Dream Fog
{
// Note: In 1.12 triggered spell 24781 still exists, need to script dummy effect for this spell then
// Select an unfriendly enemy in 100y range and attack it
if (target->GetTypeId() != TYPEID_UNIT)
return;
ThreatList const& tList = target->getThreatManager().getThreatList();
for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr)
{
Unit* pUnit = target->GetMap()->GetUnit((*itr)->getUnitGuid());
if (pUnit && target->getThreatManager().getThreat(pUnit))
target->getThreatManager().modifyThreatPercent(pUnit, -100);
}
if (Unit* pEnemy = target->SelectRandomUnfriendlyTarget(target->getVictim(), 100.0f))
((Creature*)target)->AI()->AttackStart(pEnemy);
return;
}
// // Cannon Prep
// case 24832: break;
case 24834: // Shadow Bolt Whirl
{
uint32 spellForTick[8] = { 24820, 24821, 24822, 24823, 24835, 24836, 24837, 24838 };
uint32 tick = (GetAuraTicks() + 7/*-1*/) % 8;
// casted in left/right (but triggered spell have wide forward cone)
float forward = target->GetOrientation();
if (tick <= 3)
target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); // Left
else
target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); // Right
triggerTarget->CastSpell(triggerTarget, spellForTick[tick], true, NULL, this, casterGUID);
target->SetOrientation(forward);
return;
}
// // Stink Trap
// case 24918: break;
// // Agro Drones
// case 25152: break;
case 25371: // Consume
{
int32 bpDamage = triggerTarget->GetMaxHealth() * 10 / 100;
triggerTarget->CastCustomSpell(triggerTarget, 25373, &bpDamage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// // Pain Spike
// case 25572: break;
case 26009: // Rotate 360
case 26136: // Rotate -360
{
float newAngle = target->GetOrientation();
if (auraId == 26009)
newAngle += M_PI_F / 40;
else
newAngle -= M_PI_F / 40;
newAngle = MapManager::NormalizeOrientation(newAngle);
target->SetFacingTo(newAngle);
target->CastSpell(target, 26029, true);
return;
}
// // Consume
// case 26196: break;
// // Berserk
// case 26615: break;
// // Defile
// case 27177: break;
// // Teleport: IF/UC
// case 27601: break;
// // Five Fat Finger Exploding Heart Technique
// case 27673: break;
// // Nitrous Boost
// case 27746: break;
// // Steam Tank Passive
// case 27747: break;
case 27808: // Frost Blast
{
int32 bpDamage = triggerTarget->GetMaxHealth() * 26 / 100;
triggerTarget->CastCustomSpell(triggerTarget, 29879, &bpDamage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// Detonate Mana
case 27819:
{
// 50% Mana Burn
int32 bpDamage = (int32)triggerTarget->GetPower(POWER_MANA) * 0.5f;
triggerTarget->ModifyPower(POWER_MANA, -bpDamage);
triggerTarget->CastCustomSpell(triggerTarget, 27820, &bpDamage, NULL, NULL, true, NULL, this, triggerTarget->GetObjectGuid());
return;
}
// // Controller Timer
// case 28095: break;
// Stalagg Chain and Feugen Chain
case 28096:
case 28111:
{
// X-Chain is casted by Tesla to X, so: caster == Tesla, target = X
Unit* pCaster = GetCaster();
if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT && !pCaster->IsWithinDistInMap(target, 60.0f))
{
pCaster->InterruptNonMeleeSpells(true);
((Creature*)pCaster)->SetInCombatWithZone();
// Stalagg Tesla Passive or Feugen Tesla Passive
pCaster->CastSpell(pCaster, auraId == 28096 ? 28097 : 28109, true, NULL, NULL, target->GetObjectGuid());
}
return;
}
// Stalagg Tesla Passive and Feugen Tesla Passive
case 28097:
case 28109:
{
// X-Tesla-Passive is casted by Tesla on Tesla with original caster X, so: caster = X, target = Tesla
Unit* pCaster = GetCaster();
if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT)
{
if (pCaster->getVictim() && !pCaster->IsWithinDistInMap(target, 60.0f))
{
if (Unit* pTarget = ((Creature*)pCaster)->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
target->CastSpell(pTarget, 28099, false);// Shock
}
else
{
// "Evade"
target->RemoveAurasDueToSpell(auraId);
target->DeleteThreatList();
target->CombatStop(true);
// Recast chain (Stalagg Chain or Feugen Chain
target->CastSpell(pCaster, auraId == 28097 ? 28096 : 28111, false);
}
}
return;
}
// // Mark of Didier
// case 28114: break;
// // Communique Timer, camp
// case 28346: break;
// // Icebolt
// case 28522: break;
// // Silithyst
// case 29519: break;
case 29528: // Inoculate Nestlewood Owlkin
// prevent error reports in case ignored player target
if (triggerTarget->GetTypeId() != TYPEID_UNIT)
return;
break;
// // Overload
// case 29768: break;
// // Return Fire
// case 29788: break;
// // Return Fire
// case 29793: break;
// // Return Fire
// case 29794: break;
// // Guardian of Icecrown Passive
// case 29897: break;
case 29917: // Feed Captured Animal
trigger_spell_id = 29916;
break;
// // Flame Wreath
// case 29946: break;
// // Flame Wreath
// case 29947: break;
// // Mind Exhaustion Passive
// case 30025: break;
// // Nether Beam - Serenity
// case 30401: break;
case 30427: // Extract Gas
{
Unit* caster = GetCaster();
if (!caster)
return;
// move loot to player inventory and despawn target
if (caster->GetTypeId() == TYPEID_PLAYER &&
triggerTarget->GetTypeId() == TYPEID_UNIT &&
((Creature*)triggerTarget)->GetCreatureInfo()->type == CREATURE_TYPE_GAS_CLOUD)
{
Player* player = (Player*)caster;
Creature* creature = (Creature*)triggerTarget;
// missing lootid has been reported on startup - just return
if (!creature->GetCreatureInfo()->SkinLootId)
return;
player->AutoStoreLoot(creature, creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, true);
creature->ForcedDespawn();
}
return;
}
case 30576: // Quake
trigger_spell_id = 30571;
break;
// // Burning Maul
// case 30598: break;
// // Regeneration
// case 30799:
// case 30800:
// case 30801:
// break;
// // Despawn Self - Smoke cloud
// case 31269: break;
// // Time Rift Periodic
// case 31320: break;
// // Corrupt Medivh
// case 31326: break;
case 31347: // Doom
{
target->CastSpell(target, 31350, true);
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
return;
}
case 31373: // Spellcloth
{
// Summon Elemental after create item
triggerTarget->SummonCreature(17870, 0.0f, 0.0f, 0.0f, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
return;
}
// // Bloodmyst Tesla
// case 31611: break;
case 31944: // Doomfire
{
int32 damage = m_modifier.m_amount * ((GetAuraDuration() + m_modifier.periodictime) / GetAuraMaxDuration());
triggerTarget->CastCustomSpell(triggerTarget, 31969, &damage, NULL, NULL, true, NULL, this, casterGUID);
return;
}
// // Teleport Test
// case 32236: break;
// // Earthquake
// case 32686: break;
// // Possess
// case 33401: break;
// // Draw Shadows
// case 33563: break;
// // Murmur's Touch
// case 33711: break;
case 34229: // Flame Quills
{
// cast 24 spells 34269-34289, 34314-34316
for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id)
triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID);
for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id)
triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID);
return;
}
// // Gravity Lapse
// case 34480: break;
// // Tornado
// case 34683: break;
// // Frostbite Rotate
// case 34748: break;
// // Arcane Flurry
// case 34821: break;
// // Interrupt Shutdown
// case 35016: break;
// // Interrupt Shutdown
// case 35176: break;
// // Inferno
// case 35268: break;
// // Salaadin's Tesla
// case 35515: break;
// // Ethereal Channel (Red)
// case 35518: break;
// // Nether Vapor
// case 35879: break;
// // Dark Portal Storm
// case 36018: break;
// // Burning Maul
// case 36056: break;
// // Living Grove Defender Lifespan
// case 36061: break;
// // Professor Dabiri Talks
// case 36064: break;
// // Kael Gaining Power
// case 36091: break;
// // They Must Burn Bomb Aura
// case 36344: break;
// // They Must Burn Bomb Aura (self)
// case 36350: break;
// // Stolen Ravenous Ravager Egg
// case 36401: break;
// // Activated Cannon
// case 36410: break;
// // Stolen Ravenous Ravager Egg
// case 36418: break;
// // Enchanted Weapons
// case 36510: break;
// // Cursed Scarab Periodic
// case 36556: break;
// // Cursed Scarab Despawn Periodic
// case 36561: break;
case 36573: // Vision Guide
{
if (GetAuraTicks() == 10 && target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->AreaExploredOrEventHappens(10525);
target->RemoveAurasDueToSpell(36573);
}
return;
}
// // Cannon Charging (platform)
// case 36785: break;
// // Cannon Charging (self)
// case 36860: break;
case 37027: // Remote Toy
trigger_spell_id = 37029;
break;
// // Mark of Death
// case 37125: break;
// // Arcane Flurry
// case 37268: break;
case 37429: // Spout (left)
case 37430: // Spout (right)
{
float newAngle = target->GetOrientation();
if (auraId == 37429)
newAngle += 2 * M_PI_F / 100;
else
newAngle -= 2 * M_PI_F / 100;
newAngle = MapManager::NormalizeOrientation(newAngle);
target->SetFacingTo(newAngle);
target->CastSpell(target, 37433, true);
return;
}
// // Karazhan - Chess NPC AI, Snapshot timer
// case 37440: break;
// // Karazhan - Chess NPC AI, action timer
// case 37504: break;
// // Karazhan - Chess: Is Square OCCUPIED aura (DND)
// case 39400: break;
// // Banish
// case 37546: break;
// // Shriveling Gaze
// case 37589: break;
// // Fake Aggro Radius (2 yd)
// case 37815: break;
// // Corrupt Medivh
// case 37853: break;
case 38495: // Eye of Grillok
{
target->CastSpell(target, 38530, true);
return;
}
case 38554: // Absorb Eye of Grillok (Zezzak's Shard)
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 38495, true, NULL, this);
else
return;
Creature* creatureTarget = (Creature*)target;
creatureTarget->ForcedDespawn();
return;
}
// // Magic Sucker Device timer
// case 38672: break;
// // Tomb Guarding Charging
// case 38751: break;
// // Murmur's Touch
// case 38794: break;
case 39105: // Activate Nether-wraith Beacon (31742 Nether-wraith Beacon item)
{
float fX, fY, fZ;
triggerTarget->GetClosePoint(fX, fY, fZ, triggerTarget->GetObjectBoundingRadius(), 20.0f);
triggerTarget->SummonCreature(22408, fX, fY, fZ, triggerTarget->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
return;
}
// // Drain World Tree Visual
// case 39140: break;
// // Quest - Dustin's Undead Dragon Visual aura
// case 39259: break;
// // Hellfire - The Exorcism, Jules releases darkness, aura
// case 39306: break;
// // Inferno
// case 39346: break;
// // Enchanted Weapons
// case 39489: break;
// // Shadow Bolt Whirl
// case 39630: break;
// // Shadow Bolt Whirl
// case 39634: break;
// // Shadow Inferno
// case 39645: break;
case 39857: // Tear of Azzinoth Summon Channel - it's not really supposed to do anything,and this only prevents the console spam
trigger_spell_id = 39856;
break;
// // Soulgrinder Ritual Visual (Smashed)
// case 39974: break;
// // Simon Game Pre-game timer
// case 40041: break;
// // Knockdown Fel Cannon: The Aggro Check Aura
// case 40113: break;
// // Spirit Lance
// case 40157: break;
case 40398: // Demon Transform 2
switch (GetAuraTicks())
{
case 1:
if (target->HasAura(40506))
target->RemoveAurasDueToSpell(40506);
else
trigger_spell_id = 40506;
break;
case 2:
trigger_spell_id = 40510;
break;
}
break;
case 40511: // Demon Transform 1
trigger_spell_id = 40398;
break;
// // Ancient Flames
// case 40657: break;
// // Ethereal Ring Cannon: Cannon Aura
// case 40734: break;
// // Cage Trap
// case 40760: break;
// // Random Periodic
// case 40867: break;
// // Prismatic Shield
// case 40879: break;
// // Aura of Desire
// case 41350: break;
// // Dementia
// case 41404: break;
// // Chaos Form
// case 41629: break;
// // Alert Drums
// case 42177: break;
// // Spout
// case 42581: break;
// // Spout
// case 42582: break;
// // Return to the Spirit Realm
// case 44035: break;
// // Curse of Boundless Agony
// case 45050: break;
// // Earthquake
// case 46240: break;
case 46736: // Personalized Weather
trigger_spell_id = 46737;
break;
// // Stay Submerged
// case 46981: break;
// // Dragonblight Ram
// case 47015: break;
// // Party G.R.E.N.A.D.E.
// case 51510: break;
default:
break;
}
break;
}
case SPELLFAMILY_MAGE:
{
switch (auraId)
{
case 66: // Invisibility
// Here need periodic trigger reducing threat spell (or do it manually)
return;
default:
break;
}
break;
}
// case SPELLFAMILY_WARRIOR:
// {
// switch(auraId)
// {
// // Wild Magic
// case 23410: break;
// // Corrupted Totems
// case 23425: break;
// default:
// break;
// }
// break;
// }
// case SPELLFAMILY_PRIEST:
// {
// switch(auraId)
// {
// // Blue Beam
// case 32930: break;
// // Fury of the Dreghood Elders
// case 35460: break;
// default:
// break;
// }
// break;
// }
case SPELLFAMILY_DRUID:
{
switch (auraId)
{
case 768: // Cat Form
// trigger_spell_id not set and unknown effect triggered in this case, ignoring for while
return;
case 22842: // Frenzied Regeneration
case 22895:
case 22896:
case 26999:
{
int32 LifePerRage = GetModifier()->m_amount;
int32 lRage = target->GetPower(POWER_RAGE);
if (lRage > 100) // rage stored as rage*10
lRage = 100;
target->ModifyPower(POWER_RAGE, -lRage);
int32 FRTriggerBasePoints = int32(lRage * LifePerRage / 10);
target->CastCustomSpell(target, 22845, &FRTriggerBasePoints, NULL, NULL, true, NULL, this);
return;
}
default:
break;
}
break;
}
// case SPELLFAMILY_HUNTER:
// {
// switch(auraId)
// {
// // Frost Trap Aura
// case 13810:
// return;
// // Rizzle's Frost Trap
// case 39900:
// return;
// // Tame spells
// case 19597: // Tame Ice Claw Bear
// case 19676: // Tame Snow Leopard
// case 19677: // Tame Large Crag Boar
// case 19678: // Tame Adult Plainstrider
// case 19679: // Tame Prairie Stalker
// case 19680: // Tame Swoop
// case 19681: // Tame Dire Mottled Boar
// case 19682: // Tame Surf Crawler
// case 19683: // Tame Armored Scorpid
// case 19684: // Tame Webwood Lurker
// case 19685: // Tame Nightsaber Stalker
// case 19686: // Tame Strigid Screecher
// case 30100: // Tame Crazed Dragonhawk
// case 30103: // Tame Elder Springpaw
// case 30104: // Tame Mistbat
// case 30647: // Tame Barbed Crawler
// case 30648: // Tame Greater Timberstrider
// case 30652: // Tame Nightstalker
// return;
// default:
// break;
// }
// break;
// }
case SPELLFAMILY_SHAMAN:
{
switch (auraId)
{
case 28820: // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield)
{
// Need remove self if Lightning Shield not active
Unit::SpellAuraHolderMap const& auras = triggerTarget->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
SpellEntry const* spell = itr->second->GetSpellProto();
if (spell->SpellFamilyName == SPELLFAMILY_SHAMAN &&
(spell->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
return;
}
triggerTarget->RemoveAurasDueToSpell(28820);
return;
}
case 38443: // Totemic Mastery (Skyshatter Regalia (Shaman Tier 6) - bonus)
{
if (triggerTarget->IsAllTotemSlotsUsed())
triggerTarget->CastSpell(triggerTarget, 38437, true, NULL, this);
else
triggerTarget->RemoveAurasDueToSpell(38437);
return;
}
default:
break;
}
break;
}
default:
break;
}
// Reget trigger spell proto
triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id);
}
else // initial triggeredSpellInfo != NULL
{
// for channeled spell cast applied from aura owner to channel target (persistent aura affects already applied to true target)
// come periodic casts applied to targets, so need seelct proper caster (ex. 15790)
if (IsChanneledSpell(GetSpellProto()) && GetSpellProto()->Effect[GetEffIndex()] != SPELL_EFFECT_PERSISTENT_AREA_AURA)
{
// interesting 2 cases: periodic aura at caster of channeled spell
if (target->GetObjectGuid() == casterGUID)
{
triggerCaster = target;
if (WorldObject* channelTarget = target->GetMap()->GetWorldObject(target->GetChannelObjectGuid()))
{
if (channelTarget->isType(TYPEMASK_UNIT))
triggerTarget = (Unit*)channelTarget;
else
triggerTargetObject = channelTarget;
}
}
// or periodic aura at caster channel target
else if (Unit* caster = GetCaster())
{
if (target->GetObjectGuid() == caster->GetChannelObjectGuid())
{
triggerCaster = caster;
triggerTarget = target;
}
}
}
// Spell exist but require custom code
switch (auraId)
{
case 9347: // Mortal Strike
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// expected selection current fight target
triggerTarget = ((Creature*)target)->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, triggeredSpellInfo);
if (!triggerTarget)
return;
break;
}
case 1010: // Curse of Idiocy
{
// TODO: spell casted by result in correct way mostly
// BUT:
// 1) target show casting at each triggered cast: target don't must show casting animation for any triggered spell
// but must show affect apply like item casting
// 2) maybe aura must be replace by new with accumulative stat mods instead stacking
// prevent cast by triggered auras
if (casterGUID == triggerTarget->GetObjectGuid())
return;
// stop triggering after each affected stats lost > 90
int32 intelectLoss = 0;
int32 spiritLoss = 0;
Unit::AuraList const& mModStat = triggerTarget->GetAurasByType(SPELL_AURA_MOD_STAT);
for (Unit::AuraList::const_iterator i = mModStat.begin(); i != mModStat.end(); ++i)
{
if ((*i)->GetId() == 1010)
{
switch ((*i)->GetModifier()->m_miscvalue)
{
case STAT_INTELLECT: intelectLoss += (*i)->GetModifier()->m_amount; break;
case STAT_SPIRIT: spiritLoss += (*i)->GetModifier()->m_amount; break;
default: break;
}
}
}
if (intelectLoss <= -90 && spiritLoss <= -90)
return;
break;
}
case 16191: // Mana Tide
{
triggerTarget->CastCustomSpell(triggerTarget, trigger_spell_id, &m_modifier.m_amount, NULL, NULL, true, NULL, this);
return;
}
case 33525: // Ground Slam
triggerTarget->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this, casterGUID);
return;
case 38736: // Rod of Purification - for quest 10839 (Veil Skith: Darkstone of Terokk)
{
if (Unit* caster = GetCaster())
caster->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this);
return;
}
case 44883: // Encapsulate
{
// Self cast spell, hence overwrite caster (only channeled spell where the triggered spell deals dmg to SELF)
triggerCaster = triggerTarget;
break;
}
}
}
// All ok cast by default case
if (triggeredSpellInfo)
{
if (triggerTargetObject)
triggerCaster->CastSpell(triggerTargetObject->GetPositionX(), triggerTargetObject->GetPositionY(), triggerTargetObject->GetPositionZ(),
triggeredSpellInfo, true, NULL, this, casterGUID);
else
triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this, casterGUID);
}
else
{
if (Unit* caster = GetCaster())
{
if (triggerTarget->GetTypeId() != TYPEID_UNIT || !sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)triggerTarget))
sLog.outError("Aura::TriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", GetId(), GetEffIndex());
}
}
}
void Aura::TriggerSpellWithValue()
{
ObjectGuid casterGuid = GetCasterGuid();
Unit* target = GetTriggerTarget();
if (!casterGuid || !target)
return;
// generic casting code with custom spells and target/caster customs
uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex];
int32 basepoints0 = GetModifier()->m_amount;
target->CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, NULL, this, casterGuid);
}
/*********************************************************/
/*** AURA EFFECTS ***/
/*********************************************************/
void Aura::HandleAuraDummy(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// AT APPLY
if (apply)
{
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (GetId())
{
case 1515: // Tame beast
// FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness
if (target->CanHaveThreatList())
if (Unit* caster = GetCaster())
target->AddThreat(caster, 10.0f, false, GetSpellSchoolMask(GetSpellProto()), GetSpellProto());
return;
case 7057: // Haunting Spirits
// expected to tick with 30 sec period (tick part see in Aura::PeriodicTick)
m_isPeriodic = true;
m_modifier.periodictime = 30 * IN_MILLISECONDS;
m_periodicTimer = m_modifier.periodictime;
return;
case 10255: // Stoned
{
if (Unit* caster = GetCaster())
{
if (caster->GetTypeId() != TYPEID_UNIT)
return;
caster->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
caster->addUnitState(UNIT_STAT_ROOT);
}
return;
}
case 13139: // net-o-matic
// root to self part of (root_target->charge->root_self sequence
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 13138, true, NULL, this);
return;
case 28832: // Mark of Korth'azz
case 28833: // Mark of Blaumeux
case 28834: // Mark of Rivendare
case 28835: // Mark of Zeliek
{
int32 damage = 0;
switch (GetStackAmount())
{
case 1:
return;
case 2: damage = 500; break;
case 3: damage = 1500; break;
case 4: damage = 4000; break;
case 5: damage = 12500; break;
default:
damage = 14000 + 1000 * GetStackAmount();
break;
}
if (Unit* caster = GetCaster())
caster->CastCustomSpell(target, 28836, &damage, NULL, NULL, true, NULL, this);
return;
}
case 31606: // Stormcrow Amulet
{
CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(17970);
// we must assume db or script set display id to native at ending flight (if not, target is stuck with this model)
if (cInfo)
target->SetDisplayId(Creature::ChooseDisplayId(cInfo));
return;
}
case 32045: // Soul Charge
case 32051:
case 32052:
{
// max duration is 2 minutes, but expected to be random duration
// real time randomness is unclear, using max 30 seconds here
// see further down for expire of this aura
GetHolder()->SetAuraDuration(urand(1, 30)*IN_MILLISECONDS);
return;
}
case 33326: // Stolen Soul Dispel
{
target->RemoveAurasDueToSpell(32346);
return;
}
case 36587: // Vision Guide
{
target->CastSpell(target, 36573, true, NULL, this);
return;
}
// Gender spells
case 38224: // Illidari Agent Illusion
case 37096: // Blood Elf Illusion
case 46354: // Blood Elf Illusion
{
uint8 gender = target->getGender();
uint32 spellId;
switch (GetId())
{
case 38224: spellId = (gender == GENDER_MALE ? 38225 : 38227); break;
case 37096: spellId = (gender == GENDER_MALE ? 37092 : 37094); break;
case 46354: spellId = (gender == GENDER_MALE ? 46355 : 46356); break;
default: return;
}
target->CastSpell(target, spellId, true, NULL, this);
return;
}
case 39850: // Rocket Blast
if (roll_chance_i(20)) // backfire stun
target->CastSpell(target, 51581, true, NULL, this);
return;
case 43873: // Headless Horseman Laugh
target->PlayDistanceSound(11965);
return;
case 46699: // Requires No Ammo
if (target->GetTypeId() == TYPEID_PLAYER)
// not use ammo and not allow use
((Player*)target)->RemoveAmmo();
return;
case 48025: // Headless Horseman's Mount
Spell::SelectMountByAreaAndSkill(target, GetSpellProto(), 51621, 48024, 51617, 48023, 0);
return;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (GetId())
{
case 41099: // Battle Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Battle Aura
target->CastSpell(target, 41106, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
case 41100: // Berserker Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Berserker Aura
target->CastSpell(target, 41107, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
case 41101: // Defensive Stance
{
if (target->GetTypeId() != TYPEID_UNIT)
return;
// Stance Cooldown
target->CastSpell(target, 41102, true, NULL, this);
// Defensive Aura
target->CastSpell(target, 41105, true, NULL, this);
// equipment
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32604);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 31467);
((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0);
return;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
// Earth Shield
if ((GetSpellProto()->SpellFamilyFlags & UI64LIT(0x40000000000)))
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
if (Unit* caster = GetCaster())
{
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
}
}
return;
}
break;
}
}
}
// AT REMOVE
else
{
if (IsQuestTameSpell(GetId()) && target->isAlive())
{
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
uint32 finalSpellId = 0;
switch (GetId())
{
case 19548: finalSpellId = 19597; break;
case 19674: finalSpellId = 19677; break;
case 19687: finalSpellId = 19676; break;
case 19688: finalSpellId = 19678; break;
case 19689: finalSpellId = 19679; break;
case 19692: finalSpellId = 19680; break;
case 19693: finalSpellId = 19684; break;
case 19694: finalSpellId = 19681; break;
case 19696: finalSpellId = 19682; break;
case 19697: finalSpellId = 19683; break;
case 19699: finalSpellId = 19685; break;
case 19700: finalSpellId = 19686; break;
case 30646: finalSpellId = 30647; break;
case 30653: finalSpellId = 30648; break;
case 30654: finalSpellId = 30652; break;
case 30099: finalSpellId = 30100; break;
case 30102: finalSpellId = 30103; break;
case 30105: finalSpellId = 30104; break;
}
if (finalSpellId)
caster->CastSpell(target, finalSpellId, true, NULL, this);
return;
}
switch (GetId())
{
case 10255: // Stoned
{
if (Unit* caster = GetCaster())
{
if (caster->GetTypeId() != TYPEID_UNIT)
return;
// see dummy effect of spell 10254 for removal of flags etc
caster->CastSpell(caster, 10254, true);
}
return;
}
case 12479: // Hex of Jammal'an
target->CastSpell(target, 12480, true, NULL, this);
return;
case 12774: // (DND) Belnistrasz Idol Shutdown Visual
{
if (m_removeMode == AURA_REMOVE_BY_DEATH)
return;
// Idom Rool Camera Shake <- wtf, don't drink while making spellnames?
if (Unit* caster = GetCaster())
caster->CastSpell(caster, 12816, true);
return;
}
case 28169: // Mutating Injection
{
// Mutagen Explosion
target->CastSpell(target, 28206, true, NULL, this);
// Poison Cloud
target->CastSpell(target, 28240, true, NULL, this);
return;
}
case 32045: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32054, true, NULL, this);
return;
}
case 32051: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32057, true, NULL, this);
return;
}
case 32052: // Soul Charge
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32053, true, NULL, this);
return;
}
case 32286: // Focus Target Visual
{
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32301, true, NULL, this);
return;
}
case 35079: // Misdirection, triggered buff
{
if (Unit* pCaster = GetCaster())
pCaster->RemoveAurasDueToSpell(34477);
return;
}
case 36730: // Flame Strike
{
target->CastSpell(target, 36731, true, NULL, this);
return;
}
case 41099: // Battle Stance
{
// Battle Aura
target->RemoveAurasDueToSpell(41106);
return;
}
case 41100: // Berserker Stance
{
// Berserker Aura
target->RemoveAurasDueToSpell(41107);
return;
}
case 41101: // Defensive Stance
{
// Defensive Aura
target->RemoveAurasDueToSpell(41105);
return;
}
case 42385: // Alcaz Survey Aura
{
target->CastSpell(target, 42316, true, NULL, this);
return;
}
case 42454: // Captured Totem
{
if (m_removeMode == AURA_REMOVE_BY_DEFAULT)
{
if (target->getDeathState() != CORPSE)
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// Captured Totem Test Credit
if (Player* pPlayer = pCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
pPlayer->CastSpell(pPlayer, 42455, true);
}
return;
}
case 42517: // Beam to Zelfrax
{
// expecting target to be a dummy creature
Creature* pSummon = target->SummonCreature(23864, 0.0f, 0.0f, 0.0f, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0);
Unit* pCaster = GetCaster();
if (pSummon && pCaster)
pSummon->GetMotionMaster()->MovePoint(0, pCaster->GetPositionX(), pCaster->GetPositionY(), pCaster->GetPositionZ());
return;
}
case 44191: // Flame Strike
{
if (target->GetMap()->IsDungeon())
{
uint32 spellId = target->GetMap()->IsRegularDifficulty() ? 44190 : 46163;
target->CastSpell(target, spellId, true, NULL, this);
}
return;
}
case 45934: // Dark Fiend
{
// Kill target if dispelled
if (m_removeMode == AURA_REMOVE_BY_DISPEL)
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
return;
}
case 46308: // Burning Winds
{
// casted only at creatures at spawn
target->CastSpell(target, 47287, true, NULL, this);
return;
}
}
}
// AT APPLY & REMOVE
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (GetId())
{
case 6606: // Self Visual - Sleep Until Cancelled (DND)
{
if (apply)
{
target->SetStandState(UNIT_STAND_STATE_SLEEP);
target->addUnitState(UNIT_STAT_ROOT);
}
else
{
target->clearUnitState(UNIT_STAT_ROOT);
target->SetStandState(UNIT_STAND_STATE_STAND);
}
return;
}
case 24658: // Unstable Power
{
if (apply)
{
Unit* caster = GetCaster();
if (!caster)
return;
caster->CastSpell(target, 24659, true, NULL, NULL, GetCasterGuid());
}
else
target->RemoveAurasDueToSpell(24659);
return;
}
case 24661: // Restless Strength
{
if (apply)
{
Unit* caster = GetCaster();
if (!caster)
return;
caster->CastSpell(target, 24662, true, NULL, NULL, GetCasterGuid());
}
else
target->RemoveAurasDueToSpell(24662);
return;
}
case 29266: // Permanent Feign Death
case 31261: // Permanent Feign Death (Root)
case 37493: // Feign Death
{
// Unclear what the difference really is between them.
// Some has effect1 that makes the difference, however not all.
// Some appear to be used depending on creature location, in water, at solid ground, in air/suspended, etc
// For now, just handle all the same way
if (target->GetTypeId() == TYPEID_UNIT)
target->SetFeignDeath(apply);
return;
}
case 32216: // Victorious
if (target->getClass() == CLASS_WARRIOR)
target->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, apply);
return;
case 35356: // Spawn Feign Death
case 35357: // Spawn Feign Death
{
if (target->GetTypeId() == TYPEID_UNIT)
{
// Flags not set like it's done in SetFeignDeath()
// UNIT_DYNFLAG_DEAD does not appear with these spells.
// All of the spells appear to be present at spawn and not used to feign in combat or similar.
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
target->addUnitState(UNIT_STAT_DIED);
}
else
{
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
target->clearUnitState(UNIT_STAT_DIED);
}
}
return;
}
case 40133: // Summon Fire Elemental
{
Unit* caster = GetCaster();
if (!caster)
return;
Unit* owner = caster->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
owner->CastSpell(owner, 8985, true);
else
((Player*)owner)->RemovePet(PET_SAVE_REAGENTS);
}
return;
}
case 40132: // Summon Earth Elemental
{
Unit* caster = GetCaster();
if (!caster)
return;
Unit* owner = caster->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
owner->CastSpell(owner, 19704, true);
else
((Player*)owner)->RemovePet(PET_SAVE_REAGENTS);
}
return;
}
case 40214: // Dragonmaw Illusion
{
if (apply)
{
target->CastSpell(target, 40216, true);
target->CastSpell(target, 42016, true);
}
else
{
target->RemoveAurasDueToSpell(40216);
target->RemoveAurasDueToSpell(42016);
}
return;
}
case 42515: // Jarl Beam
{
// aura animate dead (fainted) state for the duration, but we need to animate the death itself (correct way below?)
if (Unit* pCaster = GetCaster())
pCaster->ApplyModFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH, apply);
// Beam to Zelfrax at remove
if (!apply)
target->CastSpell(target, 42517, true);
return;
}
case 27978:
case 40131:
if (apply)
target->m_AuraFlags |= UNIT_AURAFLAG_ALIVE_INVISIBLE;
else
target->m_AuraFlags |= ~UNIT_AURAFLAG_ALIVE_INVISIBLE;
return;
}
break;
}
case SPELLFAMILY_MAGE:
{
// Hypothermia
if (GetId() == 41425)
{
target->ModifyAuraState(AURA_STATE_HYPOTHERMIA, apply);
return;
}
break;
}
case SPELLFAMILY_DRUID:
{
switch (GetId())
{
case 34246: // Idol of the Emerald Queen
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
// dummy not have proper effectclassmask
m_spellmod = new SpellModifier(SPELLMOD_DOT, SPELLMOD_FLAT, m_modifier.m_amount / 7, GetId(), UI64LIT(0x001000000000));
((Player*)target)->AddSpellMod(m_spellmod, apply);
return;
}
}
// Lifebloom
if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x1000000000))
{
if (apply)
{
if (Unit* caster = GetCaster())
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
// Lifebloom ignore stack amount
m_modifier.m_amount /= GetStackAmount();
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
m_modifier.m_amount = target->SpellHealingBonusTaken(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE);
}
}
}
else
{
// Final heal on duration end
if (m_removeMode != AURA_REMOVE_BY_EXPIRE)
return;
// final heal
if (target->IsInWorld() && GetStackAmount() > 0)
{
// Lifebloom dummy store single stack amount always
int32 amount = m_modifier.m_amount;
target->CastCustomSpell(target, 33778, &amount, NULL, NULL, true, NULL, this, GetCasterGuid());
}
}
return;
}
// Predatory Strikes
if (target->GetTypeId() == TYPEID_PLAYER && GetSpellProto()->SpellIconID == 1563)
{
((Player*)target)->UpdateAttackPowerAndDamage();
return;
}
break;
}
case SPELLFAMILY_ROGUE:
break;
case SPELLFAMILY_HUNTER:
{
switch (GetId())
{
// Improved Aspect of the Viper
case 38390:
{
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
// + effect value for Aspect of the Viper
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_FLAT, m_modifier.m_amount, GetId(), UI64LIT(0x4000000000000));
((Player*)target)->AddSpellMod(m_spellmod, apply);
}
return;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (GetId())
{
case 6495: // Sentry Totem
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
Totem* totem = target->GetTotem(TOTEM_SLOT_AIR);
if (totem && apply)
((Player*)target)->GetCamera().SetView(totem);
else
((Player*)target)->GetCamera().ResetView();
return;
}
}
// Improved Weapon Totems
if (GetSpellProto()->SpellIconID == 57 && target->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
{
switch (m_effIndex)
{
case 0:
// Windfury Totem
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00200000000));
break;
case 1:
// Flametongue Totem
m_spellmod = new SpellModifier(SPELLMOD_EFFECT1, SPELLMOD_PCT, m_modifier.m_amount, GetId(), UI64LIT(0x00400000000));
break;
default: return;
}
}
((Player*)target)->AddSpellMod(m_spellmod, apply);
return;
}
break;
}
}
// pet auras
if (PetAura const* petSpell = sSpellMgr.GetPetAura(GetId()))
{
if (apply)
target->AddPetAura(petSpell);
else
target->RemovePetAura(petSpell);
return;
}
if (GetEffIndex() == EFFECT_INDEX_0 && target->GetTypeId() == TYPEID_PLAYER)
{
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAuraMapBounds(GetId());
if (saBounds.first != saBounds.second)
{
uint32 zone, area;
target->GetZoneAndAreaId(zone, area);
for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
{
// some auras remove at aura remove
if (!itr->second->IsFitToRequirements((Player*)target, zone, area))
target->RemoveAurasDueToSpell(itr->second->spellId);
// some auras applied at aura apply
else if (itr->second->autocast)
{
if (!target->HasAura(itr->second->spellId, EFFECT_INDEX_0))
target->CastSpell(target, itr->second->spellId, true);
}
}
}
}
// script has to "handle with care", only use where data are not ok to use in the above code.
if (target->GetTypeId() == TYPEID_UNIT)
sScriptMgr.OnAuraDummy(this, apply);
}
void Aura::HandleAuraMounted(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue);
if (!ci)
{
sLog.outErrorDb("AuraMounted: `creature_template`='%u' not found in database (only need it modelid)", m_modifier.m_miscvalue);
return;
}
uint32 display_id = Creature::ChooseDisplayId(ci);
CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
if (minfo)
display_id = minfo->modelid;
target->Mount(display_id, GetId());
}
else
{
target->Unmount(true);
}
}
void Aura::HandleAuraWaterWalk(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
GetTarget()->SetWaterWalk(apply);
}
void Aura::HandleAuraFeatherFall(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_FEATHER_FALL, 8 + 4);
else
data.Initialize(SMSG_MOVE_NORMAL_FALL, 8 + 4);
data << target->GetPackGUID();
data << uint32(0);
target->SendMessageToSet(&data, true);
// start fall from current height
if (!apply && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->SetFallInformation(0, target->GetPositionZ());
}
void Aura::HandleAuraHover(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_HOVER, 8 + 4);
else
data.Initialize(SMSG_MOVE_UNSET_HOVER, 8 + 4);
data << GetTarget()->GetPackGUID();
data << uint32(0);
GetTarget()->SendMessageToSet(&data, true);
}
void Aura::HandleWaterBreathing(bool /*apply*/, bool /*Real*/)
{
// update timers in client
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->UpdateMirrorTimers();
}
void Aura::HandleAuraModShapeshift(bool apply, bool Real)
{
if (!Real)
return;
ShapeshiftForm form = ShapeshiftForm(m_modifier.m_miscvalue);
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (!ssEntry)
{
sLog.outError("Unknown shapeshift form %u in spell %u", form, GetId());
return;
}
uint32 modelid = 0;
Powers PowerType = POWER_MANA;
Unit* target = GetTarget();
if (ssEntry->modelID_A)
{
// i will asume that creatures will always take the defined model from the dbc
// since no field in creature_templates describes wether an alliance or
// horde modelid should be used at shapeshifting
if (target->GetTypeId() != TYPEID_PLAYER)
modelid = ssEntry->modelID_A;
else
{
// players are a bit different since the dbc has seldomly an horde modelid
if (Player::TeamForRace(target->getRace()) == HORDE)
{
// get model for race ( in 2.2.4 no horde models in dbc field, only 0 in it
modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, target->getRaceMask());
}
// nothing found in above, so use default
if (!modelid)
modelid = ssEntry->modelID_A;
}
}
// remove polymorph before changing display id to keep new display id
switch (form)
{
case FORM_CAT:
case FORM_TREE:
case FORM_TRAVEL:
case FORM_AQUA:
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_FLIGHT_EPIC:
case FORM_FLIGHT:
case FORM_MOONKIN:
{
// remove movement affects
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT, GetHolder());
Unit::AuraList const& slowingAuras = target->GetAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
for (Unit::AuraList::const_iterator iter = slowingAuras.begin(); iter != slowingAuras.end();)
{
SpellEntry const* aurSpellInfo = (*iter)->GetSpellProto();
uint32 aurMechMask = GetAllSpellMechanicMask(aurSpellInfo);
// If spell that caused this aura has Croud Control or Daze effect
if ((aurMechMask & MECHANIC_NOT_REMOVED_BY_SHAPESHIFT) ||
// some Daze spells have these parameters instead of MECHANIC_DAZE (skip snare spells)
(aurSpellInfo->SpellIconID == 15 && aurSpellInfo->Dispel == 0 &&
(aurMechMask & (1 << (MECHANIC_SNARE - 1))) == 0))
{
++iter;
continue;
}
// All OK, remove aura now
target->RemoveAurasDueToSpellByCancel(aurSpellInfo->Id);
iter = slowingAuras.begin();
}
// and polymorphic affects
if (target->IsPolymorphed())
target->RemoveAurasDueToSpell(target->getTransForm());
break;
}
default:
break;
}
if (apply)
{
// remove other shapeshift before applying a new one
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT, GetHolder());
if (modelid > 0)
target->SetDisplayId(modelid);
// now only powertype must be set
switch (form)
{
case FORM_CAT:
PowerType = POWER_ENERGY;
break;
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_BATTLESTANCE:
case FORM_BERSERKERSTANCE:
case FORM_DEFENSIVESTANCE:
PowerType = POWER_RAGE;
break;
default:
break;
}
if (PowerType != POWER_MANA)
{
// reset power to default values only at power change
if (target->getPowerType() != PowerType)
target->setPowerType(PowerType);
switch (form)
{
case FORM_CAT:
case FORM_BEAR:
case FORM_DIREBEAR:
{
// get furor proc chance
int32 furorChance = 0;
Unit::AuraList const& mDummy = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummy.begin(); i != mDummy.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 238)
{
furorChance = (*i)->GetModifier()->m_amount;
break;
}
}
if (m_modifier.m_miscvalue == FORM_CAT)
{
target->SetPower(POWER_ENERGY, 0);
if (irand(1, 100) <= furorChance)
target->CastSpell(target, 17099, true, NULL, this);
}
else
{
target->SetPower(POWER_RAGE, 0);
if (irand(1, 100) <= furorChance)
target->CastSpell(target, 17057, true, NULL, this);
}
break;
}
case FORM_BATTLESTANCE:
case FORM_DEFENSIVESTANCE:
case FORM_BERSERKERSTANCE:
{
uint32 Rage_val = 0;
// Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch)
if (target->GetTypeId() == TYPEID_PLAYER)
{
PlayerSpellMap const& sp_list = ((Player*)target)->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139)
Rage_val += target->CalculateSpellDamage(target, spellInfo, EFFECT_INDEX_0) * 10;
}
}
if (target->GetPower(POWER_RAGE) > Rage_val)
target->SetPower(POWER_RAGE, Rage_val);
break;
}
default:
break;
}
}
target->SetShapeshiftForm(form);
// a form can give the player a new castbar with some spells.. this is a clientside process..
// serverside just needs to register the new spells so that player isn't kicked as cheater
if (target->GetTypeId() == TYPEID_PLAYER)
for (uint32 i = 0; i < 8; ++i)
if (ssEntry->spellId[i])
((Player*)target)->addSpell(ssEntry->spellId[i], true, false, false, false);
}
else
{
if (modelid > 0)
target->SetDisplayId(target->GetNativeDisplayId());
if (target->getClass() == CLASS_DRUID)
target->setPowerType(POWER_MANA);
target->SetShapeshiftForm(FORM_NONE);
switch (form)
{
// Nordrassil Harness - bonus
case FORM_BEAR:
case FORM_DIREBEAR:
case FORM_CAT:
if (Aura* dummy = target->GetDummyAura(37315))
target->CastSpell(target, 37316, true, NULL, dummy);
break;
// Nordrassil Regalia - bonus
case FORM_MOONKIN:
if (Aura* dummy = target->GetDummyAura(37324))
target->CastSpell(target, 37325, true, NULL, dummy);
break;
default:
break;
}
// look at the comment in apply-part
if (target->GetTypeId() == TYPEID_PLAYER)
for (uint32 i = 0; i < 8; ++i)
if (ssEntry->spellId[i])
((Player*)target)->removeSpell(ssEntry->spellId[i], false, false, false);
}
// adding/removing linked auras
// add/remove the shapeshift aura's boosts
HandleShapeshiftBoosts(apply);
if (target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->InitDataForForm();
}
void Aura::HandleAuraTransform(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
// special case (spell specific functionality)
if (m_modifier.m_miscvalue == 0)
{
switch (GetId())
{
case 16739: // Orb of Deception
{
uint32 orb_model = target->GetNativeDisplayId();
switch (orb_model)
{
// Troll Female
case 1479: target->SetDisplayId(10134); break;
// Troll Male
case 1478: target->SetDisplayId(10135); break;
// Tauren Male
case 59: target->SetDisplayId(10136); break;
// Human Male
case 49: target->SetDisplayId(10137); break;
// Human Female
case 50: target->SetDisplayId(10138); break;
// Orc Male
case 51: target->SetDisplayId(10139); break;
// Orc Female
case 52: target->SetDisplayId(10140); break;
// Dwarf Male
case 53: target->SetDisplayId(10141); break;
// Dwarf Female
case 54: target->SetDisplayId(10142); break;
// NightElf Male
case 55: target->SetDisplayId(10143); break;
// NightElf Female
case 56: target->SetDisplayId(10144); break;
// Undead Female
case 58: target->SetDisplayId(10145); break;
// Undead Male
case 57: target->SetDisplayId(10146); break;
// Tauren Female
case 60: target->SetDisplayId(10147); break;
// Gnome Male
case 1563: target->SetDisplayId(10148); break;
// Gnome Female
case 1564: target->SetDisplayId(10149); break;
// BloodElf Female
case 15475: target->SetDisplayId(17830); break;
// BloodElf Male
case 15476: target->SetDisplayId(17829); break;
// Dranei Female
case 16126: target->SetDisplayId(17828); break;
// Dranei Male
case 16125: target->SetDisplayId(17827); break;
default: break;
}
break;
}
case 42365: // Murloc costume
target->SetDisplayId(21723);
break;
// case 44186: // Gossip NPC Appearance - All, Brewfest
// break;
// case 48305: // Gossip NPC Appearance - All, Spirit of Competition
// break;
case 50517: // Dread Corsair
case 51926: // Corsair Costume
{
// expected for players
uint32 race = target->getRace();
switch (race)
{
case RACE_HUMAN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048);
break;
case RACE_ORC:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050);
break;
case RACE_DWARF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045);
break;
case RACE_NIGHTELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049);
break;
case RACE_UNDEAD:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053);
break;
case RACE_TAUREN:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051);
break;
case RACE_GNOME:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046);
break;
case RACE_TROLL:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052);
break;
case RACE_GOBLIN: // not really player race (3.x), but model exist
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25036 : 25047);
break;
case RACE_BLOODELF:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043);
break;
case RACE_DRAENEI:
target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044);
break;
}
break;
}
// case 50531: // Gossip NPC Appearance - All, Pirate Day
// break;
// case 51010: // Dire Brew
// break;
default:
sLog.outError("Aura::HandleAuraTransform, spell %u does not have creature entry defined, need custom defined model.", GetId());
break;
}
}
else // m_modifier.m_miscvalue != 0
{
uint32 model_id;
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue);
if (!ci)
{
model_id = 16358; // pig pink ^_^
sLog.outError("Auras: unknown creature id = %d (only need its modelid) Form Spell Aura Transform in Spell ID = %d", m_modifier.m_miscvalue, GetId());
}
else
model_id = Creature::ChooseDisplayId(ci); // Will use the default model here
target->SetDisplayId(model_id);
// creature case, need to update equipment if additional provided
if (ci && target->GetTypeId() == TYPEID_UNIT)
((Creature*)target)->LoadEquipment(ci->equipmentId, false);
// Dragonmaw Illusion (set mount model also)
if (GetId() == 42016 && target->GetMountID() && !target->GetAurasByType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED).empty())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
// update active transform spell only not set or not overwriting negative by positive case
if (!target->getTransForm() || !IsPositiveSpell(GetId()) || IsPositiveSpell(target->getTransForm()))
target->setTransForm(GetId());
// polymorph case
if (Real && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed())
{
// for players, start regeneration after 1s (in polymorph fast regeneration case)
// only if caster is Player (after patch 2.4.2)
if (GetCasterGuid().IsPlayer())
((Player*)target)->setRegenTimer(1 * IN_MILLISECONDS);
// dismount polymorphed target (after patch 2.4.2)
if (target->IsMounted())
target->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED, GetHolder());
}
}
else // !apply
{
// ApplyModifier(true) will reapply it if need
target->setTransForm(0);
target->SetDisplayId(target->GetNativeDisplayId());
// apply default equipment for creature case
if (target->GetTypeId() == TYPEID_UNIT)
((Creature*)target)->LoadEquipment(((Creature*)target)->GetCreatureInfo()->equipmentId, true);
// re-apply some from still active with preference negative cases
Unit::AuraList const& otherTransforms = target->GetAurasByType(SPELL_AURA_TRANSFORM);
if (!otherTransforms.empty())
{
// look for other transform auras
Aura* handledAura = *otherTransforms.begin();
for (Unit::AuraList::const_iterator i = otherTransforms.begin(); i != otherTransforms.end(); ++i)
{
// negative auras are preferred
if (!IsPositiveSpell((*i)->GetSpellProto()->Id))
{
handledAura = *i;
break;
}
}
handledAura->ApplyModifier(true);
}
// Dragonmaw Illusion (restore mount model)
if (GetId() == 42016 && target->GetMountID() == 16314)
{
if (!target->GetAurasByType(SPELL_AURA_MOUNTED).empty())
{
uint32 cr_id = target->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetModifier()->m_miscvalue;
if (CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(cr_id))
{
uint32 display_id = Creature::ChooseDisplayId(ci);
CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id);
if (minfo)
display_id = minfo->modelid;
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, display_id);
}
}
}
}
}
void Aura::HandleForceReaction(bool apply, bool Real)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (!Real)
return;
Player* player = (Player*)GetTarget();
uint32 faction_id = m_modifier.m_miscvalue;
ReputationRank faction_rank = ReputationRank(m_modifier.m_amount);
player->GetReputationMgr().ApplyForceReaction(faction_id, faction_rank, apply);
player->GetReputationMgr().SendForceReactions();
// stop fighting if at apply forced rank friendly or at remove real rank friendly
if ((apply && faction_rank >= REP_FRIENDLY) || (!apply && player->GetReputationRank(faction_id) >= REP_FRIENDLY))
player->StopAttackFaction(faction_id);
}
void Aura::HandleAuraModSkill(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
uint32 prot = GetSpellProto()->EffectMiscValue[m_effIndex];
int32 points = GetModifier()->m_amount;
((Player*)GetTarget())->ModifySkillBonus(prot, (apply ? points : -points), m_modifier.m_auraname == SPELL_AURA_MOD_SKILL_TALENT);
if (prot == SKILL_DEFENSE)
((Player*)GetTarget())->UpdateDefenseBonusesMod();
}
void Aura::HandleChannelDeathItem(bool apply, bool Real)
{
if (Real && !apply)
{
if (m_removeMode != AURA_REMOVE_BY_DEATH)
return;
// Item amount
if (m_modifier.m_amount <= 0)
return;
SpellEntry const* spellInfo = GetSpellProto();
if (spellInfo->EffectItemType[m_effIndex] == 0)
return;
Unit* victim = GetTarget();
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
// Soul Shard (target req.)
if (spellInfo->EffectItemType[m_effIndex] == 6265)
{
// Only from non-grey units
if (!((Player*)caster)->isHonorOrXPTarget(victim) ||
(victim->GetTypeId() == TYPEID_UNIT && !((Player*)caster)->isAllowedToLoot((Creature*)victim)))
return;
}
// Adding items
uint32 noSpaceForCount = 0;
uint32 count = m_modifier.m_amount;
ItemPosCountVec dest;
InventoryResult msg = ((Player*)caster)->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->EffectItemType[m_effIndex], count, &noSpaceForCount);
if (msg != EQUIP_ERR_OK)
{
count -= noSpaceForCount;
((Player*)caster)->SendEquipError(msg, NULL, NULL, spellInfo->EffectItemType[m_effIndex]);
if (count == 0)
return;
}
Item* newitem = ((Player*)caster)->StoreNewItem(dest, spellInfo->EffectItemType[m_effIndex], true);
((Player*)caster)->SendNewItem(newitem, count, true, true);
}
}
void Aura::HandleBindSight(bool apply, bool /*Real*/)
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Camera& camera = ((Player*)caster)->GetCamera();
if (apply)
camera.SetView(GetTarget());
else
camera.ResetView();
}
void Aura::HandleFarSight(bool apply, bool /*Real*/)
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Camera& camera = ((Player*)caster)->GetCamera();
if (apply)
camera.SetView(GetTarget());
else
camera.ResetView();
}
void Aura::HandleAuraTrackCreatures(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
if (apply)
GetTarget()->SetFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1));
else
GetTarget()->RemoveFlag(PLAYER_TRACK_CREATURES, uint32(1) << (m_modifier.m_miscvalue - 1));
}
void Aura::HandleAuraTrackResources(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
if (apply)
GetTarget()->SetFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1));
else
GetTarget()->RemoveFlag(PLAYER_TRACK_RESOURCES, uint32(1) << (m_modifier.m_miscvalue - 1));
}
void Aura::HandleAuraTrackStealthed(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
GetTarget()->RemoveNoStackAurasDueToAuraHolder(GetHolder());
GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply);
}
void Aura::HandleAuraModScale(bool apply, bool /*Real*/)
{
GetTarget()->ApplyPercentModFloatValue(OBJECT_FIELD_SCALE_X, float(m_modifier.m_amount), apply);
GetTarget()->UpdateModelData();
}
void Aura::HandleModPossess(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
// not possess yourself
if (GetCasterGuid() == target->GetObjectGuid())
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* p_caster = (Player*)caster;
Camera& camera = p_caster->GetCamera();
if (apply)
{
target->addUnitState(UNIT_STAT_CONTROLLED);
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
target->SetCharmerGuid(p_caster->GetObjectGuid());
target->setFaction(p_caster->getFaction());
// target should became visible at SetView call(if not visible before):
// otherwise client\p_caster will ignore packets from the target(SetClientControl for example)
camera.SetView(target);
p_caster->SetCharm(target);
p_caster->SetClientControl(target, 1);
p_caster->SetMover(target);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (CharmInfo* charmInfo = target->InitCharmInfo(target))
{
charmInfo->InitPossessCreateSpells();
charmInfo->SetReactState(REACT_PASSIVE);
charmInfo->SetCommandState(COMMAND_STAY);
}
p_caster->PossessSpellInitialize();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
}
else if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->SetClientControl(target, 0);
}
}
else
{
p_caster->SetCharm(NULL);
p_caster->SetClientControl(target, 0);
p_caster->SetMover(NULL);
// there is a possibility that target became invisible for client\p_caster at ResetView call:
// it must be called after movement control unapplying, not before! the reason is same as at aura applying
camera.ResetView();
p_caster->RemovePetActionBar();
// on delete only do caster related effects
if (m_removeMode == AURA_REMOVE_BY_DELETE)
return;
target->clearUnitState(UNIT_STAT_CONTROLLED);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
target->SetCharmerGuid(ObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->setFactionForRace(target->getRace());
((Player*)target)->SetClientControl(target, 1);
}
else if (target->GetTypeId() == TYPEID_UNIT)
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
target->setFaction(cinfo->faction_A);
}
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
target->AttackedBy(caster);
}
}
}
void Aura::HandleModPossessPet(bool apply, bool Real)
{
if (!Real)
return;
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
Unit* target = GetTarget();
if (target->GetTypeId() != TYPEID_UNIT || !((Creature*)target)->IsPet())
return;
Pet* pet = (Pet*)target;
Player* p_caster = (Player*)caster;
Camera& camera = p_caster->GetCamera();
if (apply)
{
pet->addUnitState(UNIT_STAT_CONTROLLED);
// target should became visible at SetView call(if not visible before):
// otherwise client\p_caster will ignore packets from the target(SetClientControl for example)
camera.SetView(pet);
p_caster->SetCharm(pet);
p_caster->SetClientControl(pet, 1);
((Player*)caster)->SetMover(pet);
pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
pet->StopMoving();
pet->GetMotionMaster()->Clear(false);
pet->GetMotionMaster()->MoveIdle();
}
else
{
p_caster->SetCharm(NULL);
p_caster->SetClientControl(pet, 0);
p_caster->SetMover(NULL);
// there is a possibility that target became invisible for client\p_caster at ResetView call:
// it must be called after movement control unapplying, not before! the reason is same as at aura applying
camera.ResetView();
// on delete only do caster related effects
if (m_removeMode == AURA_REMOVE_BY_DELETE)
return;
pet->clearUnitState(UNIT_STAT_CONTROLLED);
pet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
pet->AttackStop();
// out of range pet dismissed
if (!pet->IsWithinDistInMap(p_caster, pet->GetMap()->GetVisibilityDistance()))
{
p_caster->RemovePet(PET_SAVE_REAGENTS);
}
else
{
pet->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
}
}
}
void Aura::HandleModCharm(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
// not charm yourself
if (GetCasterGuid() == target->GetObjectGuid())
return;
Unit* caster = GetCaster();
if (!caster)
return;
if (apply)
{
// is it really need after spell check checks?
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM, GetHolder());
target->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS, GetHolder());
target->SetCharmerGuid(GetCasterGuid());
target->setFaction(caster->getFaction());
target->CastStop(target == caster ? GetId() : 0);
caster->SetCharm(target);
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
CharmInfo* charmInfo = target->InitCharmInfo(target);
charmInfo->InitCharmCreateSpells();
charmInfo->SetReactState(REACT_DEFENSIVE);
if (caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK)
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
// creature with pet number expected have class set
if (target->GetByteValue(UNIT_FIELD_BYTES_0, 1) == 0)
{
if (cinfo->unit_class == 0)
sLog.outErrorDb("Creature (Entry: %u) have unit_class = 0 but used in charmed spell, that will be result client crash.", cinfo->Entry);
else
sLog.outError("Creature (Entry: %u) have unit_class = %u but at charming have class 0!!! that will be result client crash.", cinfo->Entry, cinfo->unit_class);
target->SetByteValue(UNIT_FIELD_BYTES_0, 1, CLASS_MAGE);
}
// just to enable stat window
charmInfo->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
// if charmed two demons the same session, the 2nd gets the 1st one's name
target->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL)));
}
}
}
if (caster->GetTypeId() == TYPEID_PLAYER)
((Player*)caster)->CharmSpellInitialize();
}
else
{
target->SetCharmerGuid(ObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->setFactionForRace(target->getRace());
else
{
CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo();
// restore faction
if (((Creature*)target)->IsPet())
{
if (Unit* owner = target->GetOwner())
target->setFaction(owner->getFaction());
else if (cinfo)
target->setFaction(cinfo->faction_A);
}
else if (cinfo) // normal creature
target->setFaction(cinfo->faction_A);
// restore UNIT_FIELD_BYTES_0
if (cinfo && caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK && cinfo->type == CREATURE_TYPE_DEMON)
{
// DB must have proper class set in field at loading, not req. restore, including workaround case at apply
// m_target->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class);
if (target->GetCharmInfo())
target->GetCharmInfo()->SetPetNumber(0, true);
else
sLog.outError("Aura::HandleModCharm: target (GUID: %u TypeId: %u) has a charm aura but no charm info!", target->GetGUIDLow(), target->GetTypeId());
}
}
caster->SetCharm(NULL);
if (caster->GetTypeId() == TYPEID_PLAYER)
((Player*)caster)->RemovePetActionBar();
target->CombatStop(true);
target->DeleteThreatList();
target->getHostileRefManager().deleteReferences();
if (target->GetTypeId() == TYPEID_UNIT)
{
((Creature*)target)->AIM_Initialize();
target->AttackedBy(caster);
}
}
}
void Aura::HandleModConfuse(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetConfused(apply, GetCasterGuid(), GetId());
}
void Aura::HandleModFear(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetFeared(apply, GetCasterGuid(), GetId());
}
void Aura::HandleFeignDeath(bool apply, bool Real)
{
if (!Real)
return;
GetTarget()->SetFeignDeath(apply, GetCasterGuid(), GetId());
}
void Aura::HandleAuraModDisarm(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
if (!apply && target->HasAuraType(GetModifier()->m_auraname))
return;
target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED, apply);
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// main-hand attack speed already set to special value for feral form already and don't must change and reset at remove.
if (target->IsInFeralForm())
return;
if (apply)
target->SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
else
((Player*)target)->SetRegularAttackTime();
target->UpdateDamagePhysical(BASE_ATTACK);
}
void Aura::HandleAuraModStun(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Frost stun aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
target->addUnitState(UNIT_STAT_STUNNED);
target->SetTargetGuid(ObjectGuid());
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
target->CastStop(target->GetObjectGuid() == GetCasterGuid() ? GetId() : 0);
// Creature specific
if (target->GetTypeId() != TYPEID_PLAYER)
target->StopMoving();
else
{
((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
target->SetStandState(UNIT_STAND_STATE_STAND);// in 1.5 client
}
target->SetRoot(true);
// Summon the Naj'entus Spine GameObject on target if spell is Impaling Spine
if (GetId() == 39837)
{
GameObject* pObj = new GameObject;
if (pObj->Create(target->GetMap()->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), 185584, target->GetMap(),
target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation()))
{
pObj->SetRespawnTime(GetAuraDuration() / IN_MILLISECONDS);
pObj->SetSpellId(GetId());
target->AddGameObject(pObj);
target->GetMap()->Add(pObj);
}
else
delete pObj;
}
}
else
{
// Frost stun aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
bool found_another = false;
for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auras = target->GetAurasByType(*itr);
for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
found_another = true;
break;
}
}
if (found_another)
break;
}
if (!found_another)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
}
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_STUN))
return;
target->clearUnitState(UNIT_STAT_STUNNED);
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
if (!target->hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect
{
if (target->getVictim() && target->isAlive())
target->SetTargetGuid(target->getVictim()->GetObjectGuid());
target->SetRoot(false);
}
// Wyvern Sting
if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000100000000000))
{
Unit* caster = GetCaster();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
uint32 spell_id = 0;
switch (GetId())
{
case 19386: spell_id = 24131; break;
case 24132: spell_id = 24134; break;
case 24133: spell_id = 24135; break;
case 27068: spell_id = 27069; break;
default:
sLog.outError("Spell selection called for unexpected original spell %u, new spell for this spell family?", GetId());
return;
}
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
return;
caster->CastSpell(target, spellInfo, true, NULL, this);
return;
}
}
}
void Aura::HandleModStealth(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
// drop flag at stealth in bg
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// only at real aura add
if (Real)
{
target->SetStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH);
// apply only if not in GM invisibility (and overwrite invisibility state)
if (target->GetVisibility() != VISIBILITY_OFF)
{
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_STEALTH);
}
// for RACE_NIGHTELF stealth
if (target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580)
target->CastSpell(target, 21009, true, NULL, this);
// apply full stealth period bonuses only at first stealth aura in stack
if (target->GetAurasByType(SPELL_AURA_MOD_STEALTH).size() <= 1)
{
Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
// Master of Subtlety
if ((*i)->GetSpellProto()->SpellIconID == 2114)
{
target->RemoveAurasDueToSpell(31666);
int32 bp = (*i)->GetModifier()->m_amount;
target->CastCustomSpell(target, 31665, &bp, NULL, NULL, true);
break;
}
}
}
}
}
else
{
// for RACE_NIGHTELF stealth
if (Real && target->GetTypeId() == TYPEID_PLAYER && GetId() == 20580)
target->RemoveAurasDueToSpell(21009);
// only at real aura remove of _last_ SPELL_AURA_MOD_STEALTH
if (Real && !target->HasAuraType(SPELL_AURA_MOD_STEALTH))
{
// if no GM invisibility
if (target->GetVisibility() != VISIBILITY_OFF)
{
target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP);
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_STEALTH);
// restore invisibility if any
if (target->HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
{
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
}
else
target->SetVisibility(VISIBILITY_ON);
}
// apply delayed talent bonus remover at last stealth aura remove
Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
// Master of Subtlety
if ((*i)->GetSpellProto()->SpellIconID == 2114)
{
target->CastSpell(target, 31666, true);
break;
}
}
}
}
}
void Aura::HandleInvisibility(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
target->m_invisibilityMask |= (1 << m_modifier.m_miscvalue);
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
// apply glow vision
target->SetByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
}
// apply only if not in GM invisibility and not stealth
if (target->GetVisibility() == VISIBILITY_ON)
{
// Aura not added yet but visibility code expect temporary add aura
target->SetVisibility(VISIBILITY_GROUP_NO_DETECT);
target->SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
}
}
else
{
// recalculate value at modifier remove (current aura already removed)
target->m_invisibilityMask = 0;
Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
target->m_invisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue);
// only at real aura remove and if not have different invisibility auras.
if (Real && target->m_invisibilityMask == 0)
{
// remove glow vision
if (target->GetTypeId() == TYPEID_PLAYER)
target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 1, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW);
// apply only if not in GM invisibility & not stealthed while invisible
if (target->GetVisibility() != VISIBILITY_OFF)
{
// if have stealth aura then already have stealth visibility
if (!target->HasAuraType(SPELL_AURA_MOD_STEALTH))
target->SetVisibility(VISIBILITY_ON);
}
}
}
}
void Aura::HandleInvisibilityDetect(bool apply, bool Real)
{
Unit* target = GetTarget();
if (apply)
{
target->m_detectInvisibilityMask |= (1 << m_modifier.m_miscvalue);
}
else
{
// recalculate value at modifier remove (current aura already removed)
target->m_detectInvisibilityMask = 0;
Unit::AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
target->m_detectInvisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue);
}
if (Real && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->GetCamera().UpdateVisibilityForOwner();
}
void Aura::HandleDetectAmore(bool apply, bool /*real*/)
{
GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES2, 1, (PLAYER_FIELD_BYTE2_DETECT_AMORE_0 << m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRoot(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Frost root aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
target->addUnitState(UNIT_STAT_ROOT);
target->SetTargetGuid(ObjectGuid());
// Save last orientation
if (target->getVictim())
target->SetOrientation(target->GetAngle(target->getVictim()));
if (target->GetTypeId() == TYPEID_PLAYER)
{
target->SetRoot(true);
// Clear unit movement flags
((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
}
else
target->StopMoving();
}
else
{
// Frost root aura -> freeze/unfreeze target
if (GetSpellSchoolMask(GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
bool found_another = false;
for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auras = target->GetAurasByType(*itr);
for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (GetSpellSchoolMask((*i)->GetSpellProto()) & SPELL_SCHOOL_MASK_FROST)
{
found_another = true;
break;
}
}
if (found_another)
break;
}
if (!found_another)
target->ModifyAuraState(AURA_STATE_FROZEN, apply);
}
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_ROOT))
return;
target->clearUnitState(UNIT_STAT_ROOT);
if (!target->hasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect
{
if (target->getVictim() && target->isAlive())
target->SetTargetGuid(target->getVictim()->GetObjectGuid());
if (target->GetTypeId() == TYPEID_PLAYER)
target->SetRoot(false);
}
}
}
void Aura::HandleAuraModSilence(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
// Stop cast only spells vs PreventionType == SPELL_PREVENTION_TYPE_SILENCE
for (uint32 i = CURRENT_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
// Stop spells on prepare or casting state
target->InterruptSpell(CurrentSpellTypes(i), false);
switch (GetId())
{
// Arcane Torrent (Energy)
case 25046:
{
Unit* caster = GetCaster();
if (!caster)
return;
// Search Mana Tap auras on caster
Aura* dummy = caster->GetDummyAura(28734);
if (dummy)
{
int32 bp = dummy->GetStackAmount() * 10;
caster->CastCustomSpell(caster, 25048, &bp, NULL, NULL, true);
caster->RemoveAurasDueToSpell(28734);
}
}
}
}
else
{
// Real remove called after current aura remove from lists, check if other similar auras active
if (target->HasAuraType(SPELL_AURA_MOD_SILENCE))
return;
target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
}
}
void Aura::HandleModThreat(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive())
return;
int level_diff = 0;
int multiplier = 0;
switch (GetId())
{
// Arcane Shroud
case 26400:
level_diff = target->getLevel() - 60;
multiplier = 2;
break;
// The Eye of Diminution
case 28862:
level_diff = target->getLevel() - 60;
multiplier = 1;
break;
}
if (level_diff > 0)
m_modifier.m_amount += multiplier * level_diff;
if (target->GetTypeId() == TYPEID_PLAYER)
for (int8 x = 0; x < MAX_SPELL_SCHOOL; ++x)
if (m_modifier.m_miscvalue & int32(1 << x))
ApplyPercentModFloatVar(target->m_threatModifier[x], float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModTotalThreat(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive() || target->GetTypeId() != TYPEID_PLAYER)
return;
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
float threatMod = apply ? float(m_modifier.m_amount) : float(-m_modifier.m_amount);
target->getHostileRefManager().threatAssist(caster, threatMod, GetSpellProto());
}
void Aura::HandleModTaunt(bool apply, bool Real)
{
// only at real add/remove aura
if (!Real)
return;
Unit* target = GetTarget();
if (!target->isAlive() || !target->CanHaveThreatList())
return;
Unit* caster = GetCaster();
if (!caster || !caster->isAlive())
return;
if (apply)
target->TauntApply(caster);
else
{
// When taunt aura fades out, mob will switch to previous target if current has less than 1.1 * secondthreat
target->TauntFadeOut(caster);
}
}
/*********************************************************/
/*** MODIFY SPEED ***/
/*********************************************************/
void Aura::HandleAuraModIncreaseSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_RUN, true);
}
void Aura::HandleAuraModIncreaseMountedSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_RUN, true);
}
void Aura::HandleAuraModIncreaseFlightSpeed(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// Enable Fly mode for flying mounts
if (m_modifier.m_auraname == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED)
{
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12);
else
data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12);
data << target->GetPackGUID();
data << uint32(0); // unknown
target->SendMessageToSet(&data, true);
// Players on flying mounts must be immune to polymorph
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply);
// Dragonmaw Illusion (overwrite mount model, mounted aura already applied)
if (apply && target->HasAura(42016, EFFECT_INDEX_0) && target->GetMountID())
target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314);
}
target->UpdateSpeed(MOVE_FLIGHT, true);
}
void Aura::HandleAuraModIncreaseSwimSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->UpdateSpeed(MOVE_SWIM, true);
}
void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
if (apply)
{
// Gronn Lord's Grasp, becomes stoned
if (GetId() == 33572)
{
if (GetStackAmount() >= 5 && !target->HasAura(33652))
target->CastSpell(target, 33652, true);
}
}
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
}
void Aura::HandleAuraModUseNormalSpeed(bool /*apply*/, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
target->UpdateSpeed(MOVE_RUN, true);
target->UpdateSpeed(MOVE_SWIM, true);
target->UpdateSpeed(MOVE_FLIGHT, true);
}
/*********************************************************/
/*** IMMUNITY ***/
/*********************************************************/
void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/)
{
uint32 misc = m_modifier.m_miscvalue;
Unit* target = GetTarget();
if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
{
uint32 mechanic = 1 << (misc - 1);
// immune movement impairment and loss of control (spell data have special structure for mark this case)
if (IsSpellRemoveAllMovementAndControlLossEffects(GetSpellProto()))
mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
target->RemoveAurasAtMechanicImmunity(mechanic, GetId());
}
target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, misc, apply);
// special cases
switch (misc)
{
case MECHANIC_INVULNERABILITY:
target->ModifyAuraState(AURA_STATE_FORBEARANCE, apply);
break;
case MECHANIC_SHIELD:
target->ModifyAuraState(AURA_STATE_WEAKENED_SOUL, apply);
break;
}
// Bestial Wrath
if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellIconID == 1680)
{
// The Beast Within cast on owner if talent present
if (Unit* owner = target->GetOwner())
{
// Search talent The Beast Within
Unit::AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 2229)
{
if (apply)
owner->CastSpell(owner, 34471, true, NULL, this);
else
owner->RemoveAurasDueToSpell(34471);
break;
}
}
}
}
}
void Aura::HandleModMechanicImmunityMask(bool apply, bool /*Real*/)
{
uint32 mechanic = m_modifier.m_miscvalue;
if (apply && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
GetTarget()->RemoveAurasAtMechanicImmunity(mechanic, GetId());
// check implemented in Unit::IsImmuneToSpell and Unit::IsImmuneToSpellEffect
}
// this method is called whenever we add / remove aura which gives m_target some imunity to some spell effect
void Aura::HandleAuraModEffectImmunity(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
// when removing flag aura, handle flag drop
if (!apply && target->GetTypeId() == TYPEID_PLAYER
&& (GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION))
{
Player* player = (Player*)target;
if (BattleGround* bg = player->GetBattleGround())
bg->EventPlayerDroppedFlag(player);
else if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(player->GetCachedZoneId()))
outdoorPvP->HandleDropFlag(player, GetSpellProto()->Id);
}
target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModStateImmunity(bool apply, bool Real)
{
if (apply && Real && GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY))
{
Unit::AuraList const& auraList = GetTarget()->GetAurasByType(AuraType(m_modifier.m_miscvalue));
for (Unit::AuraList::const_iterator itr = auraList.begin(); itr != auraList.end();)
{
if (auraList.front() != this) // skip itself aura (it already added)
{
GetTarget()->RemoveAurasDueToSpell(auraList.front()->GetId());
itr = auraList.begin();
}
else
++itr;
}
}
GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_STATE, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModSchoolImmunity(bool apply, bool Real)
{
Unit* target = GetTarget();
target->ApplySpellImmune(GetId(), IMMUNITY_SCHOOL, m_modifier.m_miscvalue, apply);
// remove all flag auras (they are positive, but they must be removed when you are immune)
if (GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) && GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_DAMAGE_REDUCED_SHIELD))
target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
// TODO: optimalize this cycle - use RemoveAurasWithInterruptFlags call or something else
if (Real && apply
&& GetSpellProto()->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
&& IsPositiveSpell(GetId())) // Only positive immunity removes auras
{
uint32 school_mask = m_modifier.m_miscvalue;
Unit::SpellAuraHolderMap& Auras = target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::iterator iter = Auras.begin(), next; iter != Auras.end(); iter = next)
{
next = iter;
++next;
SpellEntry const* spell = iter->second->GetSpellProto();
if ((GetSpellSchoolMask(spell) & school_mask) // Check for school mask
&& !spell->HasAttribute(SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) // Spells unaffected by invulnerability
&& !iter->second->IsPositive() // Don't remove positive spells
&& spell->Id != GetId()) // Don't remove self
{
target->RemoveAurasDueToSpell(spell->Id);
if (Auras.empty())
break;
else
next = Auras.begin();
}
}
}
if (Real && GetSpellProto()->Mechanic == MECHANIC_BANISH)
{
if (apply)
target->addUnitState(UNIT_STAT_ISOLATED);
else
target->clearUnitState(UNIT_STAT_ISOLATED);
}
}
void Aura::HandleAuraModDmgImmunity(bool apply, bool /*Real*/)
{
GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_DAMAGE, m_modifier.m_miscvalue, apply);
}
void Aura::HandleAuraModDispelImmunity(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
GetTarget()->ApplySpellDispelImmunity(GetSpellProto(), DispelType(m_modifier.m_miscvalue), apply);
}
void Aura::HandleAuraProcTriggerSpell(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
switch (GetId())
{
// some spell have charges by functionality not have its in spell data
case 28200: // Ascendance (Talisman of Ascendance trinket)
if (apply)
GetHolder()->SetAuraCharges(6);
break;
default:
break;
}
}
void Aura::HandleAuraModStalked(bool apply, bool /*Real*/)
{
// used by spells: Hunter's Mark, Mind Vision, Syndicate Tracker (MURP) DND
if (apply)
GetTarget()->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
else
GetTarget()->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TRACK_UNIT);
}
/*********************************************************/
/*** PERIODIC ***/
/*********************************************************/
void Aura::HandlePeriodicTriggerSpell(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
Unit* target = GetTarget();
if (!apply)
{
switch (GetId())
{
case 66: // Invisibility
if (m_removeMode == AURA_REMOVE_BY_EXPIRE)
target->CastSpell(target, 32612, true, NULL, this);
return;
case 29213: // Curse of the Plaguebringer
if (m_removeMode != AURA_REMOVE_BY_DISPEL)
// Cast Wrath of the Plaguebringer if not dispelled
target->CastSpell(target, 29214, true, 0, this);
return;
case 42783: // Wrath of the Astrom...
if (m_removeMode == AURA_REMOVE_BY_EXPIRE && GetEffIndex() + 1 < MAX_EFFECT_INDEX)
target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(SpellEffectIndex(GetEffIndex() + 1)), true);
return;
default:
break;
}
}
}
void Aura::HandlePeriodicTriggerSpellWithValue(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicEnergize(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraPowerBurn(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraPeriodicDummy(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
SpellEntry const* spell = GetSpellProto();
switch (spell->SpellFamilyName)
{
case SPELLFAMILY_ROGUE:
{
// Master of Subtlety
if (spell->Id == 31666 && !apply)
{
target->RemoveAurasDueToSpell(31665);
break;
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Aspect of the Viper
if (spell->SpellFamilyFlags & UI64LIT(0x0004000000000000))
{
// Update regen on remove
if (!apply && target->GetTypeId() == TYPEID_PLAYER)
((Player*)target)->UpdateManaRegen();
break;
}
break;
}
}
m_isPeriodic = apply;
}
void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
Unit* target = GetTarget();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellHealingBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
void Aura::HandlePeriodicDamage(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
m_isPeriodic = apply;
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
// For prevent double apply bonuses
bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_WARRIOR:
{
// Rend
if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000020))
{
// 0.00743*(($MWB+$mwb)/2+$AP/14*$MWS) bonus per tick
float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
int32 mws = caster->GetAttackTime(BASE_ATTACK);
float mwb_min = caster->GetWeaponDamageRange(BASE_ATTACK, MINDAMAGE);
float mwb_max = caster->GetWeaponDamageRange(BASE_ATTACK, MAXDAMAGE);
m_modifier.m_amount += int32(((mwb_min + mwb_max) / 2 + ap * mws / 14000) * 0.00743f);
}
break;
}
case SPELLFAMILY_DRUID:
{
// Rip
if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000800000))
{
if (caster->GetTypeId() != TYPEID_PLAYER)
break;
// $AP * min(0.06*$cp, 0.24)/6 [Yes, there is no difference, whether 4 or 5 CPs are being used]
uint8 cp = ((Player*)caster)->GetComboPoints();
// Idol of Feral Shadows. Cant be handled as SpellMod in SpellAura:Dummy due its dependency from CPs
Unit::AuraList const& dummyAuras = caster->GetAurasByType(SPELL_AURA_DUMMY);
for (Unit::AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
if ((*itr)->GetId() == 34241)
{
m_modifier.m_amount += cp * (*itr)->GetModifier()->m_amount;
break;
}
}
if (cp > 4) cp = 4;
m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100);
}
break;
}
case SPELLFAMILY_ROGUE:
{
// Rupture
if (spellProto->SpellFamilyFlags & UI64LIT(0x000000000000100000))
{
if (caster->GetTypeId() != TYPEID_PLAYER)
break;
// Dmg/tick = $AP*min(0.01*$cp, 0.03) [Like Rip: only the first three CP increase the contribution from AP]
uint8 cp = ((Player*)caster)->GetComboPoints();
if (cp > 3) cp = 3;
m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100);
}
break;
}
default:
break;
}
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
{
// SpellDamageBonusDone for magic spells
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
m_modifier.m_amount = caster->SpellDamageBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
// MeleeDamagebonusDone for weapon based spells
else
{
WeaponAttackType attackType = GetWeaponAttackType(GetSpellProto());
m_modifier.m_amount = caster->MeleeDamageBonusDone(target, m_modifier.m_amount, attackType, GetSpellProto(), DOT, GetStackAmount());
}
}
}
// remove time effects
else
{
// Parasitic Shadowfiend - handle summoning of two Shadowfiends on DoT expire
if (spellProto->Id == 41917)
target->CastSpell(target, 41915, true);
}
}
void Aura::HandlePeriodicDamagePCT(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicLeech(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
// For prevent double apply bonuses
bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
void Aura::HandlePeriodicManaLeech(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandlePeriodicHealthFunnel(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
// For prevent double apply bonuses
bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading());
// Custom damage calculation after
if (apply)
{
if (loading)
return;
Unit* caster = GetCaster();
if (!caster)
return;
m_modifier.m_amount = caster->SpellDamageBonusDone(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount());
}
}
/*********************************************************/
/*** MODIFY STATS ***/
/*********************************************************/
/********************************/
/*** RESISTANCE ***/
/********************************/
void Aura::HandleAuraModResistanceExclusive(bool apply, bool /*Real*/)
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
{
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleAuraModResistance(bool apply, bool /*Real*/)
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
{
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet())
GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleAuraModBaseResistancePCT(bool apply, bool /*Real*/)
{
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
{
// pets only have base armor
if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, BASE_PCT, float(m_modifier.m_amount), apply);
}
else
{
for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x)
{
if (m_modifier.m_miscvalue & int32(1 << x))
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_PCT, float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleModResistancePercent(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
{
if (m_modifier.m_miscvalue & int32(1 << i))
{
target->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply);
if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet())
{
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), true, float(m_modifier.m_amount), apply);
target->ApplyResistanceBuffModsPercentMod(SpellSchools(i), false, float(m_modifier.m_amount), apply);
}
}
}
}
void Aura::HandleModBaseResistance(bool apply, bool /*Real*/)
{
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
{
// only pets have base stats
if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
else
{
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
}
/********************************/
/*** STAT ***/
/********************************/
void Aura::HandleAuraModStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -2 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Spell %u effect %u have unsupported misc value (%i) for SPELL_AURA_MOD_STAT ", GetId(), GetEffIndex(), m_modifier.m_miscvalue);
return;
}
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
// -1 or -2 is all stats ( misc < -2 checked in function beginning )
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue == i)
{
// m_target->ApplyStatMod(Stats(i), m_modifier.m_amount,apply);
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply);
if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet())
GetTarget()->ApplyStatBuffMod(Stats(i), float(m_modifier.m_amount), apply);
}
}
}
void Aura::HandleModPercentStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
// only players have base stats
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1)
GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), BASE_PCT, float(m_modifier.m_amount), apply);
}
}
void Aura::HandleModSpellDamagePercentFromStat(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModSpellHealingPercentFromStat(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleAuraModDispelResist(bool apply, bool Real)
{
if (!Real || !apply)
return;
if (GetId() == 33206)
GetTarget()->CastSpell(GetTarget(), 44416, true, NULL, this, GetCasterGuid());
}
void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModSpellHealingPercentFromAttackPower(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Recalculate bonus
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModHealingDone(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// implemented in Unit::SpellHealingBonusDone
// this information is for client side only
((Player*)GetTarget())->UpdateSpellDamageAndHealingBonus();
}
void Aura::HandleModTotalPercentStat(bool apply, bool /*Real*/)
{
if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4)
{
sLog.outError("WARNING: Misc Value for SPELL_AURA_MOD_PERCENT_STAT not valid");
return;
}
Unit* target = GetTarget();
// save current and max HP before applying aura
uint32 curHPValue = target->GetHealth();
uint32 maxHPValue = target->GetMaxHealth();
for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1)
{
target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply);
if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet())
target->ApplyStatPercentBuffMod(Stats(i), float(m_modifier.m_amount), apply);
}
}
// recalculate current HP/MP after applying aura modifications (only for spells with 0x10 flag)
if (m_modifier.m_miscvalue == STAT_STAMINA && maxHPValue > 0 && GetSpellProto()->HasAttribute(SPELL_ATTR_UNK4))
{
// newHP = (curHP / maxHP) * newMaxHP = (newMaxHP * curHP) / maxHP -> which is better because no int -> double -> int conversion is needed
uint32 newHPValue = (target->GetMaxHealth() * curHPValue) / maxHPValue;
target->SetHealth(newHPValue);
}
}
void Aura::HandleAuraModResistenceOfStatPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (m_modifier.m_miscvalue != SPELL_SCHOOL_MASK_NORMAL)
{
// support required adding replace UpdateArmor by loop by UpdateResistence at intellect update
// and include in UpdateResistence same code as in UpdateArmor for aura mod apply.
sLog.outError("Aura SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT(182) need adding support for non-armor resistances!");
return;
}
// Recalculate Armor
GetTarget()->UpdateArmor();
}
/********************************/
/*** HEAL & ENERGIZE ***/
/********************************/
void Aura::HandleAuraModTotalHealthPercentRegen(bool apply, bool /*Real*/)
{
m_isPeriodic = apply;
}
void Aura::HandleAuraModTotalManaPercentRegen(bool apply, bool /*Real*/)
{
if (m_modifier.periodictime == 0)
m_modifier.periodictime = 1000;
m_periodicTimer = m_modifier.periodictime;
m_isPeriodic = apply;
}
void Aura::HandleModRegen(bool apply, bool /*Real*/) // eating
{
if (m_modifier.periodictime == 0)
m_modifier.periodictime = 5000;
m_periodicTimer = 5000;
m_isPeriodic = apply;
}
void Aura::HandleModPowerRegen(bool apply, bool Real) // drinking
{
if (!Real)
return;
Powers pt = GetTarget()->getPowerType();
if (m_modifier.periodictime == 0)
{
// Anger Management (only spell use this aura for rage)
if (pt == POWER_RAGE)
m_modifier.periodictime = 3000;
else
m_modifier.periodictime = 2000;
}
m_periodicTimer = 5000;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER && m_modifier.m_miscvalue == POWER_MANA)
((Player*)GetTarget())->UpdateManaRegen();
m_isPeriodic = apply;
}
void Aura::HandleModPowerRegenPCT(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Update manaregen value
if (m_modifier.m_miscvalue == POWER_MANA)
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleModManaRegen(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
// Note: an increase in regen does NOT cause threat.
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleComprehendLanguage(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
}
void Aura::HandleAuraModIncreaseHealth(bool apply, bool Real)
{
Unit* target = GetTarget();
// Special case with temporary increase max/current health
switch (GetId())
{
case 12976: // Warrior Last Stand triggered spell
case 28726: // Nightmare Seed ( Nightmare Seed )
case 34511: // Valor (Bulwark of Kings, Bulwark of the Ancient Kings)
case 44055: // Tremendous Fortitude (Battlemaster's Alacrity)
{
if (Real)
{
if (apply)
{
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->ModifyHealth(m_modifier.m_amount);
}
else
{
if (int32(target->GetHealth()) > m_modifier.m_amount)
target->ModifyHealth(-m_modifier.m_amount);
else
target->SetHealth(1);
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
}
return;
}
}
// generic case
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseMaxHealth(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
uint32 oldhealth = target->GetHealth();
double healthPercentage = (double)oldhealth / (double)target->GetMaxHealth();
target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply);
// refresh percentage
if (oldhealth > 0)
{
uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage));
if (newhealth == 0)
newhealth = 1;
target->SetHealth(newhealth);
}
}
void Aura::HandleAuraModIncreaseEnergy(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
Powers powerType = target->getPowerType();
if (int32(powerType) != m_modifier.m_miscvalue)
return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
target->HandleStatModifier(unitMod, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseEnergyPercent(bool apply, bool /*Real*/)
{
Powers powerType = GetTarget()->getPowerType();
if (int32(powerType) != m_modifier.m_miscvalue)
return;
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + powerType);
GetTarget()->HandleStatModifier(unitMod, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModIncreaseHealthPercent(bool apply, bool /*Real*/)
{
GetTarget()->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
/********************************/
/*** FIGHT ***/
/********************************/
void Aura::HandleAuraModParryPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateParryPercentage();
}
void Aura::HandleAuraModDodgePercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateDodgePercentage();
// sLog.outError("BONUS DODGE CHANCE: + %f", float(m_modifier.m_amount));
}
void Aura::HandleAuraModBlockPercent(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateBlockPercentage();
// sLog.outError("BONUS BLOCK CHANCE: + %f", float(m_modifier.m_amount));
}
void Aura::HandleAuraModRegenInterrupt(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateManaRegen();
}
void Aura::HandleAuraModCritPercent(bool apply, bool Real)
{
Unit* target = GetTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// apply item specific bonuses for already equipped weapon
if (Real)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraCritMod(pItem, WeaponAttackType(i), this, apply);
}
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if (GetSpellProto()->EquippedItemClass == -1)
{
((Player*)target)->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
((Player*)target)->HandleBaseModValue(OFFHAND_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
((Player*)target)->HandleBaseModValue(RANGED_CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
}
void Aura::HandleModHitChance(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
if (target->GetTypeId() == TYPEID_PLAYER)
{
((Player*)target)->UpdateMeleeHitChances();
((Player*)target)->UpdateRangedHitChances();
}
else
{
target->m_modMeleeHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
target->m_modRangedHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellHitChance(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
{
((Player*)GetTarget())->UpdateSpellHitChances();
}
else
{
GetTarget()->m_modSpellHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellCritChance(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
{
((Player*)GetTarget())->UpdateAllSpellCritChances();
}
else
{
GetTarget()->m_baseSpellCritChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount);
}
}
void Aura::HandleModSpellCritChanceShool(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school)
if (m_modifier.m_miscvalue & (1 << school))
((Player*)GetTarget())->UpdateSpellCritChance(school);
}
/********************************/
/*** ATTACK SPEED ***/
/********************************/
void Aura::HandleModCastingSpeed(bool apply, bool /*Real*/)
{
GetTarget()->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply);
}
void Aura::HandleModMeleeRangedSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModCombatSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyCastTimePercentMod(float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModAttackSpeed(bool apply, bool /*Real*/)
{
GetTarget()->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleModMeleeSpeedPct(bool apply, bool /*Real*/)
{
Unit* target = GetTarget();
target->ApplyAttackTimePercentMod(BASE_ATTACK, float(m_modifier.m_amount), apply);
target->ApplyAttackTimePercentMod(OFF_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedHaste(bool apply, bool /*Real*/)
{
GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
void Aura::HandleRangedAmmoHaste(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
GetTarget()->ApplyAttackTimePercentMod(RANGED_ATTACK, float(m_modifier.m_amount), apply);
}
/********************************/
/*** ATTACK POWER ***/
/********************************/
void Aura::HandleAuraModAttackPower(bool apply, bool /*Real*/)
{
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPower(bool apply, bool /*Real*/)
{
if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModAttackPowerPercent(bool apply, bool /*Real*/)
{
// UNIT_FIELD_ATTACK_POWER_MULTIPLIER = multiplier - 1
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPowerPercent(bool apply, bool /*Real*/)
{
if ((GetTarget()->getClassMask() & CLASSMASK_WAND_USERS) != 0)
return;
// UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER = multiplier - 1
GetTarget()->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraModRangedAttackPowerOfStatPercent(bool /*apply*/, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
// Recalculate bonus
if (GetTarget()->GetTypeId() == TYPEID_PLAYER && !(GetTarget()->getClassMask() & CLASSMASK_WAND_USERS))
((Player*)GetTarget())->UpdateAttackPowerAndDamage(true);
}
/********************************/
/*** DAMAGE BONUS ***/
/********************************/
void Aura::HandleModDamageDone(bool apply, bool Real)
{
Unit* target = GetTarget();
// apply item specific bonuses for already equipped weapon
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply);
}
// m_modifier.m_miscvalue is bitmask of spell schools
// 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL)
// 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wands
// 127 - full bitmask any damages
//
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0)
{
// apply generic physical damage bonuses including wand case
if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER)
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (m_positive)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, m_modifier.m_amount, apply);
else
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG, m_modifier.m_amount, apply);
}
}
// Skip non magic case for speedup
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0)
return;
if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0)
{
// wand magic case (skip generic to all item spell bonuses)
// done in Player::_ApplyWeaponDependentAuraMods
// Skip item specific requirements for not wand magic damage
return;
}
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (m_positive)
{
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
if ((m_modifier.m_miscvalue & (1 << i)) != 0)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, m_modifier.m_amount, apply);
}
}
else
{
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
if ((m_modifier.m_miscvalue & (1 << i)) != 0)
target->ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, m_modifier.m_amount, apply);
}
}
Pet* pet = target->GetPet();
if (pet)
pet->UpdateAttackPowerAndDamage();
}
}
void Aura::HandleModDamagePercentDone(bool apply, bool Real)
{
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD DAMAGE type:%u negative:%u", m_modifier.m_miscvalue, m_positive ? 0 : 1);
Unit* target = GetTarget();
// apply item specific bonuses for already equipped weapon
if (Real && target->GetTypeId() == TYPEID_PLAYER)
{
for (int i = 0; i < MAX_ATTACK; ++i)
if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false))
((Player*)target)->_ApplyWeaponDependentAuraDamageMod(pItem, WeaponAttackType(i), this, apply);
}
// m_modifier.m_miscvalue is bitmask of spell schools
// 1 ( 0-bit ) - normal school damage (SPELL_SCHOOL_MASK_NORMAL)
// 126 - full bitmask all magic damages (SPELL_SCHOOL_MASK_MAGIC) including wand
// 127 - full bitmask any damages
//
// mods must be applied base at equipped weapon class and subclass comparison
// with spell->EquippedItemClass and EquippedItemSubClassMask and EquippedItemInventoryTypeMask
// m_modifier.m_miscvalue comparison with item generated damage types
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) != 0)
{
// apply generic physical damage bonuses including wand case
if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER)
{
target->HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
target->HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
else
{
// done in Player::_ApplyWeaponDependentAuraMods
}
// For show in client
if (target->GetTypeId() == TYPEID_PLAYER)
target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT, m_modifier.m_amount / 100.0f, apply);
}
// Skip non magic case for speedup
if ((m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_MAGIC) == 0)
return;
if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()->EquippedItemInventoryTypeMask != 0)
{
// wand magic case (skip generic to all item spell bonuses)
// done in Player::_ApplyWeaponDependentAuraMods
// Skip item specific requirements for not wand magic damage
return;
}
// Magic damage percent modifiers implemented in Unit::SpellDamageBonusDone
// Send info to client
if (target->GetTypeId() == TYPEID_PLAYER)
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
target->ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, m_modifier.m_amount / 100.0f, apply);
}
void Aura::HandleModOffhandDamagePercent(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "AURA MOD OFFHAND DAMAGE");
GetTarget()->HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT, float(m_modifier.m_amount), apply);
}
/********************************/
/*** POWER COST ***/
/********************************/
void Aura::HandleModPowerCostPCT(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
float amount = m_modifier.m_amount / 100.0f;
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, amount, apply);
}
void Aura::HandleModPowerCost(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
if (m_modifier.m_miscvalue & (1 << i))
GetTarget()->ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, m_modifier.m_amount, apply);
}
/*********************************************************/
/*** OTHERS ***/
/*********************************************************/
void Aura::HandleShapeshiftBoosts(bool apply)
{
uint32 spellId1 = 0;
uint32 spellId2 = 0;
uint32 HotWSpellId = 0;
ShapeshiftForm form = ShapeshiftForm(GetModifier()->m_miscvalue);
Unit* target = GetTarget();
switch (form)
{
case FORM_CAT:
spellId1 = 3025;
HotWSpellId = 24900;
break;
case FORM_TREE:
spellId1 = 5420;
break;
case FORM_TRAVEL:
spellId1 = 5419;
break;
case FORM_AQUA:
spellId1 = 5421;
break;
case FORM_BEAR:
spellId1 = 1178;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_DIREBEAR:
spellId1 = 9635;
spellId2 = 21178;
HotWSpellId = 24899;
break;
case FORM_BATTLESTANCE:
spellId1 = 21156;
break;
case FORM_DEFENSIVESTANCE:
spellId1 = 7376;
break;
case FORM_BERSERKERSTANCE:
spellId1 = 7381;
break;
case FORM_MOONKIN:
spellId1 = 24905;
break;
case FORM_FLIGHT:
spellId1 = 33948;
spellId2 = 34764;
break;
case FORM_FLIGHT_EPIC:
spellId1 = 40122;
spellId2 = 40121;
break;
case FORM_SPIRITOFREDEMPTION:
spellId1 = 27792;
spellId2 = 27795; // must be second, this important at aura remove to prevent to early iterator invalidation.
break;
case FORM_GHOSTWOLF:
case FORM_AMBIENT:
case FORM_GHOUL:
case FORM_SHADOW:
case FORM_STEALTH:
case FORM_CREATURECAT:
case FORM_CREATUREBEAR:
break;
}
if (apply)
{
if (spellId1)
target->CastSpell(target, spellId1, true, NULL, this);
if (spellId2)
target->CastSpell(target, spellId2, true, NULL, this);
if (target->GetTypeId() == TYPEID_PLAYER)
{
const PlayerSpellMap& sp_list = ((Player*)target)->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED) continue;
if (itr->first == spellId1 || itr->first == spellId2) continue;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first);
if (!spellInfo || !IsNeedCastSpellAtFormApply(spellInfo, form))
continue;
target->CastSpell(target, itr->first, true, NULL, this);
}
// Leader of the Pack
if (((Player*)target)->HasSpell(17007))
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(24932);
if (spellInfo && spellInfo->Stances & (1 << (form - 1)))
target->CastSpell(target, 24932, true, NULL, this);
}
// Heart of the Wild
if (HotWSpellId)
{
Unit::AuraList const& mModTotalStatPct = target->GetAurasByType(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE);
for (Unit::AuraList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 240 && (*i)->GetModifier()->m_miscvalue == 3)
{
int32 HotWMod = (*i)->GetModifier()->m_amount;
if (GetModifier()->m_miscvalue == FORM_CAT)
HotWMod /= 2;
target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this);
break;
}
}
}
}
}
else
{
if (spellId1)
target->RemoveAurasDueToSpell(spellId1);
if (spellId2)
target->RemoveAurasDueToSpell(spellId2);
Unit::SpellAuraHolderMap& tAuras = target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
{
if (itr->second->IsRemovedOnShapeLost())
{
target->RemoveAurasDueToSpell(itr->second->GetId());
itr = tAuras.begin();
}
else
++itr;
}
}
}
void Aura::HandleAuraEmpathy(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_UNIT)
return;
CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(GetTarget()->GetEntry());
if (ci && ci->type == CREATURE_TYPE_BEAST)
GetTarget()->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO, apply);
}
void Aura::HandleAuraUntrackable(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE);
else
GetTarget()->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNTRACKABLE);
}
void Aura::HandleAuraModPacify(bool apply, bool /*Real*/)
{
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED);
}
void Aura::HandleAuraModPacifyAndSilence(bool apply, bool Real)
{
HandleAuraModPacify(apply, Real);
HandleAuraModSilence(apply, Real);
}
void Aura::HandleAuraGhost(bool apply, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
if (apply)
{
GetTarget()->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
}
else
{
GetTarget()->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
}
}
void Aura::HandleAuraAllowFlight(bool apply, bool Real)
{
// all applied/removed only at real aura add/remove
if (!Real)
return;
// allow fly
WorldPacket data;
if (apply)
data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12);
else
data.Initialize(SMSG_MOVE_UNSET_CAN_FLY, 12);
data << GetTarget()->GetPackGUID();
data << uint32(0); // unk
GetTarget()->SendMessageToSet(&data, true);
}
void Aura::HandleModRating(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating)
if (m_modifier.m_miscvalue & (1 << rating))
((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), m_modifier.m_amount, apply);
}
void Aura::HandleForceMoveForward(bool apply, bool Real)
{
if (!Real)
return;
if (apply)
GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
else
GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
}
void Aura::HandleAuraModExpertise(bool /*apply*/, bool /*Real*/)
{
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
((Player*)GetTarget())->UpdateExpertise(BASE_ATTACK);
((Player*)GetTarget())->UpdateExpertise(OFF_ATTACK);
}
void Aura::HandleModTargetResistance(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// applied to damage as HandleNoImmediateEffect in Unit::CalculateAbsorbAndResist and Unit::CalcArmorReducedDamage
// show armor penetration
if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL))
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, m_modifier.m_amount, apply);
// show as spell penetration only full spell penetration bonuses (all resistances except armor and holy
if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_SPELL) == SPELL_SCHOOL_MASK_SPELL)
target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, m_modifier.m_amount, apply);
}
void Aura::HandleShieldBlockValue(bool apply, bool /*Real*/)
{
BaseModType modType = FLAT_MOD;
if (m_modifier.m_auraname == SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT)
modType = PCT_MOD;
if (GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->HandleBaseModValue(SHIELD_BLOCK_VALUE, modType, float(m_modifier.m_amount), apply);
}
void Aura::HandleAuraRetainComboPoints(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
if (GetTarget()->GetTypeId() != TYPEID_PLAYER)
return;
Player* target = (Player*)GetTarget();
// combo points was added in SPELL_EFFECT_ADD_COMBO_POINTS handler
// remove only if aura expire by time (in case combo points amount change aura removed without combo points lost)
if (!apply && m_removeMode == AURA_REMOVE_BY_EXPIRE && target->GetComboTargetGuid())
if (Unit* unit = ObjectAccessor::GetUnit(*GetTarget(), target->GetComboTargetGuid()))
target->AddComboPoints(unit, -m_modifier.m_amount);
}
void Aura::HandleModUnattackable(bool Apply, bool Real)
{
if (Real && Apply)
{
GetTarget()->CombatStop();
GetTarget()->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
}
GetTarget()->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, Apply);
}
void Aura::HandleSpiritOfRedemption(bool apply, bool Real)
{
// spells required only Real aura add/remove
if (!Real)
return;
Unit* target = GetTarget();
// prepare spirit state
if (apply)
{
if (target->GetTypeId() == TYPEID_PLAYER)
{
// disable breath/etc timers
((Player*)target)->StopMirrorTimers();
// set stand state (expected in this form)
if (!target->IsStandState())
target->SetStandState(UNIT_STAND_STATE_STAND);
}
target->SetHealth(1);
}
// die at aura end
else
target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, GetSpellProto(), false);
}
void Aura::HandleSchoolAbsorb(bool apply, bool Real)
{
if (!Real)
return;
Unit* caster = GetCaster();
if (!caster)
return;
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
if (apply)
{
// prevent double apply bonuses
if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading())
{
float DoneActualBenefit = 0.0f;
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_PRIEST:
// Power Word: Shield
if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001))
{
//+30% from +healing bonus
DoneActualBenefit = caster->SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto)) * 0.3f;
break;
}
break;
case SPELLFAMILY_MAGE:
// Frost Ward, Fire Ward
if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000100080108)))
//+10% from +spell bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f;
break;
case SPELLFAMILY_WARLOCK:
// Shadow Ward
if (spellProto->SpellFamilyFlags == UI64LIT(0x00))
//+10% from +spell bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)) * 0.1f;
break;
default:
break;
}
DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto());
m_modifier.m_amount += (int32)DoneActualBenefit;
}
}
}
void Aura::PeriodicTick()
{
Unit* target = GetTarget();
SpellEntry const* spellProto = GetSpellProto();
switch (m_modifier.m_auraname)
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
// some auras remove at specific health level or more
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
{
switch (GetId())
{
case 43093: case 31956: case 38801:
case 35321: case 38363: case 39215:
case 48920:
{
if (target->GetHealth() == target->GetMaxHealth())
{
target->RemoveAurasDueToSpell(GetId());
return;
}
break;
}
case 38772:
{
uint32 percent =
GetEffIndex() < EFFECT_INDEX_2 && spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_DUMMY ?
pCaster->CalculateSpellDamage(target, spellProto, SpellEffectIndex(GetEffIndex() + 1)) :
100;
if (target->GetHealth() * 100 >= target->GetMaxHealth() * percent)
{
target->RemoveAurasDueToSpell(GetId());
return;
}
break;
}
default:
break;
}
}
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage;
if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_DAMAGE)
pdamage = amount;
else
pdamage = uint32(target->GetMaxHealth() * amount / 100);
// SpellDamageBonus for magic spells
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
// MeleeDamagebonus for weapon based spells
else
{
WeaponAttackType attackType = GetWeaponAttackType(spellProto);
pdamage = target->MeleeDamageBonusTaken(pCaster, pdamage, attackType, spellProto, DOT, GetStackAmount());
}
// Calculate armor mitigation if it is a physical spell
// But not for bleed mechanic spells
if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL &&
GetEffectMechanic(spellProto, m_effIndex) != MECHANIC_BLEED)
{
uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage);
cleanDamage.damage += pdamage - pdamageReductedArmor;
pdamage = pdamageReductedArmor;
}
// Curse of Agony damage-per-tick calculation
if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000400)) && spellProto->SpellIconID == 544)
{
// 1..4 ticks, 1/2 from normal tick damage
if (GetAuraTicks() <= 4)
pdamage = pdamage / 2;
// 9..12 ticks, 3/2 from normal tick damage
else if (GetAuraTicks() >= 9)
pdamage += (pdamage + 1) / 2; // +1 prevent 0.5 damage possible lost at 1..4 ticks
// 5..8 ticks have normal tick damage
}
// As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit
// Reduce dot damage from resilience for players
if (target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage);
target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !GetSpellProto()->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED));
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s attacked %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
pCaster->DealDamageMods(target, pdamage, &absorb);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist);
SpellPeriodicAuraLogInfo pInfo(this, pdamage, absorb, resist, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
if (pdamage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto);
pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, true);
break;
}
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (!pCaster->isAlive())
return;
if (spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
uint32 absorb = 0;
uint32 resist = 0;
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
// Calculate armor mitigation if it is a physical spell
if (GetSpellSchoolMask(spellProto) & SPELL_SCHOOL_MASK_NORMAL)
{
uint32 pdamageReductedArmor = pCaster->CalcArmorReducedDamage(target, pdamage);
cleanDamage.damage += pdamage - pdamageReductedArmor;
pdamage = pdamageReductedArmor;
}
pdamage = target->SpellDamageBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
// As of 2.2 resilience reduces damage from DoT ticks as much as the chance to not be critically hit
// Reduce dot damage from resilience for players
if (target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetDotDamageReduction(pdamage);
target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !spellProto->HasAttribute(SPELL_ATTR_EX2_CANT_REFLECTED));
if (target->GetHealth() < pdamage)
pdamage = uint32(target->GetHealth());
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s health leech of %s for %u dmg inflicted by %u abs is %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId(), absorb);
pCaster->DealDamageMods(target, pdamage, &absorb);
pCaster->SendSpellNonMeleeDamageLog(target, GetId(), pdamage, GetSpellSchoolMask(spellProto), absorb, resist, false, 0);
float multiplier = spellProto->EffectMultipleValue[GetEffIndex()] > 0 ? spellProto->EffectMultipleValue[GetEffIndex()] : 1;
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist);
if (pdamage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, PROC_EX_NORMAL_HIT, pdamage, BASE_ATTACK, spellProto);
int32 new_damage = pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, false);
if (!target->isAlive() && pCaster->IsNonMeleeSpellCasted(false))
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = pCaster->GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->m_spellInfo->Id == GetId())
spell->cancel();
if (Player* modOwner = pCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, multiplier);
uint32 heal = pCaster->SpellHealingBonusTaken(pCaster, spellProto, int32(new_damage * multiplier), DOT, GetStackAmount());
int32 gain = pCaster->DealHeal(pCaster, heal, spellProto);
pCaster->getHostileRefManager().threatAssist(pCaster, gain * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
{
// don't heal target if not alive, mostly death persistent effects from items
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// heal for caster damage (must be alive)
if (target != pCaster && spellProto->SpellVisual == 163 && !pCaster->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage;
if (m_modifier.m_auraname == SPELL_AURA_OBS_MOD_HEALTH)
pdamage = uint32(target->GetMaxHealth() * amount / 100);
else
pdamage = amount;
pdamage = target->SpellHealingBonusTaken(pCaster, spellProto, pdamage, DOT, GetStackAmount());
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s heal of %s for %u health inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
int32 gain = target->ModifyHealth(pdamage);
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;
uint32 procEx = PROC_EX_NORMAL_HIT | PROC_EX_PERIODIC_POSITIVE;
pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, gain, BASE_ATTACK, spellProto);
// add HoTs to amount healed in bgs
if (pCaster->GetTypeId() == TYPEID_PLAYER)
if (BattleGround* bg = ((Player*)pCaster)->GetBattleGround())
bg->UpdatePlayerScore(((Player*)pCaster), SCORE_HEALING_DONE, gain);
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
// heal for caster damage
if (target != pCaster && spellProto->SpellVisual == 163)
{
uint32 dmg = spellProto->manaPerSecond;
if (pCaster->GetHealth() <= dmg && pCaster->GetTypeId() == TYPEID_PLAYER)
{
pCaster->RemoveAurasDueToSpell(GetId());
// finish current generic/channeling spells, don't affect autorepeat
pCaster->FinishSpell(CURRENT_GENERIC_SPELL);
pCaster->FinishSpell(CURRENT_CHANNELED_SPELL);
}
else
{
uint32 damage = gain;
uint32 absorb = 0;
pCaster->DealDamageMods(pCaster, damage, &absorb);
pCaster->SendSpellNonMeleeDamageLog(pCaster, GetId(), damage, GetSpellSchoolMask(spellProto), absorb, 0, false, 0, false);
CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL);
pCaster->DealDamage(pCaster, damage, &cleanDamage, NODAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
}
}
break;
}
case SPELL_AURA_PERIODIC_MANA_LEECH:
{
// don't damage target if not alive, possible death persistent effects
if (!target->isAlive())
return;
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS)
return;
Powers power = Powers(m_modifier.m_miscvalue);
// power type might have changed between aura applying and tick (druid's shapeshift)
if (target->getPowerType() != power)
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
if (!pCaster->isAlive())
return;
if (GetSpellProto()->Effect[GetEffIndex()] == SPELL_EFFECT_PERSISTENT_AREA_AURA &&
pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s power leech of %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
int32 drain_amount = target->GetPower(power) > pdamage ? pdamage : target->GetPower(power);
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (power == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER)
drain_amount -= ((Player*)target)->GetSpellCritDamageReduction(drain_amount);
target->ModifyPower(power, -drain_amount);
float gain_multiplier = 0.0f;
if (pCaster->GetMaxPower(power) > 0)
{
gain_multiplier = spellProto->EffectMultipleValue[GetEffIndex()];
if (Player* modOwner = pCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_MULTIPLE_VALUE, gain_multiplier);
}
SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, gain_multiplier);
target->SendPeriodicAuraLog(&pInfo);
if (int32 gain_amount = int32(drain_amount * gain_multiplier))
{
int32 gain = pCaster->ModifyPower(power, gain_amount);
if (GetId() == 5138) // Drain Mana
if (Aura* petPart = GetHolder()->GetAuraByEffectIndex(EFFECT_INDEX_1))
if (int pet_gain = gain_amount * petPart->GetModifier()->m_amount / 100)
pCaster->CastCustomSpell(pCaster, 32554, &pet_gain, NULL, NULL, true);
target->AddThreat(pCaster, float(gain) * 0.5f, false, GetSpellSchoolMask(spellProto), spellProto);
}
// Some special cases
switch (GetId())
{
case 32960: // Mark of Kazzak
{
if (target->GetTypeId() == TYPEID_PLAYER && target->getPowerType() == POWER_MANA)
{
// Drain 5% of target's mana
pdamage = target->GetMaxPower(POWER_MANA) * 5 / 100;
drain_amount = target->GetPower(POWER_MANA) > pdamage ? pdamage : target->GetPower(POWER_MANA);
target->ModifyPower(POWER_MANA, -drain_amount);
SpellPeriodicAuraLogInfo pInfo(this, drain_amount, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
}
// no break here
}
case 21056: // Mark of Kazzak
case 31447: // Mark of Kaz'rogal
{
uint32 triggerSpell = 0;
switch (GetId())
{
case 21056: triggerSpell = 21058; break;
case 31447: triggerSpell = 31463; break;
case 32960: triggerSpell = 32961; break;
}
if (target->GetTypeId() == TYPEID_PLAYER && target->GetPower(power) == 0)
{
target->CastSpell(target, triggerSpell, true, NULL, this);
target->RemoveAurasDueToSpell(GetId());
}
break;
}
}
break;
}
case SPELL_AURA_PERIODIC_ENERGIZE:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u dmg inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS)
break;
Powers power = Powers(m_modifier.m_miscvalue);
if (target->GetMaxPower(power) == 0)
break;
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
int32 gain = target->ModifyPower(power, pdamage);
if (Unit* pCaster = GetCaster())
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_OBS_MOD_MANA:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
// ignore non positive values (can be result apply spellmods to aura damage
uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
uint32 pdamage = uint32(target->GetMaxPower(POWER_MANA) * amount / 100);
DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s energize %s for %u mana inflicted by %u",
GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId());
if (target->GetMaxPower(POWER_MANA) == 0)
break;
SpellPeriodicAuraLogInfo pInfo(this, pdamage, 0, 0, 0.0f);
target->SendPeriodicAuraLog(&pInfo);
int32 gain = target->ModifyPower(POWER_MANA, pdamage);
if (Unit* pCaster = GetCaster())
target->getHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_POWER_BURN_MANA:
{
// don't mana burn target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Unit* pCaster = GetCaster();
if (!pCaster)
return;
// Check for immune (not use charges)
if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto)))
return;
int32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0;
Powers powerType = Powers(m_modifier.m_miscvalue);
if (!target->isAlive() || target->getPowerType() != powerType)
return;
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (powerType == POWER_MANA && target->GetTypeId() == TYPEID_PLAYER)
pdamage -= ((Player*)target)->GetSpellCritDamageReduction(pdamage);
uint32 gain = uint32(-target->ModifyPower(powerType, -pdamage));
gain = uint32(gain * spellProto->EffectMultipleValue[GetEffIndex()]);
// maybe has to be sent different to client, but not by SMSG_PERIODICAURALOG
SpellNonMeleeDamage damageInfo(pCaster, target, spellProto->Id, SpellSchoolMask(spellProto->SchoolMask));
pCaster->CalculateSpellDamage(&damageInfo, gain, spellProto);
damageInfo.target->CalculateAbsorbResistBlock(pCaster, &damageInfo, spellProto);
pCaster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
pCaster->SendSpellNonMeleeDamageLog(&damageInfo);
// Set trigger flag
uint32 procAttacker = PROC_FLAG_ON_DO_PERIODIC; // | PROC_FLAG_SUCCESSFUL_HARMFUL_SPELL_HIT;
uint32 procVictim = PROC_FLAG_ON_TAKE_PERIODIC;// | PROC_FLAG_TAKEN_HARMFUL_SPELL_HIT;
uint32 procEx = createProcExtendMask(&damageInfo, SPELL_MISS_NONE);
if (damageInfo.damage)
procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
pCaster->ProcDamageAndSpell(damageInfo.target, procAttacker, procVictim, procEx, damageInfo.damage, BASE_ATTACK, spellProto);
pCaster->DealSpellDamage(&damageInfo, true);
break;
}
case SPELL_AURA_MOD_REGEN:
{
// don't heal target if not alive, possible death persistent effects
if (!target->isAlive())
return;
int32 gain = target->ModifyHealth(m_modifier.m_amount);
if (Unit* caster = GetCaster())
target->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto);
break;
}
case SPELL_AURA_MOD_POWER_REGEN:
{
// don't energize target if not alive, possible death persistent effects
if (!target->isAlive())
return;
Powers pt = target->getPowerType();
if (int32(pt) != m_modifier.m_miscvalue)
return;
if (spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED)
{
// eating anim
target->HandleEmoteCommand(EMOTE_ONESHOT_EAT);
}
else if (GetId() == 20577)
{
// cannibalize anim
target->HandleEmoteCommand(EMOTE_STATE_CANNIBALIZE);
}
// Anger Management
// amount = 1+ 16 = 17 = 3,4*5 = 10,2*5/3
// so 17 is rounded amount for 5 sec tick grow ~ 1 range grow in 3 sec
if (pt == POWER_RAGE)
target->ModifyPower(pt, m_modifier.m_amount * 3 / 5);
break;
}
// Here tick dummy auras
case SPELL_AURA_DUMMY: // some spells have dummy aura
case SPELL_AURA_PERIODIC_DUMMY:
{
PeriodicDummyTick();
break;
}
case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
{
TriggerSpell();
break;
}
case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE:
{
TriggerSpellWithValue();
break;
}
default:
break;
}
}
void Aura::PeriodicDummyTick()
{
SpellEntry const* spell = GetSpellProto();
Unit* target = GetTarget();
switch (spell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (spell->Id)
{
// Forsaken Skills
case 7054:
{
// Possibly need cast one of them (but
// 7038 Forsaken Skill: Swords
// 7039 Forsaken Skill: Axes
// 7040 Forsaken Skill: Daggers
// 7041 Forsaken Skill: Maces
// 7042 Forsaken Skill: Staves
// 7043 Forsaken Skill: Bows
// 7044 Forsaken Skill: Guns
// 7045 Forsaken Skill: 2H Axes
// 7046 Forsaken Skill: 2H Maces
// 7047 Forsaken Skill: 2H Swords
// 7048 Forsaken Skill: Defense
// 7049 Forsaken Skill: Fire
// 7050 Forsaken Skill: Frost
// 7051 Forsaken Skill: Holy
// 7053 Forsaken Skill: Shadow
return;
}
case 7057: // Haunting Spirits
if (roll_chance_i(33))
target->CastSpell(target, m_modifier.m_amount, true, NULL, this);
return;
// // Panda
// case 19230: break;
// // Gossip NPC Periodic - Talk
// case 33208: break;
// // Gossip NPC Periodic - Despawn
// case 33209: break;
// // Steal Weapon
// case 36207: break;
// // Simon Game START timer, (DND)
// case 39993: break;
// // Harpooner's Mark
// case 40084: break;
// // Old Mount Spell
// case 40154: break;
// // Magnetic Pull
// case 40581: break;
// // Ethereal Ring: break; The Bolt Burst
// case 40801: break;
// // Crystal Prison
// case 40846: break;
// // Copy Weapon
// case 41054: break;
// // Ethereal Ring Visual, Lightning Aura
// case 41477: break;
// // Ethereal Ring Visual, Lightning Aura (Fork)
// case 41525: break;
// // Ethereal Ring Visual, Lightning Jumper Aura
// case 41567: break;
// // No Man's Land
// case 41955: break;
// // Headless Horseman - Fire
// case 42074: break;
// // Headless Horseman - Visual - Large Fire
// case 42075: break;
// // Headless Horseman - Start Fire, Periodic Aura
// case 42140: break;
// // Ram Speed Boost
// case 42152: break;
// // Headless Horseman - Fires Out Victory Aura
// case 42235: break;
// // Pumpkin Life Cycle
// case 42280: break;
// // Brewfest Request Chick Chuck Mug Aura
// case 42537: break;
// // Squashling
// case 42596: break;
// // Headless Horseman Climax, Head: Periodic
// case 42603: break;
case 42621: // Fire Bomb
{
// Cast the summon spells (42622 to 42627) with increasing chance
uint32 rand = urand(0, 99);
for (uint32 i = 1; i <= 6; ++i)
{
if (rand < i * (i + 1) / 2 * 5)
{
target->CastSpell(target, spell->Id + i, true);
break;
}
}
break;
}
// // Headless Horseman - Conflagrate, Periodic Aura
// case 42637: break;
// // Headless Horseman - Create Pumpkin Treats Aura
// case 42774: break;
// // Headless Horseman Climax - Summoning Rhyme Aura
// case 42879: break;
// // Tricky Treat
// case 42919: break;
// // Giddyup!
// case 42924: break;
// // Ram - Trot
// case 42992: break;
// // Ram - Canter
// case 42993: break;
// // Ram - Gallop
// case 42994: break;
// // Ram Level - Neutral
// case 43310: break;
// // Headless Horseman - Maniacal Laugh, Maniacal, Delayed 17
// case 43884: break;
// // Headless Horseman - Maniacal Laugh, Maniacal, other, Delayed 17
// case 44000: break;
// // Energy Feedback
// case 44328: break;
// // Romantic Picnic
// case 45102: break;
// // Romantic Picnic
// case 45123: break;
// // Looking for Love
// case 45124: break;
// // Kite - Lightning Strike Kite Aura
// case 45197: break;
// // Rocket Chicken
// case 45202: break;
// // Copy Offhand Weapon
// case 45205: break;
// // Upper Deck - Kite - Lightning Periodic Aura
// case 45207: break;
// // Kite -Sky Lightning Strike Kite Aura
// case 45251: break;
// // Ribbon Pole Dancer Check Aura
// case 45390: break;
// // Holiday - Midsummer, Ribbon Pole Periodic Visual
// case 45406: break;
// // Alliance Flag, Extra Damage Debuff
// case 45898: break;
// // Horde Flag, Extra Damage Debuff
// case 45899: break;
// // Ahune - Summoning Rhyme Aura
// case 45926: break;
// // Ahune - Slippery Floor
// case 45945: break;
// // Ahune's Shield
// case 45954: break;
// // Nether Vapor Lightning
// case 45960: break;
// // Darkness
// case 45996: break;
case 46041: // Summon Blood Elves Periodic
target->CastSpell(target, 46037, true, NULL, this);
target->CastSpell(target, roll_chance_i(50) ? 46038 : 46039, true, NULL, this);
target->CastSpell(target, 46040, true, NULL, this);
return;
// // Transform Visual Missile Periodic
// case 46205: break;
// // Find Opening Beam End
// case 46333: break;
// // Ice Spear Control Aura
// case 46371: break;
// // Hailstone Chill
// case 46458: break;
// // Hailstone Chill, Internal
// case 46465: break;
// // Chill, Internal Shifter
// case 46549: break;
// // Summon Ice Spear Knockback Delayer
// case 46878: break;
// // Send Mug Control Aura
// case 47369: break;
// // Direbrew's Disarm (precast)
// case 47407: break;
// // Mole Machine Port Schedule
// case 47489: break;
// // Mole Machine Portal Schedule
// case 49466: break;
// // Drink Coffee
// case 49472: break;
// // Listening to Music
// case 50493: break;
// // Love Rocket Barrage
// case 50530: break;
// Exist more after, need add later
default:
break;
}
// Drink (item drink spells)
if (GetEffIndex() > EFFECT_INDEX_0 && spell->EffectApplyAuraName[GetEffIndex()-1] == SPELL_AURA_MOD_POWER_REGEN)
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Search SPELL_AURA_MOD_POWER_REGEN aura for this spell and add bonus
if (Aura* aura = GetHolder()->GetAuraByEffectIndex(SpellEffectIndex(GetEffIndex() - 1)))
{
aura->GetModifier()->m_amount = m_modifier.m_amount;
((Player*)target)->UpdateManaRegen();
// Disable continue
m_isPeriodic = false;
return;
}
return;
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Aspect of the Viper
switch (spell->Id)
{
case 34074:
{
if (target->GetTypeId() != TYPEID_PLAYER)
return;
// Should be manauser
if (target->getPowerType() != POWER_MANA)
return;
Unit* caster = GetCaster();
if (!caster)
return;
// Regen amount is max (100% from spell) on 21% or less mana and min on 92.5% or greater mana (20% from spell)
int mana = target->GetPower(POWER_MANA);
int max_mana = target->GetMaxPower(POWER_MANA);
int32 base_regen = caster->CalculateSpellDamage(target, GetSpellProto(), m_effIndex, &m_currentBasePoints);
float regen_pct = 1.20f - 1.1f * mana / max_mana;
if (regen_pct > 1.0f) regen_pct = 1.0f;
else if (regen_pct < 0.2f) regen_pct = 0.2f;
m_modifier.m_amount = int32(base_regen * regen_pct);
((Player*)target)->UpdateManaRegen();
return;
}
// // Knockdown Fel Cannon: break; The Aggro Burst
// case 40119: break;
}
break;
}
default:
break;
}
}
void Aura::HandlePreventFleeing(bool apply, bool Real)
{
if (!Real)
return;
Unit::AuraList const& fearAuras = GetTarget()->GetAurasByType(SPELL_AURA_MOD_FEAR);
if (!fearAuras.empty())
{
if (apply)
GetTarget()->SetFeared(false, fearAuras.front()->GetCasterGuid());
else
GetTarget()->SetFeared(true);
}
}
void Aura::HandleManaShield(bool apply, bool Real)
{
if (!Real)
return;
// prevent double apply bonuses
if (apply && (GetTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)GetTarget())->GetSession()->PlayerLoading()))
{
if (Unit* caster = GetCaster())
{
float DoneActualBenefit = 0.0f;
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000008000))
{
// Mana Shield
// +50% from +spd bonus
DoneActualBenefit = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(GetSpellProto())) * 0.5f;
break;
}
break;
default:
break;
}
DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto());
m_modifier.m_amount += (int32)DoneActualBenefit;
}
}
}
void Aura::HandleArenaPreparation(bool apply, bool Real)
{
if (!Real)
return;
Unit* target = GetTarget();
target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION, apply);
if (apply)
{
// max regen powers at start preparation
target->SetHealth(target->GetMaxHealth());
target->SetPower(POWER_MANA, target->GetMaxPower(POWER_MANA));
target->SetPower(POWER_ENERGY, target->GetMaxPower(POWER_ENERGY));
}
else
{
// reset originally 0 powers at start/leave
target->SetPower(POWER_RAGE, 0);
}
}
void Aura::HandleAuraMirrorImage(bool apply, bool Real)
{
if (!Real)
return;
// Target of aura should always be creature (ref Spell::CheckCast)
Creature* pCreature = (Creature*)GetTarget();
if (apply)
{
// Caster can be player or creature, the unit who pCreature will become an clone of.
Unit* caster = GetCaster();
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, caster->getRace());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, caster->getClass());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, caster->getGender());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, caster->getPowerType());
pCreature->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED);
pCreature->SetDisplayId(caster->GetNativeDisplayId());
}
else
{
const CreatureInfo* cinfo = pCreature->GetCreatureInfo();
const CreatureModelInfo* minfo = sObjectMgr.GetCreatureModelInfo(pCreature->GetNativeDisplayId());
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, 0);
pCreature->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED);
pCreature->SetDisplayId(pCreature->GetNativeDisplayId());
}
}
void Aura::HandleAuraSafeFall(bool Apply, bool Real)
{
// implemented in WorldSession::HandleMovementOpcodes
// only special case
if (Apply && Real && GetId() == 32474 && GetTarget()->GetTypeId() == TYPEID_PLAYER)
((Player*)GetTarget())->ActivateTaxiPathTo(506, GetId());
}
bool Aura::IsLastAuraOnHolder()
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (i != GetEffIndex() && GetHolder()->m_auras[i])
return false;
return true;
}
bool Aura::HasMechanic(uint32 mechanic) const
{
return GetSpellProto()->Mechanic == mechanic ||
GetSpellProto()->EffectMechanic[m_effIndex] == mechanic;
}
SpellAuraHolder::SpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) :
m_spellProto(spellproto),
m_target(target), m_castItemGuid(castItem ? castItem->GetObjectGuid() : ObjectGuid()),
m_auraSlot(MAX_AURAS), m_auraLevel(1),
m_procCharges(0), m_stackAmount(1),
m_timeCla(1000), m_removeMode(AURA_REMOVE_BY_DEFAULT), m_AuraDRGroup(DIMINISHING_NONE),
m_permanent(false), m_isRemovedOnShapeLost(true), m_deleted(false), m_in_use(0)
{
MANGOS_ASSERT(target);
MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element");
if (!caster)
m_casterGuid = target->GetObjectGuid();
else
{
// remove this assert when not unit casters will be supported
MANGOS_ASSERT(caster->isType(TYPEMASK_UNIT))
m_casterGuid = caster->GetObjectGuid();
}
m_applyTime = time(NULL);
m_isPassive = IsPassiveSpell(spellproto);
m_isDeathPersist = IsDeathPersistentSpell(spellproto);
m_trackedAuraType= IsSingleTargetSpell(spellproto) ? TRACK_AURA_TYPE_SINGLE_TARGET : TRACK_AURA_TYPE_NOT_TRACKED;
m_procCharges = spellproto->procCharges;
m_isRemovedOnShapeLost = (GetCasterGuid() == m_target->GetObjectGuid() &&
m_spellProto->Stances &&
!m_spellProto->HasAttribute(SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) &&
!m_spellProto->HasAttribute(SPELL_ATTR_NOT_SHAPESHIFT));
Unit* unitCaster = caster && caster->isType(TYPEMASK_UNIT) ? (Unit*)caster : NULL;
m_duration = m_maxDuration = CalculateSpellDuration(spellproto, unitCaster);
if (m_maxDuration == -1 || (m_isPassive && spellproto->DurationIndex == 0))
m_permanent = true;
if (unitCaster)
{
if (Player* modOwner = unitCaster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges);
}
// some custom stack values at aura holder create
switch (m_spellProto->Id)
{
// some auras applied with max stack
case 24575: // Brittle Armor
case 24659: // Unstable Power
case 24662: // Restless Strength
case 26464: // Mercurial Shield
m_stackAmount = m_spellProto->StackAmount;
break;
}
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
m_auras[i] = NULL;
}
void SpellAuraHolder::AddAura(Aura* aura, SpellEffectIndex index)
{
m_auras[index] = aura;
}
void SpellAuraHolder::RemoveAura(SpellEffectIndex index)
{
m_auras[index] = NULL;
}
void SpellAuraHolder::ApplyAuraModifiers(bool apply, bool real)
{
for (int32 i = 0; i < MAX_EFFECT_INDEX && !IsDeleted(); ++i)
if (Aura* aur = GetAuraByEffectIndex(SpellEffectIndex(i)))
aur->ApplyModifier(apply, real);
}
void SpellAuraHolder::_AddSpellAuraHolder()
{
if (!GetId())
return;
if (!m_target)
return;
// Try find slot for aura
uint8 slot = NULL_AURA_SLOT;
Unit* caster = GetCaster();
// Lookup free slot
// will be < MAX_AURAS slot (if find free) with !secondaura
if (IsNeedVisibleSlot(caster))
{
if (IsPositive()) // empty positive slot
{
for (uint8 i = 0; i < MAX_POSITIVE_AURAS; i++)
{
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0)
{
slot = i;
break;
}
}
}
else // empty negative slot
{
for (uint8 i = MAX_POSITIVE_AURAS; i < MAX_AURAS; i++)
{
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + i)) == 0)
{
slot = i;
break;
}
}
}
}
// set infinity cooldown state for spells
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
if (m_spellProto->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE))
{
Item* castItem = m_castItemGuid ? ((Player*)caster)->GetItemByGuid(m_castItemGuid) : NULL;
((Player*)caster)->AddSpellAndCategoryCooldowns(m_spellProto, castItem ? castItem->GetEntry() : 0, NULL, true);
}
}
SetAuraSlot(slot);
// Not update fields for not first spell's aura, all data already in fields
if (slot < MAX_AURAS) // slot found
{
SetAura(slot, false);
SetAuraFlag(slot, true);
SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
UpdateAuraApplication();
// update for out of range group members
m_target->UpdateAuraForGroup(slot);
UpdateAuraDuration();
}
//*****************************************************
// Update target aura state flag (at 1 aura apply)
// TODO: Make it easer
//*****************************************************
// Sitdown on apply aura req seated
if (m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !m_target->IsSitState())
m_target->SetStandState(UNIT_STAND_STATE_SIT);
// register aura diminishing on apply
if (getDiminishGroup() != DIMINISHING_NONE)
m_target->ApplyDiminishingAura(getDiminishGroup(), true);
// Update Seals information
if (IsSealSpell(GetSpellProto()))
m_target->ModifyAuraState(AURA_STATE_JUDGEMENT, true);
// Conflagrate aura state
if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_WARLOCK, UI64LIT(0x0000000000000004)))
m_target->ModifyAuraState(AURA_STATE_CONFLAGRATE, true);
// Faerie Fire (druid versions)
if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000400)))
m_target->ModifyAuraState(AURA_STATE_FAERIE_FIRE, true);
// Swiftmend state on Regrowth & Rejuvenation
if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000050)))
m_target->ModifyAuraState(AURA_STATE_SWIFTMEND, true);
// Deadly poison aura state
if (m_spellProto->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000010000)))
m_target->ModifyAuraState(AURA_STATE_DEADLY_POISON, true);
}
void SpellAuraHolder::_RemoveSpellAuraHolder()
{
// Remove all triggered by aura spells vs unlimited duration
// except same aura replace case
if (m_removeMode != AURA_REMOVE_BY_STACK)
CleanupTriggeredSpells();
Unit* caster = GetCaster();
if (caster && IsPersistent())
if (DynamicObject* dynObj = caster->GetDynObject(GetId()))
dynObj->RemoveAffected(m_target);
// remove at-store spell cast items (for all remove modes?)
if (m_target->GetTypeId() == TYPEID_PLAYER && m_removeMode != AURA_REMOVE_BY_DEFAULT && m_removeMode != AURA_REMOVE_BY_DELETE)
if (ObjectGuid castItemGuid = GetCastItemGuid())
if (Item* castItem = ((Player*)m_target)->GetItemByGuid(castItemGuid))
((Player*)m_target)->DestroyItemWithOnStoreSpell(castItem, GetId());
// passive auras do not get put in slots - said who? ;)
// Note: but totem can be not accessible for aura target in time remove (to far for find in grid)
// if(m_isPassive && !(caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem()))
// return;
uint8 slot = GetAuraSlot();
if (slot >= MAX_AURAS) // slot not set
return;
if (m_target->GetUInt32Value((uint16)(UNIT_FIELD_AURA + slot)) == 0)
return;
// unregister aura diminishing (and store last time)
if (getDiminishGroup() != DIMINISHING_NONE)
m_target->ApplyDiminishingAura(getDiminishGroup(), false);
SetAura(slot, true);
SetAuraFlag(slot, false);
SetAuraLevel(slot, caster ? caster->getLevel() : sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL));
m_procCharges = 0;
m_stackAmount = 1;
UpdateAuraApplication();
if (m_removeMode != AURA_REMOVE_BY_DELETE)
{
// update for out of range group members
m_target->UpdateAuraForGroup(slot);
//*****************************************************
// Update target aura state flag (at last aura remove)
//*****************************************************
uint32 removeState = 0;
ClassFamilyMask removeFamilyFlag = m_spellProto->SpellFamilyFlags;
switch (m_spellProto->SpellFamilyName)
{
case SPELLFAMILY_PALADIN:
if (IsSealSpell(m_spellProto))
removeState = AURA_STATE_JUDGEMENT; // Update Seals information
break;
case SPELLFAMILY_WARLOCK:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000004)))
removeState = AURA_STATE_CONFLAGRATE; // Conflagrate aura state
break;
case SPELLFAMILY_DRUID:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000400)))
removeState = AURA_STATE_FAERIE_FIRE; // Faerie Fire (druid versions)
else if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000050)))
{
removeFamilyFlag = ClassFamilyMask(UI64LIT(0x00000000000050));
removeState = AURA_STATE_SWIFTMEND; // Swiftmend aura state
}
break;
case SPELLFAMILY_ROGUE:
if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000010000)))
removeState = AURA_STATE_DEADLY_POISON; // Deadly poison aura state
break;
}
// Remove state (but need check other auras for it)
if (removeState)
{
bool found = false;
Unit::SpellAuraHolderMap const& holders = m_target->GetSpellAuraHolderMap();
for (Unit::SpellAuraHolderMap::const_iterator i = holders.begin(); i != holders.end(); ++i)
{
SpellEntry const* auraSpellInfo = (*i).second->GetSpellProto();
if (auraSpellInfo->IsFitToFamily(SpellFamily(m_spellProto->SpellFamilyName), removeFamilyFlag))
{
found = true;
break;
}
}
// this has been last aura
if (!found)
m_target->ModifyAuraState(AuraState(removeState), false);
}
// reset cooldown state for spells
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
if (GetSpellProto()->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE))
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases)
((Player*)caster)->SendCooldownEvent(GetSpellProto());
}
}
}
void SpellAuraHolder::CleanupTriggeredSpells()
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (!m_spellProto->EffectApplyAuraName[i])
continue;
uint32 tSpellId = m_spellProto->EffectTriggerSpell[i];
if (!tSpellId)
continue;
SpellEntry const* tProto = sSpellStore.LookupEntry(tSpellId);
if (!tProto)
continue;
if (GetSpellDuration(tProto) != -1)
continue;
// needed for spell 43680, maybe others
// TODO: is there a spell flag, which can solve this in a more sophisticated way?
if (m_spellProto->EffectApplyAuraName[i] == SPELL_AURA_PERIODIC_TRIGGER_SPELL &&
GetSpellDuration(m_spellProto) == int32(m_spellProto->EffectAmplitude[i]))
continue;
m_target->RemoveAurasDueToSpell(tSpellId);
}
}
bool SpellAuraHolder::ModStackAmount(int32 num)
{
uint32 protoStackAmount = m_spellProto->StackAmount;
// Can`t mod
if (!protoStackAmount)
return true;
// Modify stack but limit it
int32 stackAmount = m_stackAmount + num;
if (stackAmount > (int32)protoStackAmount)
stackAmount = protoStackAmount;
else if (stackAmount <= 0) // Last aura from stack removed
{
m_stackAmount = 0;
return true; // need remove aura
}
// Update stack amount
SetStackAmount(stackAmount);
return false;
}
void SpellAuraHolder::SetStackAmount(uint32 stackAmount)
{
Unit* target = GetTarget();
Unit* caster = GetCaster();
if (!target || !caster)
return;
bool refresh = stackAmount >= m_stackAmount;
if (stackAmount != m_stackAmount)
{
m_stackAmount = stackAmount;
UpdateAuraApplication();
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (Aura* aur = m_auras[i])
{
int32 bp = aur->GetBasePoints();
int32 amount = m_stackAmount * caster->CalculateSpellDamage(target, m_spellProto, SpellEffectIndex(i), &bp);
// Reapply if amount change
if (amount != aur->GetModifier()->m_amount)
{
aur->ApplyModifier(false, true);
aur->GetModifier()->m_amount = amount;
aur->ApplyModifier(true, true);
}
}
}
}
if (refresh)
// Stack increased refresh duration
RefreshHolder();
}
Unit* SpellAuraHolder::GetCaster() const
{
if (GetCasterGuid() == m_target->GetObjectGuid())
return m_target;
return ObjectAccessor::GetUnit(*m_target, m_casterGuid);// player will search at any maps
}
bool SpellAuraHolder::IsWeaponBuffCoexistableWith(SpellAuraHolder const* ref) const
{
// only item casted spells
if (!GetCastItemGuid())
return false;
// Exclude Debuffs
if (!IsPositive())
return false;
// Exclude Non-generic Buffs and Executioner-Enchant
if (GetSpellProto()->SpellFamilyName != SPELLFAMILY_GENERIC || GetId() == 42976)
return false;
// Exclude Stackable Buffs [ie: Blood Reserve]
if (GetSpellProto()->StackAmount)
return false;
// only self applied player buffs
if (m_target->GetTypeId() != TYPEID_PLAYER || m_target->GetObjectGuid() != GetCasterGuid())
return false;
Item* castItem = ((Player*)m_target)->GetItemByGuid(GetCastItemGuid());
if (!castItem)
return false;
// Limit to Weapon-Slots
if (!castItem->IsEquipped() ||
(castItem->GetSlot() != EQUIPMENT_SLOT_MAINHAND && castItem->GetSlot() != EQUIPMENT_SLOT_OFFHAND))
return false;
// form different weapons
return ref->GetCastItemGuid() && ref->GetCastItemGuid() != GetCastItemGuid();
}
bool SpellAuraHolder::IsNeedVisibleSlot(Unit const* caster) const
{
bool totemAura = caster && caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem();
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (!m_auras[i])
continue;
// special area auras cases
switch (m_spellProto->Effect[i])
{
case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY:
return m_target != caster;
case SPELL_EFFECT_APPLY_AREA_AURA_PET:
case SPELL_EFFECT_APPLY_AREA_AURA_OWNER:
case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND:
case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
// passive auras (except totem auras) do not get placed in caster slot
return (m_target != caster || totemAura || !m_isPassive) && m_auras[i]->GetModifier()->m_auraname != SPELL_AURA_NONE;
default:
break;
}
}
// passive auras (except totem auras) do not get placed in the slots
return !m_isPassive || totemAura;
}
void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply)
{
uint32 spellId1 = 0;
uint32 spellId2 = 0;
uint32 spellId3 = 0;
uint32 spellId4 = 0;
switch (GetSpellProto()->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
switch (GetId())
{
case 11189: // Frost Warding
case 28332:
{
if (m_target->GetTypeId() == TYPEID_PLAYER && !apply)
{
// reflection chance (effect 1) of Frost Ward, applied in dummy effect
if (SpellModifier* mod = ((Player*)m_target)->GetSpellMod(SPELLMOD_EFFECT2, GetId()))
((Player*)m_target)->AddSpellMod(mod, false);
}
return;
}
default:
return;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
if (!apply)
{
// Remove Blood Frenzy only if target no longer has any Deep Wound or Rend (applying is handled by procs)
if (GetSpellProto()->Mechanic != MECHANIC_BLEED)
return;
// If target still has one of Warrior's bleeds, do nothing
Unit::AuraList const& PeriodicDamage = m_target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
for (Unit::AuraList::const_iterator i = PeriodicDamage.begin(); i != PeriodicDamage.end(); ++i)
if ((*i)->GetCasterGuid() == GetCasterGuid() &&
(*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARRIOR &&
(*i)->GetSpellProto()->Mechanic == MECHANIC_BLEED)
return;
spellId1 = 30069; // Blood Frenzy (Rank 1)
spellId2 = 30070; // Blood Frenzy (Rank 2)
}
else
return;
break;
}
case SPELLFAMILY_HUNTER:
{
switch (GetId())
{
// The Beast Within and Bestial Wrath - immunity
case 19574:
case 34471:
{
spellId1 = 24395;
spellId2 = 24396;
spellId3 = 24397;
spellId4 = 26592;
break;
}
// Misdirection, main spell
case 34477:
{
if (!apply)
m_target->getHostileRefManager().ResetThreatRedirection();
return;
}
default:
return;
}
break;
}
default:
return;
}
// prevent aura deletion, specially in multi-boost case
SetInUse(true);
if (apply)
{
if (spellId1)
m_target->CastSpell(m_target, spellId1, true, NULL, NULL, GetCasterGuid());
if (spellId2 && !IsDeleted())
m_target->CastSpell(m_target, spellId2, true, NULL, NULL, GetCasterGuid());
if (spellId3 && !IsDeleted())
m_target->CastSpell(m_target, spellId3, true, NULL, NULL, GetCasterGuid());
if (spellId4 && !IsDeleted())
m_target->CastSpell(m_target, spellId4, true, NULL, NULL, GetCasterGuid());
}
else
{
if (spellId1)
m_target->RemoveAurasByCasterSpell(spellId1, GetCasterGuid());
if (spellId2)
m_target->RemoveAurasByCasterSpell(spellId2, GetCasterGuid());
if (spellId3)
m_target->RemoveAurasByCasterSpell(spellId3, GetCasterGuid());
if (spellId4)
m_target->RemoveAurasByCasterSpell(spellId4, GetCasterGuid());
}
SetInUse(false);
}
SpellAuraHolder::~SpellAuraHolder()
{
// note: auras in delete list won't be affected since they clear themselves from holder when adding to deletedAuraslist
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
delete aur;
}
void SpellAuraHolder::Update(uint32 diff)
{
if (m_duration > 0)
{
m_duration -= diff;
if (m_duration < 0)
m_duration = 0;
m_timeCla -= diff;
if (m_timeCla <= 0)
{
if (Unit* caster = GetCaster())
{
Powers powertype = Powers(GetSpellProto()->powerType);
int32 manaPerSecond = GetSpellProto()->manaPerSecond + GetSpellProto()->manaPerSecondPerLevel * caster->getLevel();
m_timeCla = 1 * IN_MILLISECONDS;
if (manaPerSecond)
{
if (powertype == POWER_HEALTH)
caster->ModifyHealth(-manaPerSecond);
else
caster->ModifyPower(powertype, -manaPerSecond);
}
}
}
}
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aura = m_auras[i])
aura->UpdateAura(diff);
// Channeled aura required check distance from caster
if (IsChanneledSpell(m_spellProto) && GetCasterGuid() != m_target->GetObjectGuid())
{
Unit* caster = GetCaster();
if (!caster)
{
m_target->RemoveAurasByCasterSpell(GetId(), GetCasterGuid());
return;
}
// need check distance for channeled target only
if (caster->GetChannelObjectGuid() == m_target->GetObjectGuid())
{
// Get spell range
float max_range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellProto->rangeIndex));
if (Player* modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(GetId(), SPELLMOD_RANGE, max_range, NULL);
if (!caster->IsWithinDistInMap(m_target, max_range))
{
caster->InterruptSpell(CURRENT_CHANNELED_SPELL);
return;
}
}
}
}
void SpellAuraHolder::RefreshHolder()
{
SetAuraDuration(GetAuraMaxDuration());
UpdateAuraDuration();
}
void SpellAuraHolder::SetAuraMaxDuration(int32 duration)
{
m_maxDuration = duration;
// possible overwrite persistent state
if (duration > 0)
{
if (!(IsPassive() && GetSpellProto()->DurationIndex == 0))
SetPermanent(false);
}
}
bool SpellAuraHolder::HasMechanic(uint32 mechanic) const
{
if (mechanic == m_spellProto->Mechanic)
return true;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i] && m_spellProto->EffectMechanic[i] == mechanic)
return true;
return false;
}
bool SpellAuraHolder::HasMechanicMask(uint32 mechanicMask) const
{
if (mechanicMask & (1 << (m_spellProto->Mechanic - 1)))
return true;
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i] && m_spellProto->EffectMechanic[i] && ((1 << (m_spellProto->EffectMechanic[i] - 1)) & mechanicMask))
return true;
return false;
}
bool SpellAuraHolder::IsPersistent() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (aur->IsPersistent())
return true;
return false;
}
bool SpellAuraHolder::IsAreaAura() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (aur->IsAreaAura())
return true;
return false;
}
bool SpellAuraHolder::IsPositive() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (Aura* aur = m_auras[i])
if (!aur->IsPositive())
return false;
return true;
}
bool SpellAuraHolder::IsEmptyHolder() const
{
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
if (m_auras[i])
return false;
return true;
}
void SpellAuraHolder::UnregisterAndCleanupTrackedAuras()
{
TrackedAuraType trackedType = GetTrackedAuraType();
if (!trackedType)
return;
if (trackedType == TRACK_AURA_TYPE_SINGLE_TARGET)
{
if (Unit* caster = GetCaster())
caster->GetTrackedAuraTargets(trackedType).erase(GetSpellProto());
}
m_trackedAuraType = TRACK_AURA_TYPE_NOT_TRACKED;
}
void SpellAuraHolder::SetAuraFlag(uint32 slot, bool add)
{
uint32 index = slot / 4;
uint32 byte = (slot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAFLAGS + index);
val &= ~((uint32)AFLAG_MASK << byte);
if (add)
{
if (IsPositive())
val |= ((uint32)AFLAG_POSITIVE << byte);
else
val |= ((uint32)AFLAG_NEGATIVE << byte);
}
m_target->SetUInt32Value(UNIT_FIELD_AURAFLAGS + index, val);
}
void SpellAuraHolder::SetAuraLevel(uint32 slot, uint32 level)
{
uint32 index = slot / 4;
uint32 byte = (slot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURALEVELS + index);
val &= ~(0xFF << byte);
val |= (level << byte);
m_target->SetUInt32Value(UNIT_FIELD_AURALEVELS + index, val);
}
void SpellAuraHolder::UpdateAuraApplication()
{
if (m_auraSlot >= MAX_AURAS)
return;
uint32 stackCount = m_procCharges > 0 ? m_procCharges * m_stackAmount : m_stackAmount;
uint32 index = m_auraSlot / 4;
uint32 byte = (m_auraSlot % 4) * 8;
uint32 val = m_target->GetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index);
val &= ~(0xFF << byte);
// field expect count-1 for proper amount show, also prevent overflow at client side
val |= ((uint8(stackCount <= 255 ? stackCount - 1 : 255 - 1)) << byte);
m_target->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS + index, val);
}
void SpellAuraHolder::UpdateAuraDuration()
{
if (GetAuraSlot() >= MAX_AURAS || m_isPassive)
return;
if (m_target->GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_UPDATE_AURA_DURATION, 5);
data << uint8(GetAuraSlot());
data << uint32(GetAuraDuration());
((Player*)m_target)->SendDirectMessage(&data);
data.Initialize(SMSG_SET_EXTRA_AURA_INFO, (8 + 1 + 4 + 4 + 4));
data << m_target->GetPackGUID();
data << uint8(GetAuraSlot());
data << uint32(GetId());
data << uint32(GetAuraMaxDuration());
data << uint32(GetAuraDuration());
((Player*)m_target)->SendDirectMessage(&data);
}
// not send in case player loading (will not work anyway until player not added to map), sent in visibility change code
if (m_target->GetTypeId() == TYPEID_PLAYER && ((Player*)m_target)->GetSession()->PlayerLoading())
return;
Unit* caster = GetCaster();
if (caster && caster->GetTypeId() == TYPEID_PLAYER && caster != m_target)
SendAuraDurationForCaster((Player*)caster);
}
void SpellAuraHolder::SendAuraDurationForCaster(Player* caster)
{
WorldPacket data(SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE, (8 + 1 + 4 + 4 + 4));
data << m_target->GetPackGUID();
data << uint8(GetAuraSlot());
data << uint32(GetId());
data << uint32(GetAuraMaxDuration()); // full
data << uint32(GetAuraDuration()); // remain
caster->GetSession()->SendPacket(&data);
}
| blueboy/portalone | src/game/SpellAuras.cpp | C++ | gpl-2.0 | 309,536 |
<?php
/*
*
* Copyright 2001-2012 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun
*
* This file is part of GEPI.
*
* GEPI 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.
*
* GEPI 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 GEPI; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// On indique qu'il faut creer des variables non protégées (voir fonction cree_variables_non_protegees())
$variables_non_protegees = 'yes';
// Begin standart header
$titre_page = "Saisie de commentaires-types";
// Initialisations files
require_once("../lib/initialisations.inc.php");
// Resume session
$resultat_session = $session_gepi->security_check();
if ($resultat_session == 'c') {
header("Location: ../utilisateurs/mon_compte.php?change_mdp=yes");
die();
} else if ($resultat_session == '0') {
header("Location: ../logout.php?auto=1");
die();
}
// Check access
// INSERT INTO droits VALUES ('/saisie/commentaires_types.php', 'V', 'V', 'V', 'V', 'F', 'F', 'V', 'Saisie de commentaires-types', '');
if (!checkAccess()) {
header("Location: ../logout.php?auto=1");
die();
}
//==========================================
// End standart header
require_once("../lib/header.inc.php");
if (!loadSettings()) {
die("Erreur chargement settings");
}
//==========================================
$sql="CREATE TABLE IF NOT EXISTS `commentaires_types` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`commentaire` TEXT NOT NULL ,
`num_periode` INT NOT NULL ,
`id_classe` INT NOT NULL
) ENGINE=MyISAM CHARACTER SET utf8 COLLATE utf8_general_ci;";
$resultat_creation_table=mysqli_query($GLOBALS["mysqli"], $sql);
function get_classe_from_id($id){
//$sql="SELECT * FROM classes WHERE id='$id_classe[0]'";
$sql="SELECT * FROM classes WHERE id='$id'";
$resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classe)!=1){
//echo "<p>ERREUR! La classe d'identifiant '$id_classe[0]' n'a pas pu être identifiée.</p>";
echo "<p>ERREUR! La classe d'identifiant '$id' n'a pas pu être identifiée.</p>";
}
else{
$ligne_classe=mysqli_fetch_object($resultat_classe);
$classe=$ligne_classe->classe;
return $classe;
}
}
?>
<p class="bold"><a href="../accueil.php">Retour</a>
| <a href="commentaires_types.php">Saisir des commentaires</a>
| <a href="commentaires_types.php?recopie=oui">Recopier des commentaires</a>
</p>
<?php
/*
if ((($_SESSION['statut']=='professeur') AND ((getSettingValue("GepiProfImprBul")!='yes') OR ((getSettingValue("GepiProfImprBul")=='yes') AND (getSettingValue("GepiProfImprBulSettings")!='yes')))) OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("GepiScolImprBulSettings")!='yes')) OR (($_SESSION['statut']=='administrateur') AND (getSettingValue("GepiAdminImprBulSettings")!='yes')))
{
die("Droits insuffisants pour effectuer cette opération");
}
*/
if ((($_SESSION['statut']=='professeur') AND (getSettingValue("CommentairesTypesPP")=='yes') AND (mysqli_num_rows(mysqli_query($GLOBALS["mysqli"], "SELECT 1=1 FROM j_eleves_professeurs WHERE professeur='".$_SESSION['login']."'"))>0))
OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("CommentairesTypesScol")=='yes'))
OR (($_SESSION['statut']=='cpe') AND (getSettingValue("CommentairesTypesCpe")=='yes'))
)
{
// Accès autorisé à la page
}
else{
die("Droits insuffisants pour effectuer cette opération");
}
?>
<form name="formulaire" action="commentaires_types.php" method="post">
<?php
echo add_token_field();
//echo "\$_GET['recopie']=".$_GET['recopie']."<br />";
$recopie=isset($_GET['recopie']) ? $_GET['recopie'] : (isset($_POST['recopie']) ? $_POST['recopie'] : "");
//echo "\$recopie=$recopie<br />";
if($recopie!="oui"){
// =============================================
// Définition/modification des commentaires-type
// =============================================
if(!isset($_POST['id_classe'])){
// Choix de la classe
//echo "<p>Pour quelle classe et quelles périodes souhaitez-vous définir/modifier les commentaires-type?</p>\n";
echo "<p>Pour quelle classe souhaitez-vous définir/modifier les commentaires-type?</p>\n";
echo "<blockquote>\n";
// A REVOIR: Il ne faut lister que les classes appropriées.
//$sql="select distinct id,classe from classes order by classe";
// if ((($_SESSION['statut']=='professeur') AND (getSettingValue("CommentairesTypesPP")=='yes') AND (mysql_num_rows(mysql_query("SELECT 1=1 FROM j_eleves_professeurs WHERE professeur='".$_SESSION['login']."'"))>0))
// OR (($_SESSION['statut']=='scolarite') AND (getSettingValue("CommentairesTypesScol")=='yes')))
if($_SESSION['statut']=='professeur'){
$sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_classes jec, classes c, j_eleves_professeurs jep
WHERE jec.id_classe=c.id AND
jec.login=jep.login AND
jep.professeur='".$_SESSION['login']."'
ORDER BY c.classe";
}
elseif($_SESSION['statut']=='scolarite'){
$sql="SELECT DISTINCT c.id,c.classe FROM j_scol_classes jsc, classes c
WHERE jsc.id_classe=c.id AND
jsc.login='".$_SESSION['login']."'
ORDER BY c.classe";
}
elseif(($_SESSION['statut']=='cpe')&&(getSettingAOui('GepiRubConseilCpe'))) {
$sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_cpe jecpe, j_eleves_classes jec, classes c
WHERE jec.id_classe=c.id AND
jec.login=jecpe.e_login AND
jecpe.cpe_login='".$_SESSION['login']."'
ORDER BY c.classe";
}
elseif(($_SESSION['statut']=='cpe')&&(getSettingAOui('GepiRubConseilCpeTous'))) {
$sql="select distinct id,classe from classes order by classe";
}
else {
// CA NE DEVRAIT PAS ARRIVER...
//$sql="select distinct id,classe from classes order by classe";
echo "<p>Statut incorrect.</p>\n";
die();
require("../lib/footer.inc.php");
}
$resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classes)==0){
echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n";
exit();
}
/*
$cpt=0;
while($ligne_classe=mysql_fetch_object($resultat_classes)){
if($cpt==0){
$checked="checked ";
}
else{
$checked="";
}
//echo "<input type='radio' name='id_classe' value='$ligne_classe->id' $checked/> $ligne_classe->classe<br />\n";
echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' $checked/><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n";
$cpt++;
}
*/
$nb_classes=mysqli_num_rows($resultat_classes);
$nb_class_par_colonne=round($nb_classes/3);
echo "<table width='100%'>\n";
echo "<tr valign='top' align='center'>\n";
$cpt=0;
//echo "<td style='padding: 0 10px 0 10px'>\n";
echo "<td align='left'>\n";
while($ligne_classe=mysqli_fetch_object($resultat_classes)){
if(($cpt>0)&&(round($cpt/$nb_class_par_colonne)==$cpt/$nb_class_par_colonne)){
echo "</td>\n";
//echo "<td style='padding: 0 10px 0 10px'>\n";
echo "<td align='left'>\n";
}
if($cpt==0){
$checked="checked ";
}
else{
$checked="";
}
//echo "<input type='radio' name='id_classe' value='$ligne_classe->id' /> $ligne_classe->classe<br />\n";
echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' $checked/><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n";
$cpt++;
}
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</blockquote>\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
}
else{
if(!isset($_POST['num_periode'])){
// ==================
// Choix des périodes
// ==================
// Récupération des variables:
$id_classe=$_POST['id_classe'];
//echo "\$id_classe=$id_classe<br />\n";
echo "<h2>Saisie/Modification des commentaires-types pour la classe de ".get_classe_from_id($id_classe)."</h2>\n";
// Rappel des commentaires-type saisis pour cette classe sur toutes les périodes définies:
$sql="select * from periodes where id_classe='$id_classe' order by num_periode";
//echo "$sql<br />";
$resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_num_periode)==0){
echo "Aucune période n'est encore définie pour cette classe...<br />\n";
echo "</body>\n</html>\n";
exit();
}
else{
echo "<p>Voici les commentaires-type actuellement saisis pour cette classe:</p>\n";
echo "<ul>\n";
while($ligne_periode=mysqli_fetch_object($resultat_num_periode)){
//for($i=0;$i<count($num_periode);$i++){
echo "<li>\n";
//$sql="select nom_periode from periodes where num_periode='$ligne_periode->num_periode'";
//$resultat_periode=mysql_query($sql);
//$ligne_nom_periode=mysql_fetch_object($resultat_periode);
//echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<p><b>$ligne_periode->nom_periode</b>:</p>\n";
// AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE
$sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$ligne_periode->num_periode' order by commentaire";
$resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_commentaires)>0){
echo "<ul>\n";
while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){
echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n";
}
echo "</ul>\n";
}
else{
echo "<p style='color:red;'>Aucun commentaire-type n'est saisi pour cette classe sur cette période.</p>\n";
}
echo "</li>\n";
}
echo "</ul>\n";
}
// Choix des périodes:
echo "<p>Pour quelles périodes souhaitez-vous définir/modifier les commentaires-type?</p>\n";
//echo "<p>\n";
echo "<input type='hidden' name='id_classe' value='$id_classe' />\n";
// Récupération du nom de la classe
$sql="select * from classes where id='$id_classe'";
$resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classe)==0){
echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n";
exit();
}
$ligne_classe=mysqli_fetch_object($resultat_classe);
$classe_courante="$ligne_classe->classe";
echo "<p><b>$classe_courante</b>: ";
$sql="select * from periodes where id_classe='$id_classe' order by num_periode";
//echo "$sql<br />";
$resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_num_periode)==0){
echo "Aucune période n'est encore définie pour cette classe...<br />\n";
}
else{
/*
$ligne_num_periode=mysql_fetch_object($resultat_num_periode);
$sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'";
$resultat_periode=mysql_query($sql);
$ligne_periode=mysql_fetch_object($resultat_periode);
//echo "<input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n";
echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n";
while($ligne_num_periode=mysql_fetch_object($resultat_num_periode)){
//$cpt++;
$sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'";
$resultat_periode=mysql_query($sql);
$ligne_periode=mysql_fetch_object($resultat_periode);
//echo " - <input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n";
echo " - <input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n";
}
*/
$cpt_per=0;
while($ligne_num_periode=mysqli_fetch_object($resultat_num_periode)){
if($cpt_per>0) {echo " - ";}
echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_num_periode->num_periode."' value='$ligne_num_periode->num_periode' /><label for='num_periode_".$ligne_num_periode->num_periode."' style='cursor: pointer;'> $ligne_num_periode->nom_periode</label>\n";
$cpt_per++;
}
echo "<br />\n";
}
echo "</p>\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
}
else {
check_token(false);
// ==============================================================
// Saisie, modification, suppression, validation des commentaires
// ==============================================================
// Récupération des variables:
$id_classe=$_POST['id_classe'];
$num_periode=$_POST['num_periode'];
$suppr=isset($_POST['suppr']) ? $_POST['suppr'] : "";
/*
$nom_log = "app_eleve_".$k."_".$i;
//echo "\$nom_log=$nom_log<br />";
if (isset($NON_PROTECT[$nom_log])){
$app = traitement_magic_quotes(corriger_caracteres($NON_PROTECT[$nom_log]));
}
else{
$app = "";
}
*/
$compteur_nb_commentaires=isset($_POST['compteur_nb_commentaires']) ? $_POST['compteur_nb_commentaires'] : NULL;
//if(isset($_POST['commentaire_1'])){
if(isset($compteur_nb_commentaires)){
//if(isset($_POST['commentaire'])){
// Récupération des variables:
//$commentaire=$_POST['commentaire'];
//$commentaire=html_entity_decode($_POST['commentaire']);
// Nettoyage des commentaires déjà saisis pour cette classe et ces périodes:
$sql="delete from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'";
for($i=1;$i<count($num_periode);$i++){
$sql=$sql." or num_periode='$num_periode[$i]'";
}
$sql=$sql.")";
//echo "sql=$sql<br />";
$resultat_nettoyage=mysqli_query($GLOBALS["mysqli"], $sql);
// Validation des saisies/modifs...
//for($i=1;$i<=count($commentaire);$i++){
for($i=1;$i<=$compteur_nb_commentaires;$i++){
//echo "\$suppr[$i]=$suppr[$i]<br />";
//if(($suppr[$i]=="")&&($commentaire[$i]!="")){
//if((!isset($suppr[$i]))&&($commentaire[$i]!="")){
if(!isset($suppr[$i])) {
$nom_log = "commentaire_".$i;
if (isset($NON_PROTECT[$nom_log])){
$commentaire_courant = traitement_magic_quotes(corriger_caracteres($NON_PROTECT[$nom_log]));
if($commentaire_courant!=""){
for($j=0;$j<count($num_periode);$j++){
//$sql="insert into commentaires_types values('','$commentaire[$i]','$num_periode[$j]','$id_classe')";
//=========================
// MODIF: boireaus 20071121
//$sql="insert into commentaires_types values('','".html_entity_decode($commentaire[$i])."','$num_periode[$j]','$id_classe')";
//$tmp_commentaire=my_ereg_replace("'","'",html_entity_decode($commentaire[$i]));
//$sql="insert into commentaires_types values('','".addslashes($tmp_commentaire)."','$num_periode[$j]','$id_classe')";
//$sql="insert into commentaires_types values('','".addslashes($commentaire_courant)."','$num_periode[$j]','$id_classe')";
$sql="insert into commentaires_types values('','".$commentaire_courant."','$num_periode[$j]','$id_classe')";
//=========================
//echo "sql=$sql<br />";
$resultat_insertion_commentaire=mysqli_query($GLOBALS["mysqli"], $sql);
}
}
}
}
}
}
echo "<input type='hidden' name='id_classe' value='$id_classe' />\n";
/*
echo "$id_classe: ";
for($i=0;$i<count($num_periode);$i++){
echo "$num_periode[$i] -";
}
echo "<br />";
*/
// Récupération du nom de la classe
$sql="select * from classes where id='$id_classe'";
$resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classe)==0){
echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n";
exit();
}
$ligne_classe=mysqli_fetch_object($resultat_classe);
$classe_courante="$ligne_classe->classe";
//echo "<p><b>Classe de $classe_courante</b></p>\n";
echo "<h2>Classe de $classe_courante</h2>\n";
// Recherche des commentaires déjà saisis:
//$sql="select * from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'";
//$sql="select distinct commentaire,id from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'";
$sql="select distinct commentaire,id from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'";
echo "<input type='hidden' name='num_periode[0]' value='$num_periode[0]' />\n";
for($i=1;$i<count($num_periode);$i++){
$sql=$sql." or num_periode='$num_periode[$i]'";
echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]' />\n";
}
//$sql=$sql.")";
$sql=$sql.") order by commentaire";
//echo "$sql";
$resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql);
$cpt=1;
if(mysqli_num_rows($resultat_commentaires)!=0){
echo "<p>Voici la liste des commentaires-type existants pour la classe et la/les période(s) choisie(s):</p>\n";
echo "<blockquote>\n";
echo "<table class='boireaus' border='1'>\n";
echo "<tr style='text-align:center;'>\n";
echo "<th>Commentaire</th>\n";
echo "<th>Supprimer</th>\n";
echo "</tr>\n";
$precedent_commentaire="";
//$cpt=1;
$alt=1;
while($ligne_commentaire=mysqli_fetch_object($resultat_commentaires)){
if("$ligne_commentaire->commentaire"!="$precedent_commentaire"){
$alt=$alt*(-1);
echo "<tr class='lig$alt' style='text-align:center;'>\n";
echo "<td>";
//echo "<textarea name='commentaire[$cpt]' cols='60'>".stripslashes($ligne_commentaire->commentaire)."</textarea>";
echo "<textarea name='no_anti_inject_commentaire_".$cpt."' cols='60' onchange='changement()'>".stripslashes($ligne_commentaire->commentaire)."</textarea>";
echo "</td>\n";
echo "<td><input type='checkbox' name='suppr[$cpt]' value='$ligne_commentaire->id' /></td>\n";
echo "</tr>\n";
$cpt++;
$precedent_commentaire="$ligne_commentaire->commentaire";
}
}
echo "</table>\n";
echo "</blockquote>\n";
}
echo "<p>Saisie d'un nouveau commentaire:</p>";
echo "<blockquote>\n";
//echo "<textarea name='commentaire[$cpt]' cols='60'></textarea><br />\n";
echo "<textarea name='no_anti_inject_commentaire_".$cpt."' id='no_anti_inject_commentaire_".$cpt."' cols='60' onchange='changement()'></textarea><br />\n";
echo "<input type='hidden' name='compteur_nb_commentaires' value='$cpt' />\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
echo "</blockquote>\n";
echo "<script type='text/javascript'>
document.getElementById('no_anti_inject_commentaire_".$cpt."').focus();
</script>\n";
}
}
}
else{
//==================================================================
// ==============================================================
// ============================
// Recopie de commentaires-type
// ============================
echo "<input type='hidden' name='recopie' value='oui' />\n";
if(!isset($_POST['id_classe'])){
// =========================
// Choix de la classe modèle
// =========================
echo "<p>De quelle classe souhaitez-vous recopier les commentaires-type?</p>\n";
echo "<blockquote>\n";
$sql="select distinct id,classe from classes order by classe";
$resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classes)==0){
echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n";
exit();
}
$nb_classes=mysqli_num_rows($resultat_classes);
$nb_class_par_colonne=round($nb_classes/3);
echo "<table width='100%'>\n";
echo "<tr valign='top' align='center'>\n";
$cpt=0;
//echo "<td style='padding: 0 10px 0 10px'>\n";
echo "<td align='left'>\n";
while($ligne_classe=mysqli_fetch_object($resultat_classes)){
if(($cpt>0)&&(round($cpt/$nb_class_par_colonne)==$cpt/$nb_class_par_colonne)){
echo "</td>\n";
//echo "<td style='padding: 0 10px 0 10px'>\n";
echo "<td align='left'>\n";
}
//echo "<input type='radio' name='id_classe' value='$ligne_classe->id' /> $ligne_classe->classe<br />\n";
echo "<input type='radio' name='id_classe' id='id_classe".$ligne_classe->id."' value='$ligne_classe->id' /><label for='id_classe".$ligne_classe->id."' style='cursor: pointer;'> $ligne_classe->classe</label><br />\n";
$cpt++;
}
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</blockquote>\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
}
else{
// ============================
// La classe-modèle est choisie
// ============================
// Récupération des variables:
$id_classe=$_POST['id_classe'];
echo "<h2>Recopie de commentaires-types</h2>\n";
/*
echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n";
echo "<ul>\n";
for($i=0;$i<count($num_periode);$i++){
echo "<li>\n";
$sql="select nom_periode from periodes where num_periode='$num_periode[$i]'";
$resultat_periode=mysql_query($sql);
$ligne_nom_periode=mysql_fetch_object($resultat_periode);
echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]'>\n";
// AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE
$sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire";
$resultat_commentaires=mysql_query($sql);
echo "<ul>\n";
while($ligne_commentaires=mysql_fetch_object($resultat_commentaires)){
echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n";
}
echo "</ul>\n";
echo "</li>\n";
}
echo "</ul>\n";
*/
echo "<input type='hidden' name='id_classe' value='$id_classe' />\n";
// Récupération du nom de la classe
$sql="select * from classes where id='$id_classe'";
$resultat_classe=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classe)==0){
echo "<p>L'identifiant de la classe semble erroné.</p>\n</form>\n</body>\n</html>\n";
exit();
}
$ligne_classe=mysqli_fetch_object($resultat_classe);
$classe_source="$ligne_classe->classe";
echo "<p><b>Classe modèle:</b> $classe_source</p>\n";
if(!isset($_POST['num_periode'])){
// =============================
// Choix des périodes à recopier
// =============================
// Rappel des commentaires-type saisis pour cette classe sur toutes les périodes définies:
$sql="select * from periodes where id_classe='$id_classe' order by num_periode";
//echo "$sql<br />";
$resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_num_periode)==0){
echo "Aucune période n'est encore définie pour cette classe...<br />\n";
echo "</body>\n</html>\n";
exit();
}
else{
$compteur_commentaires=0;
echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n";
echo "<ul>\n";
while($ligne_periode=mysqli_fetch_object($resultat_num_periode)){
//for($i=0;$i<count($num_periode);$i++){
echo "<li>\n";
//$sql="select nom_periode from periodes where num_periode='$ligne_periode->num_periode'";
//$resultat_periode=mysql_query($sql);
//$ligne_nom_periode=mysql_fetch_object($resultat_periode);
//echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<p><b>$ligne_periode->nom_periode</b>:</p>\n";
// AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE
$sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$ligne_periode->num_periode' order by commentaire";
$resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_commentaires)>0){
echo "<ul>\n";
while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){
echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n";
$compteur_commentaires++;
}
echo "</ul>\n";
}
else{
echo "<p style='color:red;'>Aucun commentaire-type n'est saisi pour cette classe sur cette période.</p>\n";
//echo "</body>\n</html>\n";
//exit();
}
echo "</li>\n";
}
echo "</ul>\n";
if($compteur_commentaires==0){
echo "</body>\n</html>\n";
exit();
}
}
// Choix des périodes:
echo "<p>Pour quelles périodes souhaitez-vous recopier les commentaires-type?</p>\n";
//echo "<p>\n";
//echo "<input type='hidden' name='id_classe' value='$id_classe'>\n";
//echo "<p><b>$classe_source</b>: ";
$sql="select * from periodes where id_classe='$id_classe' order by num_periode";
//echo "$sql<br />";
$resultat_num_periode=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_num_periode)==0){
echo "<p>Aucune période n'est encore définie pour cette classe...</p>\n";
}
else{
/*
$ligne_num_periode=mysql_fetch_object($resultat_num_periode);
$sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'";
$resultat_periode=mysql_query($sql);
$ligne_periode=mysql_fetch_object($resultat_periode);
//echo "<input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n";
echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n";
while($ligne_num_periode=mysql_fetch_object($resultat_num_periode)){
//$cpt++;
$sql="select * from periodes where num_periode='$ligne_num_periode->num_periode'";
$resultat_periode=mysql_query($sql);
$ligne_periode=mysql_fetch_object($resultat_periode);
//echo " - <input type='checkbox' name='num_periode[]' value='$ligne_periode->num_periode'> $ligne_periode->nom_periode\n";
echo " - <input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_periode->num_periode."' value='$ligne_periode->num_periode' /><label for='num_periode_".$ligne_periode->num_periode."' style='cursor: pointer;'> $ligne_periode->nom_periode</label>\n";
}
*/
$cpt_per=0;
while($ligne_num_periode=mysqli_fetch_object($resultat_num_periode)){
if($cpt_per>0) {echo " - ";}
echo "<input type='checkbox' name='num_periode[]' id='num_periode_".$ligne_num_periode->num_periode."' value='$ligne_num_periode->num_periode' /><label for='num_periode_".$ligne_num_periode->num_periode."' style='cursor: pointer;'> $ligne_num_periode->nom_periode</label>\n";
$cpt_per++;
}
echo "<br />\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
}
//echo "</p>\n";
//echo "<input type='submit' name='ok' value='Valider'>\n";
}
else{
// =========================================================
// La classe-modèle et les périodes à recopier sont choisies
// =========================================================
// Récupération des variables:
$num_periode=$_POST['num_periode'];
/*
echo "<p>Voici les commentaires-type saisis pour cette classe:</p>\n";
echo "<ul>\n";
for($i=0;$i<count($num_periode);$i++){
echo "<li>\n";
$sql="select nom_periode from periodes where num_periode='$num_periode[$i]'";
$resultat_periode=mysql_query($sql);
$ligne_nom_periode=mysql_fetch_object($resultat_periode);
echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]'>\n";
// AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE
$sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire";
$resultat_commentaires=mysql_query($sql);
echo "<ul>\n";
while($ligne_commentaires=mysql_fetch_object($resultat_commentaires)){
echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n";
}
echo "</ul>\n";
echo "</li>\n";
}
echo "</ul>\n";
*/
if(!isset($_POST['id_dest_classe'])){
// ==========================================================
// Choix des classes vers lesquelles la recopie doit se faire
// ==========================================================
echo "<p>Voici les commentaires-type saisis pour cette classe et les périodes choisies:</p>\n";
echo "<ul>\n";
for($i=0;$i<count($num_periode);$i++){
echo "<li>\n";
$sql="select nom_periode from periodes where num_periode='$num_periode[$i]'";
$resultat_periode=mysqli_query($GLOBALS["mysqli"], $sql);
$ligne_nom_periode=mysqli_fetch_object($resultat_periode);
echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<input type='hidden' name='num_periode[$i]' value='$num_periode[$i]' />\n";
// AFFICHER LES COMMENTAIRES-TYPE POUR CHAQUE PERIODE
$sql="select * from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire";
$resultat_commentaires=mysqli_query($GLOBALS["mysqli"], $sql);
echo "<ul>\n";
while($ligne_commentaires=mysqli_fetch_object($resultat_commentaires)){
echo "<li>".stripslashes(nl2br(trim($ligne_commentaires->commentaire)))."</li>\n";
}
echo "</ul>\n";
echo "</li>\n";
}
echo "</ul>\n";
echo "<p>Pour quelles classes souhaitez-vous supprimer les commentaires-type existant et les remplacer par ceux de $classe_source?</p>\n";
// AJOUTER UN JavaScript POUR 'Tout cocher'
//$sql="select distinct id,classe from classes order by classe";
if($_SESSION['statut']=='professeur'){
$sql="SELECT DISTINCT c.id,c.classe FROM j_eleves_classes jec, classes c, j_eleves_professeurs jep
WHERE jec.id_classe=c.id AND
jec.login=jep.login AND
jep.professeur='".$_SESSION['login']."'
ORDER BY c.classe";
}
elseif($_SESSION['statut']=='scolarite'){
$sql="SELECT DISTINCT c.id,c.classe FROM j_scol_classes jsc, classes c
WHERE jsc.id_classe=c.id AND
jsc.login='".$_SESSION['login']."'
ORDER BY c.classe";
}
else{
// CA NE DEVRAIT PAS ARRIVER...
$sql="select distinct id,classe from classes order by classe";
}
$resultat_classes=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_classes)==0){
echo "<p>Aucune classe n'est encore définie...</p>\n</form>\n</body>\n</html>\n";
exit();
}
$cpt=0;
while($ligne_classe=mysqli_fetch_object($resultat_classes)){
if("$ligne_classe->id"!="$id_classe"){
echo "<label for='id_dest_classe$cpt' style='cursor: pointer;'><input type='checkbox' name='id_dest_classe[]' id='id_dest_classe$cpt' value='$ligne_classe->id' /> $ligne_classe->classe</label><br />\n";
$cpt++;
}
}
//echo "</blockquote>\n";
echo "<!--script language='JavaScript'-->
<script language='JavaScript' type='text/javascript'>
function tout_cocher(){
for(i=0;i<$cpt;i++){
document.getElementById('id_dest_classe'+i).checked=true;
}
}
function tout_decocher(){
for(i=0;i<$cpt;i++){
document.getElementById('id_dest_classe'+i).checked=false;
}
}
</script>
";
echo "<input type='button' name='toutcocher' value='Tout cocher' onClick='tout_cocher();' /> - \n";
echo "<input type='button' name='toutdecocher' value='Tout décocher' onClick='tout_decocher();' />\n";
echo "<center><input type='submit' name='ok' value='Valider' /></center>\n";
}
else {
check_token(false);
// =======================
// Recopie proprement dite
// =======================
$id_dest_classe=$_POST['id_dest_classe'];
//echo count($num_periode)."<br />";
//flush();
// Nettoyage des commentaires déjà saisis pour ces classes et ces périodes:
for($i=0;$i<count($id_dest_classe);$i++){
$sql="delete from commentaires_types where id_classe='$id_dest_classe[$i]' and (num_periode='$num_periode[0]'";
//for($i=0;$i<count($num_periode);$i++){
for($j=1;$j<count($num_periode);$j++){
$sql=$sql." or num_periode='$num_periode[$j]'";
}
$sql=$sql.")";
//echo "sql=$sql<br />";
$resultat_nettoyage=mysqli_query($GLOBALS["mysqli"], $sql);
}
/*
$sql="select commentaire from commentaires_types where id_classe='$id_classe' and (num_periode='$num_periode[0]'";
for($i=1;$i<count($num_periode);$i++){
$sql=$sql." or num_periode='$num_periode[$i]'";
}
$sql=$sql.") order by commentaire";
echo "sql=$sql<br />";
$resultat_commentaires_source=mysql_query($sql);
if(mysql_num_rows($resultat_commentaires_source)==0){
echo "<p>C'est malin... il n'existe pas de commentaires-type pour la/les classe(s) et la/les période(s) choisie(s).<br />\nDe plus, les commentaires existants ont été supprimés...</p>\n";
}
else{
while($ligne_commentaires_source=mysql_fetch_object($resultat_commentaires_source)){
}
}
*/
for($i=0;$i<count($num_periode);$i++){
// Nom de la période courante:
$sql="select nom_periode from periodes where num_periode='$num_periode[$i]'";
$resultat_periode=mysqli_query($GLOBALS["mysqli"], $sql);
$ligne_nom_periode=mysqli_fetch_object($resultat_periode);
echo "<p><b>$ligne_nom_periode->nom_periode</b>:</p>\n";
echo "<blockquote>\n";
// Récupération des commentaires à insérer:
$sql="select commentaire from commentaires_types where id_classe='$id_classe' and num_periode='$num_periode[$i]' order by commentaire";
//echo "sql=$sql<br />";
$resultat_commentaires_source=mysqli_query($GLOBALS["mysqli"], $sql);
if(mysqli_num_rows($resultat_commentaires_source)==0){
echo "<p>C'est malin... il n'existe pas de commentaires-type pour la classe modèle et la période choisie.<br />\nDe plus, les commentaires existants pour les classes destination ont été supprimés...</p>\n";
}
else{
while($ligne_commentaires_source=mysqli_fetch_object($resultat_commentaires_source)){
echo "<table>\n";
for($j=0;$j<count($id_dest_classe);$j++){
// Récupération du nom de la classe:
$sql="select classe from classes where id='$id_dest_classe[$j]'";
$resultat_classe_dest=mysqli_query($GLOBALS["mysqli"], $sql);
$ligne_classe_dest=mysqli_fetch_object($resultat_classe_dest);
//echo "<b>Insertion pour $ligne_classe_dest->classe:</b><br /> ".stripslashes(nl2br(trim($ligne_commentaires_source->commentaire)))."<br />\n";
echo "<tr valign=\"top\"><td><b>Insertion pour $ligne_classe_dest->classe:</b></td><td> ".stripslashes(nl2br(trim($ligne_commentaires_source->commentaire)))."</td></tr>\n";
//$sql="insert into commentaires_types values('','$ligne_commentaires_source->commentaire','$num_periode[$i]','$id_dest_classe[$j]')";
$commentaire_courant=traitement_magic_quotes(corriger_caracteres($ligne_commentaires_source->commentaire));
$sql="insert into commentaires_types values('','$commentaire_courant','$num_periode[$i]','$id_dest_classe[$j]')";
//echo "sql=$sql<br />";
$resultat_insertion_commentaire=mysqli_query($GLOBALS["mysqli"], $sql);
}
echo "</table>\n";
}
echo "<p>Insertions terminées pour la période.</p>\n";
}
echo "</blockquote>\n";
}
/*
// Validation des saisies/modifs...
for($i=1;$i<=count($commentaire);$i++){
echo "\$suppr[$i]=$suppr[$i]<br />";
if(($suppr[$i]=="")&&($commentaire[$i]!="")){
for($j=0;$j<count($num_periode);$j++){
$sql="insert into commentaires_types values('','$commentaire[$i]','$num_periode[$j]','$id_classe')";
echo "sql=$sql<br />";
$resultat_insertion_commentaire=mysql_query($sql);
}
}
}
*/
}
}
}
}
?>
</form>
<p><br /></p>
<?php
require("../lib/footer.inc.php");
?>
| prunkdump/gepi | saisie/commentaires_types.php | PHP | gpl-2.0 | 38,738 |
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, p_i;
cin >> n;
double total = 0.0;
for (size_t i = 0; i < n; i++) {
cin >> p_i;
total += p_i;
}
cout << setprecision(12) << fixed << (total / n) << endl;
}
| emanuelsaringan/codeforces | Drinks/main.cc | C++ | gpl-2.0 | 314 |
<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2016 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct accees
defined ('_JEXEC') or die ('restricted access');
class SppagebuilderAddonTab extends SppagebuilderAddons {
public function render() {
$class = (isset($this->addon->settings->class) && $this->addon->settings->class) ? $this->addon->settings->class : '';
$style = (isset($this->addon->settings->style) && $this->addon->settings->style) ? $this->addon->settings->style : '';
$title = (isset($this->addon->settings->title) && $this->addon->settings->title) ? $this->addon->settings->title : '';
$heading_selector = (isset($this->addon->settings->heading_selector) && $this->addon->settings->heading_selector) ? $this->addon->settings->heading_selector : 'h3';
//Output
$output = '<div class="sppb-addon sppb-addon-tab ' . $class . '">';
$output .= ($title) ? '<'.$heading_selector.' class="sppb-addon-title">' . $title . '</'.$heading_selector.'>' : '';
$output .= '<div class="sppb-addon-content sppb-tab">';
//Tab Title
$output .='<ul class="sppb-nav sppb-nav-' . $style . '">';
foreach ($this->addon->settings->sp_tab_item as $key => $tab) {
$title = (isset($tab->icon) && $tab->icon) ? '<i class="fa ' . $tab->icon . '"></i> ' . $tab->title : $tab->title;
$output .='<li class="'. ( ($key==0) ? "active" : "").'"><a data-toggle="sppb-tab" href="#sppb-tab-'. ($this->addon->id + $key) .'">'. $title .'</a></li>';
}
$output .='</ul>';
//Tab Contnet
$output .='<div class="sppb-tab-content sppb-nav-' . $style . '-content">';
foreach ($this->addon->settings->sp_tab_item as $key => $tab) {
$output .='<div id="sppb-tab-'. ($this->addon->id + $key) .'" class="sppb-tab-pane sppb-fade'. ( ($key==0) ? " active in" : "").'">' . $tab->content .'</div>';
}
$output .='</div>';
$output .= '</div>';
$output .= '</div>';
return $output;
}
public function css() {
$addon_id = '#sppb-addon-' . $this->addon->id;
$tab_style = (isset($this->addon->settings->style) && $this->addon->settings->style) ? $this->addon->settings->style : '';
$style = (isset($this->addon->settings->active_tab_color) && $this->addon->settings->active_tab_color) ? 'color: ' . $this->addon->settings->active_tab_color . ';': '';
$css = '';
if($tab_style == 'pills') {
$style .= (isset($this->addon->settings->active_tab_bg) && $this->addon->settings->active_tab_bg) ? 'background-color: ' . $this->addon->settings->active_tab_bg . ';': '';
if($style) {
$css .= $addon_id . ' .sppb-nav-pills > li.active > a,' . $addon_id . ' .sppb-nav-pills > li.active > a:hover,' . $addon_id . ' .sppb-nav-pills > li.active > a:focus {';
$css .= $style;
$css .= '}';
}
} else if ($tab_style == 'lines') {
$style .= (isset($this->addon->settings->active_tab_bg) && $this->addon->settings->active_tab_bg) ? 'border-bottom-color: ' . $this->addon->settings->active_tab_bg . ';': '';
if($style) {
$css .= $addon_id . ' .sppb-nav-lines > li.active > a,' . $addon_id . ' .sppb-nav-lines > li.active > a:hover,' . $addon_id . ' .sppb-nav-lines > li.active > a:focus {';
$css .= $style;
$css .= '}';
}
}
return $css;
}
}
| hoangyen201201/TrienLamOnline | components/com_sppagebuilder/addons/tab/site.php | PHP | gpl-2.0 | 3,318 |
var ajaxManager = (function() {
$jq = jQuery.noConflict();
var requests = [];
return {
addReq: function(opt) {
requests.push(opt);
},
removeReq: function(opt) {
if($jq.inArray(opt, requests) > -1) {
requests.splice($jq.inArray(opt, requests), 1);
}
},
run: function() {
var self = this, orgSuc;
if(requests.length) {
oriSuc = requests[0].complete;
requests[0].complete = function() {
if(typeof oriSuc === 'function') {
oriSuc();
}
requests.shift();
self.run.apply(self, []);
};
$jq.ajax(requests[0]);
} else {
self.tid = setTimeout(function() {
self.run.apply(self, []);
}, 1000);
}
},
stop: function() {
requests = [];
clearTimeout(this.tid);
}
};
}());
ajaxManager.run();
(function($){
$(document).ready(function(){
$('.purAddToCart, .purAddToCartImage').click(function() {
$(this).attr('disabled', 'disabled');
})
$('.Cart66AjaxWarning').hide();
// Added to remove error on double-click when add to cart is clicked
$('.purAddToCart, .purAddToCartImage').click(function() {
$(this).attr('disabled', 'disabled');
})
$('.ajax-button').click(function() {
$(this).attr('disabled', true);
var id = $(this).attr('id').replace('addToCart_', '');
$('#task_' + id).val('ajax');
var product = C66.products[id];
if(C66.trackInventory) {
inventoryCheck(id, C66.ajaxurl, product.ajax, product.name, product.returnUrl, product.addingText);
}
else {
if(product.ajax === 'no') {
$('#task_' + id).val('addToCart');
$('#cartButtonForm_' + id).submit();
return false;
}
else if(product.ajax === 'yes' || product.ajax === 'true') {
buttonTransform(id, C66.ajaxurl, product.name, product.returnUrl, product.addingText);
}
}
return false;
});
$('.modalClose').click(function() {
$('.Cart66Unavailable, .Cart66Warning, .Cart66Error, .alert-message').fadeOut(800);
});
$('#Cart66CancelPayPalSubscription').click(function() {
return confirm('Are you sure you want to cancel your subscription?\n');
});
var original_methods = $('#shipping_method_id').html();
var selected_country = $('#shipping_country_code').val();
$('.methods-country').each(function() {
if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) {
$(this).remove();
}
});
$('#shipping_country_code').change(function() {
var selected_country = $(this).val();
$('#shipping_method_id').html(original_methods);
$('.methods-country').each(function() {
if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) {
$(this).remove();
}
});
$("#shipping_method_id option:eq(1)").attr('selected','selected').change();
});
$('#shipping_method_id').change(function() {
$('#Cart66CartForm').submit();
});
$('#live_rates').change(function() {
$('#Cart66CartForm').submit();
});
$('.showEntriesLink').click(function() {
var panel = $(this).attr('rel');
$('#' + panel).toggle();
return false;
});
$('#change_shipping_zip_link').click(function() {
$('#set_shipping_zip_row').toggle();
return false;
});
})
})(jQuery);
function getCartButtonFormData(formId) {
$jq = jQuery.noConflict();
var theForm = $jq('#' + formId);
var str = '';
$jq('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each(
function() {
var name = $jq(this).attr('name');
var val = $jq(this).val();
str += name + '=' + encodeURIComponent(val) + '&';
}
);
return str.substring(0, str.length-1);
}
function inventoryCheck(formId, ajaxurl, useAjax, productName, productUrl, addingText) {
$jq = jQuery.noConflict();
var mydata = getCartButtonFormData('cartButtonForm_' + formId);
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=1',
data: mydata,
dataType: 'json',
success: function(response) {
if(response[0]) {
$jq('#task_' + formId).val('addToCart');
if(useAjax == 'no') {
$jq('#cartButtonForm_' + formId).submit();
}
else {
buttonTransform(formId, ajaxurl, productName, productUrl, addingText);
}
}
else {
$jq('.modalClose').show();
$jq('#stock_message_box_' + formId).fadeIn(300);
$jq('#stock_message_' + formId).html(response[1]);
$jq('#addToCart_' + formId).removeAttr('disabled');
}
},
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
}
});
}
function addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText) {
$jq = jQuery.noConflict();
var options1 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_1').val();
var options2 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_2').val();
var itemQuantity = $jq('#Cart66UserQuantityInput_' + formId).val();
var itemUserPrice = $jq('#Cart66UserPriceInput_' + formId).val();
var cleanProductId = formId.split('_');
cleanProductId = cleanProductId[0];
var data = {
cart66ItemId: cleanProductId,
itemName: productName,
options_1: options1,
options_2: options2,
item_quantity: itemQuantity,
item_user_price: itemUserPrice,
product_url: productUrl
};
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=2',
data: data,
dataType: 'json',
success: function(response) {
$jq('#addToCart_' + formId).removeAttr('disabled');
$jq('#addToCart_' + formId).removeClass('ajaxPurAddToCart');
$jq('#addToCart_' + formId).val(buttonText);
$jq.hookExecute('addToCartAjaxHook', response);
ajaxUpdateCartWidgets(ajaxurl);
if($jq('.customAjaxAddToCartMessage').length > 0) {
$jq('.customAjaxAddToCartMessage').show().html(response.msg);
$jq.hookExecute('customAjaxAddToCartMessage', response);
}
else {
if((response.msgId) == 0){
$jq('.success_' + formId).fadeIn(300);
$jq('.success_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.success' + formId + ' .message-header').html(response.msgHeader);
}
$jq('.success_' + formId).delay(2000).fadeOut(300);
}
if((response.msgId) == -1){
$jq('.warning_' + formId).fadeIn(300);
$jq('.warning_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.warning' + formId + ' .message-header').html(response.msgHeader);
}
}
if((response.msgId) == -2){
$jq('.error_' + formId).fadeIn(300);
$jq('.error_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.error_' + formId + ' .message-header').html(response.msgHeader);
}
}
}
}
})
}
function buttonTransform(formId, ajaxurl, productName, productUrl, addingText) {
$jq = jQuery.noConflict();
var buttonText = $jq('#addToCart_' + formId).val();
$jq('#addToCart_' + formId).attr('disabled', 'disabled');
$jq('#addToCart_' + formId).addClass('ajaxPurAddToCart');
$jq('#addToCart_' + formId).val(addingText);
addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText);
}
function ajaxUpdateCartWidgets(ajaxurl) {
$jq = jQuery.noConflict();
var widgetId = $jq('.Cart66CartWidget').attr('id');
var data = {
action: "ajax_cart_elements"
};
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=3',
data: data,
dataType: 'json',
success: function(response) {
$jq.hookExecute('cartElementsAjaxHook', response);
$jq('#Cart66AdvancedSidebarAjax, #Cart66WidgetCartContents').show();
$jq('.Cart66WidgetViewCartCheckoutEmpty, #Cart66WidgetCartEmpty').hide();
$jq('#Cart66WidgetCartLink').each(function(){
widgetContent = "<span id=\"Cart66WidgetCartCount\">" + response.summary.count + "</span>";
widgetContent += "<span id=\"Cart66WidgetCartCountText\">" + response.summary.items + "</span>";
widgetContent += "<span id=\"Cart66WidgetCartCountDash\"> – </span>"
widgetContent += "<span id=\"Cart66WidgetCartPrice\">" + response.summary.amount + "</span>";
$jq(this).html(widgetContent).fadeIn('slow');
});
$jq('.Cart66RequireShipping').each(function(){
if(response.shipping == 1) {
$jq(this).show();
}
})
$jq('#Cart66WidgetCartEmptyAdvanced').each(function(){
widgetContent = C66.youHave + ' ' + response.summary.count + " " + response.summary.items + " (" + response.summary.amount + ") " + C66.inYourShoppingCart;
$jq(this).html(widgetContent).fadeIn('slow');
});
$jq("#Cart66AdvancedWidgetCartTable .product_items").remove();
$jq.each(response.products.reverse(), function(index, array){
widgetContent = "<tr class=\"product_items\"><td>";
widgetContent += "<span class=\"Cart66ProductTitle\">" + array.productName + "</span>";
widgetContent += "<span class=\"Cart66QuanPrice\">";
widgetContent += "<span class=\"Cart66ProductQuantity\">" + array.productQuantity + "</span>";
widgetContent += "<span class=\"Cart66MetaSep\"> x </span>";
widgetContent += "<span class=\"Cart66ProductPrice\">" + array.productPrice + "</span>";
widgetContent += "</span>";
widgetContent += "</td><td class=\"Cart66ProductSubtotalColumn\">";
widgetContent += "<span class=\"Cart66ProductSubtotal\">" + array.productSubtotal + "</span>";
widgetContent += "</td></tr>";
$jq("#Cart66AdvancedWidgetCartTable tbody").prepend(widgetContent).fadeIn("slow");
});
$jq('.Cart66Subtotal').each(function(){
$jq(this).html(response.subtotal)
});
$jq('.Cart66Shipping').each(function(){
$jq(this).html(response.shippingAmount)
});
}
})
}
jQuery.extend({
hookExecute: function (function_name, response){
if (typeof window[function_name] == "function"){
window[function_name](response);
return true;
}
else{
return false;
}
}
}); | rbredow/allyzabbacart | js/cart66-library.js | JavaScript | gpl-2.0 | 10,666 |
<?php
session_start();
ob_start();
include ('connect.php');
if(($_SESSION['LOGIN'] == "NO") or (!$_SESSION['LOGIN'])) header('Location: index.php');
function cssifysize($img) {
$dimensions = getimagesize($img);
$dimensions = str_replace("=\"", ":", $dimensions['3']);
$dimensions = str_replace("\"", "px;", $dimensions);
return $dimensions;
};
?>
<br /><br /><a href="index.php">RETURN</a><br /><br />
<form action="image_folder.php" method="POST" enctype="multipart/form-data">
<p> Image Name: <input type="text" name="name_image"> </p>
<p>Locate Image: <input type="file" name="userfile" id="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
<br /><br />
<?php
if(($_POST['name_image'])){
$nameimg = $_POST['name_image'];
$uploaddir = 'img/';
$uploadfile = $uploaddir . $nameimg; //basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$query=mysql_query("INSERT INTO IMG_NEWSLETTER (NAME_IMG, DELETED) VALUES ('$nameimg', 'NO') ") or die (mysql_error()) ;
if($query) header('Location: image_folder?img_upload=success');
}
else { echo "<br />Upload failed<br /><br />"; }
};
$query=mysql_query("SELECT * FROM IMG_NEWSLETTER WHERE DELETED LIKE 'NO' ") or die (mysql_error());
$count = 0;
while($array=mysql_fetch_array($query)){
$count++;
?>
<?php
$img = "img/".$array['NAME_IMG'];
?>
<p><b>Real Size:</b> <?php echo cssifysize($img); ?></p>
<p><b>Display below:</b> width:200px; height:150px; </p>
<p><a href="<?php echo "img/".$array['NAME_IMG']; ?>" target="_blank" ><img src="<?php echo "img/".$array['NAME_IMG']; ?>" width="200" height="150"></a></p><p><b><font size="+2"> <?php echo $array['NAME_IMG']; ?></b></font><input type="button" value="DELETE" onClick="javascript: document.location.href = 'delimg.php?idimg=<?php echo $array['ID_IMG_NEWSLETTER']; ?>';" /></p>
<br />-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=<br />
<?php
};
if($count == 0 ) echo "No image found.";
if($_GET['delete']) echo "<br />The Image has been deleted successfully.";
if($_GET['img_upload']) echo "<br />The Image has been uploaded successfully.";
?>
<br /><br /><a href="index.php">RETURN</a><br /><br />
| somalitaekwondo/site | newsletter/image_folder.php | PHP | gpl-2.0 | 2,323 |
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <iostream>
#include "ftfilemapper.h"
//#define DEBUG_FILEMAPPER
ftFileMapper::ftFileMapper(uint64_t file_size,uint32_t chunk_size)
: _file_size(file_size),_chunk_size(chunk_size)
{
int nb_chunks = (int)(file_size / (uint64_t)chunk_size) + ( (file_size % chunk_size)==0 ?0:1 ) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) Creating ftFileMapper for file of size " << file_size << ", with " << nb_chunks << " chunks." << std::endl;
#endif
_first_free_chunk = 0 ;
_mapped_chunks.clear() ;
_mapped_chunks.resize(nb_chunks,-1) ;
_data_chunks.clear() ;
_data_chunks.resize(nb_chunks,-1) ;
}
bool ftFileMapper::computeStorageOffset(uint64_t offset,uint64_t& storage_offset) const
{
// Compute the chunk number for this offset
//
uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ;
// Check that the cid is in the allowed range. That should always be the case.
//
if(cid < _mapped_chunks.size() && _mapped_chunks[cid] >= 0)
{
storage_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ;
return true ;
}
else
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::computeStorageOffset(): offset " << offset << " corresponds to chunk number " << cid << " which is not mapped!!" << std::endl;
#endif
return false ;
}
}
bool ftFileMapper::writeData(uint64_t offset,uint32_t size,void *data,FILE *fd) const
{
if (0 != fseeko64(fd, offset, SEEK_SET))
{
std::cerr << "(EE) ftFileMapper::ftFileMapper::writeData() Bad fseek at offset " << offset << ", fd=" << (void*)fd << ", size=" << size << ", errno=" << errno << std::endl;
return false;
}
if (1 != fwrite(data, size, 1, fd))
{
std::cerr << "(EE) ftFileMapper::ftFileCreator::addFileData() Bad fwrite." << std::endl;
std::cerr << "ERRNO: " << errno << std::endl;
return false;
}
fflush(fd) ;
return true ;
}
bool ftFileMapper::storeData(void *data, uint32_t data_size, uint64_t offset,FILE *fd)
{
uint64_t real_offset = 0;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::storeData(): storing data size " << data_size << " for offset "<< offset << std::endl;
#endif
// we compute the real place of the data in the mapped file. Several cases:
//
// 1 - the place corresponds to a mapped place
// => write there.
// 2 - the place does not correspond to a mapped place.
// 2.0 - we allocate a new chunk at the end of the file.
// 2.0.1 - the chunk corresponds to a mapped chunk somewhere before
// => we move it, and use the other chunk as writing position
// 2.0.2 - the chunk does not correspond to a mapped chunk somewhere before
// => we use it
// 2.1 - the place is in the range of existing data
// => we move the existing data at the end of the file, and update the mapping
// 2.2 - the place is outside the range of existing data
// => we allocate a new chunk at the end of the file, and write there.
// 2.2.1 - we look for the first chunk that is not already mapped before.
//
if(!computeStorageOffset(offset,real_offset))
{
uint32_t cid = (uint32_t)(offset / (uint64_t)_chunk_size) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) real offset unknown. chunk id is " << cid << std::endl;
#endif
uint32_t empty_chunk = allocateNewEmptyChunk(fd) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) allocated new empty chunk " << empty_chunk << std::endl;
#endif
if(cid < _first_free_chunk && cid != empty_chunk) // the place is already occupied by some data
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) chunk already in use. " << std::endl;
std::cerr << "(DD) swapping with first free chunk: " << empty_chunk << std::endl;
#endif
if(!moveChunk(cid, empty_chunk,fd))
{
std::cerr << "(EE) ftFileMapper::writeData(): cannot move chunk " << empty_chunk << " and " << cid << std::endl ;
return false ;
}
// Get the old chunk id that was mapping to this place
//
int oid = _data_chunks[cid] ;
if(oid < 0)
{
std::cerr << "(EE) ftFileMapper::writeData(): cannot find chunk that was previously mapped to place " << cid << std::endl ;
return false ;
}
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) old chunk now pointing to: " << empty_chunk << std::endl;
std::cerr << "(DD) new chunk now pointing to: " << cid << std::endl;
#endif
_mapped_chunks[cid] = cid ; // this one is in place, since we swapped it
_mapped_chunks[oid] = empty_chunk ;
_data_chunks[cid] = cid ;
_data_chunks[empty_chunk] = oid ;
}
else // allocate a new chunk at end of the file.
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) allocating new storage place at first free chunk: " << empty_chunk << std::endl;
#endif
_mapped_chunks[cid] = empty_chunk ;
_data_chunks[empty_chunk] = cid ;
}
real_offset = _mapped_chunks[cid]*_chunk_size + (offset % (uint64_t)_chunk_size) ;
}
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) real offset = " << real_offset << ", data size=" << data_size << std::endl;
std::cerr << "(DD) writing data " << std::endl;
#endif
return writeData(real_offset,data_size,data,fd) ;
}
uint32_t ftFileMapper::allocateNewEmptyChunk(FILE *fd_out)
{
// look into _first_free_chunk. Is it the place of a chunk already mapped before?
//
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::getFirstEmptyChunk()" << std::endl;
#endif
if(_mapped_chunks[_first_free_chunk] >= 0 && _mapped_chunks[_first_free_chunk] < (int)_first_free_chunk)
{
uint32_t old_chunk = _mapped_chunks[_first_free_chunk] ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) first free chunk " << _first_free_chunk << " is actually mapped to " << old_chunk << ". Moving it." << std::endl;
#endif
moveChunk(_mapped_chunks[_first_free_chunk],_first_free_chunk,fd_out) ;
_mapped_chunks[_first_free_chunk] = _first_free_chunk ;
_data_chunks[_first_free_chunk] = _first_free_chunk ;
_first_free_chunk++ ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) Returning " << old_chunk << std::endl;
#endif
return old_chunk ;
}
else
{
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) first free chunk is fine. Returning " << _first_free_chunk << ", and making room" << std::endl;
#endif
// We need to wipe the entire chunk, since it might be moved before beign completely written, which would cause
// a fread error.
//
wipeChunk(_first_free_chunk,fd_out) ;
return _first_free_chunk++ ;
}
}
bool ftFileMapper::wipeChunk(uint32_t cid,FILE *fd) const
{
uint32_t size = (cid == _mapped_chunks.size()-1)?(_file_size - cid*_chunk_size) : _chunk_size ;
void *buf = malloc(size) ;
if(buf == NULL)
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot allocate temporary buf of size " << size << std::endl;
return false ;
}
if(fseeko64(fd, cid*_chunk_size, SEEK_SET)!= 0)
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot fseek file at position " << cid*_chunk_size << std::endl;
free(buf) ;
return false ;
}
if(1 != fwrite(buf, size, 1, fd))
{
std::cerr << "(EE) ftFileMapper::wipeChunk(): cannot write to file" << std::endl;
free(buf) ;
return false ;
}
free(buf) ;
return true ;
}
bool ftFileMapper::moveChunk(uint32_t to_move, uint32_t new_place,FILE *fd_out)
{
// Read the old chunk, write at the new place
assert(to_move != new_place) ;
fflush(fd_out) ;
#ifdef DEBUG_FILEMAPPER
std::cerr << "(DD) ftFileMapper::moveChunk(): moving chunk " << to_move << " to place " << new_place << std::endl ;
#endif
uint32_t new_place_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ;
uint32_t to_move_size = (new_place == _mapped_chunks.size()-1)?(_file_size - (_mapped_chunks.size()-1)*_chunk_size) : _chunk_size ;
uint32_t size = std::min(new_place_size,to_move_size) ;
void *buff = malloc(size) ;
if(buff == NULL)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot open temporary buffer. Out of memory??" << std::endl;
return false ;
}
if(fseeko64(fd_out, to_move*_chunk_size, SEEK_SET) != 0)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << to_move*_chunk_size << std::endl;
return false ;
}
size_t rd ;
if(size != (rd = fread(buff, 1, size, fd_out)))
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot read from file" << std::endl;
std::cerr << "(EE) errno = " << errno << std::endl;
std::cerr << "(EE) feof = " << feof(fd_out) << std::endl;
std::cerr << "(EE) size = " << size << std::endl;
std::cerr << "(EE) rd = " << rd << std::endl;
return false ;
}
if(fseeko64(fd_out, new_place*_chunk_size, SEEK_SET)!= 0)
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot fseek file at position " << new_place*_chunk_size << std::endl;
return false ;
}
if(1 != fwrite(buff, size, 1, fd_out))
{
std::cerr << "(EE) ftFileMapper::moveChunk(): cannot write to file" << std::endl;
return false ;
}
free(buff) ;
return true ;
}
void ftFileMapper::print() const
{
std::cerr << "ftFileMapper:: [ " ;
for(uint32_t i=0;i<_mapped_chunks.size();++i)
{
std::cerr << _mapped_chunks[i] << " " ;
}
std::cerr << "] - ffc = " << _first_free_chunk << " - [ ";
for(uint32_t i=0;i<_data_chunks.size();++i)
std::cerr << _data_chunks[i] << " " ;
std::cerr << " ] " << std::endl;
}
| RedCraig/retroshare | libretroshare/src/ft/ftfilemapper.cc | C++ | gpl-2.0 | 9,367 |
# Endpoints for user to control the home.
from datetime import datetime
from flask import Blueprint, jsonify, request
from services import elements_services, home_services
home_api = Blueprint('/home_api', __name__)
elements_services = elements_services.ElementsServices()
home_services = home_services.HomeServices()
@home_api.route('/profiles')
def profiles():
"""Gets all profiles for all elements for user application to display and manipulate elements"""
return jsonify(home_services.get_profiles())
@home_api.route('/element', methods=['POST'])
def update_element():
"""Updates single element with all new values received from the user application"""
received_element = request.get_json()
home_services.update_element(received_element)
return 'OK'
@home_api.route('/elements', methods=['POST'])
def update_elements():
"""Updates all elements with all new values received from the user application"""
received_elements = request.get_json()
home_services.update_elements(received_elements)
return 'OK'
@home_api.route('/elementdelete', methods=['POST'])
def delete_element():
"""Deletes a single element with given hid"""
element = request.get_json()
home_services.delete_element(element['hid'])
return 'OK'
@home_api.route('/timerules', methods=['POST'])
def timerules():
"""Adds, Updates or deletes time rule for the given element"""
rules = request.get_json()
if len(rules) == 0:
raise Exception("No elements in the list")
for rule in rules:
if 'id' not in rule:
rule['id'] = None
home_services.save_time_rules(rules)
return 'OK'
@home_api.route('/timerules/<string:hid>')
def get_timerules(hid):
"""Gets list of timerules for given hid"""
timerules= home_services.read_time_rules(hid)
return jsonify(timerules)
| igrlas/CentralHub | CHPackage/src/centralhub/server/home_endpoints.py | Python | gpl-2.0 | 1,856 |
#include "stdafx.h"
#include "Utilities/Log.h"
#include "Utilities/File.h"
#include "git-version.h"
#include "rpcs3/Ini.h"
#include "Emu/Memory/Memory.h"
#include "Emu/System.h"
#include "Emu/GameInfo.h"
#include "Emu/SysCalls/ModuleManager.h"
#include "Emu/Cell/PPUThread.h"
#include "Emu/Cell/SPUThread.h"
#include "Emu/Cell/PPUInstrTable.h"
#include "Emu/FS/vfsFile.h"
#include "Emu/FS/vfsLocalFile.h"
#include "Emu/FS/vfsDeviceLocalFile.h"
#include "Emu/DbgCommand.h"
#include "Emu/CPU/CPUThreadManager.h"
#include "Emu/SysCalls/Callback.h"
#include "Emu/IdManager.h"
#include "Emu/Io/Pad.h"
#include "Emu/Io/Keyboard.h"
#include "Emu/Io/Mouse.h"
#include "Emu/RSX/GSManager.h"
#include "Emu/Audio/AudioManager.h"
#include "Emu/FS/VFS.h"
#include "Emu/Event.h"
#include "Loader/PSF.h"
#include "Loader/ELF64.h"
#include "Loader/ELF32.h"
#include "../Crypto/unself.h"
#include <fstream>
using namespace PPU_instr;
static const std::string& BreakPointsDBName = "BreakPoints.dat";
static const u16 bpdb_version = 0x1000;
extern std::atomic<u32> g_thread_count;
extern u64 get_system_time();
extern void finalize_psv_modules();
Emulator::Emulator()
: m_status(Stopped)
, m_mode(DisAsm)
, m_rsx_callback(0)
, m_thread_manager(new CPUThreadManager())
, m_pad_manager(new PadManager())
, m_keyboard_manager(new KeyboardManager())
, m_mouse_manager(new MouseManager())
, m_gs_manager(new GSManager())
, m_audio_manager(new AudioManager())
, m_callback_manager(new CallbackManager())
, m_event_manager(new EventManager())
, m_module_manager(new ModuleManager())
, m_vfs(new VFS())
{
m_loader.register_handler(new loader::handlers::elf32);
m_loader.register_handler(new loader::handlers::elf64);
}
Emulator::~Emulator()
{
}
void Emulator::Init()
{
}
void Emulator::SetPath(const std::string& path, const std::string& elf_path)
{
m_path = path;
m_elf_path = elf_path;
}
void Emulator::SetTitleID(const std::string& id)
{
m_title_id = id;
}
void Emulator::SetTitle(const std::string& title)
{
m_title = title;
}
bool Emulator::BootGame(const std::string& path, bool direct)
{
static const char* elf_path[6] =
{
"/PS3_GAME/USRDIR/BOOT.BIN",
"/USRDIR/BOOT.BIN",
"/BOOT.BIN",
"/PS3_GAME/USRDIR/EBOOT.BIN",
"/USRDIR/EBOOT.BIN",
"/EBOOT.BIN"
};
auto curpath = path;
if (direct)
{
if (fs::is_file(curpath))
{
SetPath(curpath);
Load();
return true;
}
}
for (int i = 0; i < sizeof(elf_path) / sizeof(*elf_path); i++)
{
curpath = path + elf_path[i];
if (fs::is_file(curpath))
{
SetPath(curpath);
Load();
return true;
}
}
return false;
}
void Emulator::Load()
{
m_status = Ready;
GetModuleManager().Init();
if (!fs::is_file(m_path))
{
m_status = Stopped;
return;
}
const std::string elf_dir = m_path.substr(0, m_path.find_last_of("/\\", std::string::npos, 2) + 1);
if (IsSelf(m_path))
{
const std::string full_name = m_path.substr(elf_dir.length());
const std::string base_name = full_name.substr(0, full_name.find_last_of('.', std::string::npos));
const std::string ext = full_name.substr(base_name.length());
if (fmt::toupper(full_name) == "EBOOT.BIN")
{
m_path = elf_dir + "BOOT.BIN";
}
else if (fmt::toupper(ext) == ".SELF")
{
m_path = elf_dir + base_name + ".elf";
}
else if (fmt::toupper(ext) == ".SPRX")
{
m_path = elf_dir + base_name + ".prx";
}
else
{
m_path = elf_dir + base_name + ".decrypted" + ext;
}
LOG_NOTICE(LOADER, "Decrypting '%s%s'...", elf_dir, full_name);
if (!DecryptSelf(m_path, elf_dir + full_name))
{
m_status = Stopped;
return;
}
}
LOG_NOTICE(LOADER, "Loading '%s'...", m_path.c_str());
ResetInfo();
GetVFS().Init(elf_dir);
// /dev_bdvd/ mounting
vfsFile f("/app_home/../dev_bdvd.path");
if (f.IsOpened())
{
// load specified /dev_bdvd/ directory and mount it
std::string bdvd;
bdvd.resize(f.GetSize());
f.Read(&bdvd[0], bdvd.size());
Emu.GetVFS().Mount("/dev_bdvd/", bdvd, new vfsDeviceLocalFile());
}
else if (fs::is_file(elf_dir + "../../PS3_DISC.SFB")) // guess loading disc game
{
const auto dir_list = fmt::split(elf_dir, { "/", "\\" });
// check latest two directories
if (dir_list.size() >= 2 && dir_list.back() == "USRDIR" && *(dir_list.end() - 2) == "PS3_GAME")
{
// mount detected /dev_bdvd/ directory
Emu.GetVFS().Mount("/dev_bdvd/", elf_dir.substr(0, elf_dir.length() - 17), new vfsDeviceLocalFile());
}
}
LOG_NOTICE(LOADER, "");
LOG_NOTICE(LOADER, "Mount info:");
for (uint i = 0; i < GetVFS().m_devices.size(); ++i)
{
LOG_NOTICE(LOADER, "%s -> %s", GetVFS().m_devices[i]->GetPs3Path().c_str(), GetVFS().m_devices[i]->GetLocalPath().c_str());
}
LOG_NOTICE(LOADER, "");
LOG_NOTICE(LOADER, "RPCS3 version: %s", RPCS3_GIT_VERSION);
LOG_NOTICE(LOADER, "");
LOG_NOTICE(LOADER, "Settings:");
LOG_NOTICE(LOADER, "CPU: %s", Ini.CPUIdToString(Ini.CPUDecoderMode.GetValue()));
LOG_NOTICE(LOADER, "SPU: %s", Ini.SPUIdToString(Ini.SPUDecoderMode.GetValue()));
LOG_NOTICE(LOADER, "Renderer: %s", Ini.RendererIdToString(Ini.GSRenderMode.GetValue()));
if (Ini.GSRenderMode.GetValue() == 2)
{
LOG_NOTICE(LOADER, "D3D Adapter: %s", Ini.AdapterIdToString(Ini.GSD3DAdaptater.GetValue()));
}
LOG_NOTICE(LOADER, "Resolution: %s", Ini.ResolutionIdToString(Ini.GSResolution.GetValue()));
LOG_NOTICE(LOADER, "Write Depth Buffer: %s", Ini.GSDumpDepthBuffer.GetValue() ? "Yes" : "No");
LOG_NOTICE(LOADER, "Write Color Buffers: %s", Ini.GSDumpColorBuffers.GetValue() ? "Yes" : "No");
LOG_NOTICE(LOADER, "Read Color Buffer: %s", Ini.GSReadColorBuffer.GetValue() ? "Yes" : "No");
LOG_NOTICE(LOADER, "Audio Out: %s", Ini.AudioOutIdToString(Ini.AudioOutMode.GetValue()));
LOG_NOTICE(LOADER, "Log Everything: %s", Ini.HLELogging.GetValue() ? "Yes" : "No");
LOG_NOTICE(LOADER, "RSX Logging: %s", Ini.RSXLogging.GetValue() ? "Yes" : "No");
LOG_NOTICE(LOADER, "");
f.Open("/app_home/../PARAM.SFO");
const PSFLoader psf(f);
std::string title = psf.GetString("TITLE");
std::string title_id = psf.GetString("TITLE_ID");
LOG_NOTICE(LOADER, "Title: %s", title.c_str());
LOG_NOTICE(LOADER, "Serial: %s", title_id.c_str());
title.length() ? SetTitle(title) : SetTitle(m_path);
SetTitleID(title_id);
if (m_elf_path.empty())
{
GetVFS().GetDeviceLocal(m_path, m_elf_path);
LOG_NOTICE(LOADER, "Elf path: %s", m_elf_path);
LOG_NOTICE(LOADER, "");
}
f.Open(m_elf_path);
if (!f.IsOpened())
{
LOG_ERROR(LOADER, "Opening '%s' failed", m_path.c_str());
m_status = Stopped;
return;
}
if (!m_loader.load(f))
{
LOG_ERROR(LOADER, "Loading '%s' failed", m_path.c_str());
LOG_NOTICE(LOADER, "");
m_status = Stopped;
vm::close();
return;
}
LoadPoints(BreakPointsDBName);
GetGSManager().Init();
GetCallbackManager().Init();
GetAudioManager().Init();
GetEventManager().Init();
SendDbgCommand(DID_READY_EMU);
}
void Emulator::Run()
{
if (!IsReady())
{
Load();
if(!IsReady()) return;
}
if (IsRunning()) Stop();
if (IsPaused())
{
Resume();
return;
}
SendDbgCommand(DID_START_EMU);
m_pause_start_time = 0;
m_pause_amend_time = 0;
m_status = Running;
GetCPU().Exec();
SendDbgCommand(DID_STARTED_EMU);
}
void Emulator::Pause()
{
const u64 start = get_system_time();
// try to set Paused status
if (!sync_bool_compare_and_swap(&m_status, Running, Paused))
{
return;
}
// update pause start time
if (m_pause_start_time.exchange(start))
{
LOG_ERROR(GENERAL, "Emulator::Pause() error: concurrent access");
}
SendDbgCommand(DID_PAUSE_EMU);
for (auto& t : GetCPU().GetAllThreads())
{
t->sleep(); // trigger status check
}
SendDbgCommand(DID_PAUSED_EMU);
}
void Emulator::Resume()
{
// get pause start time
const u64 time = m_pause_start_time.exchange(0);
// try to increment summary pause time
if (time)
{
m_pause_amend_time += get_system_time() - time;
}
// try to resume
if (!sync_bool_compare_and_swap(&m_status, Paused, Running))
{
return;
}
if (!time)
{
LOG_ERROR(GENERAL, "Emulator::Resume() error: concurrent access");
}
SendDbgCommand(DID_RESUME_EMU);
for (auto& t : GetCPU().GetAllThreads())
{
t->awake(); // untrigger status check and signal
}
SendDbgCommand(DID_RESUMED_EMU);
}
extern std::map<u32, std::string> g_armv7_dump;
void Emulator::Stop()
{
LOG_NOTICE(GENERAL, "Stopping emulator...");
if (sync_lock_test_and_set(&m_status, Stopped) == Stopped)
{
return;
}
SendDbgCommand(DID_STOP_EMU);
{
LV2_LOCK;
// notify all threads
for (auto& t : GetCPU().GetAllThreads())
{
std::lock_guard<std::mutex> lock(t->mutex);
t->sleep(); // trigger status check
t->cv.notify_one(); // signal
}
}
LOG_NOTICE(GENERAL, "All threads signaled...");
while (g_thread_count)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
LOG_NOTICE(GENERAL, "All threads stopped...");
idm::clear();
fxm::clear();
LOG_NOTICE(GENERAL, "Objects cleared...");
finalize_psv_modules();
for (auto& v : decltype(g_armv7_dump)(std::move(g_armv7_dump)))
{
LOG_NOTICE(ARMv7, v.second);
}
m_rsx_callback = 0;
// TODO: check finalization order
SavePoints(BreakPointsDBName);
m_break_points.clear();
m_marked_points.clear();
GetVFS().UnMountAll();
GetGSManager().Close();
GetAudioManager().Close();
GetEventManager().Clear();
GetCPU().Close();
GetPadManager().Close();
GetKeyboardManager().Close();
GetMouseManager().Close();
GetCallbackManager().Clear();
GetModuleManager().Close();
CurGameInfo.Reset();
RSXIOMem.Clear();
vm::close();
SendDbgCommand(DID_STOPPED_EMU);
}
void Emulator::SavePoints(const std::string& path)
{
std::ofstream f(path, std::ios::binary | std::ios::trunc);
u32 break_count = (u32)m_break_points.size();
u32 marked_count = (u32)m_marked_points.size();
f.write((char*)(&bpdb_version), sizeof(bpdb_version));
f.write((char*)(&break_count), sizeof(break_count));
f.write((char*)(&marked_count), sizeof(marked_count));
if (break_count)
{
f.write((char*)(m_break_points.data()), sizeof(u64) * break_count);
}
if (marked_count)
{
f.write((char*)(m_marked_points.data()), sizeof(u64) * marked_count);
}
}
bool Emulator::LoadPoints(const std::string& path)
{
if (!fs::is_file(path)) return false;
std::ifstream f(path, std::ios::binary);
if (!f.is_open())
return false;
f.seekg(0, std::ios::end);
u64 length = (u64)f.tellg();
f.seekg(0, std::ios::beg);
u16 version;
u32 break_count, marked_count;
u64 expected_length = sizeof(bpdb_version) + sizeof(break_count) + sizeof(marked_count);
if (length < expected_length)
{
LOG_ERROR(LOADER,
"'%s' breakpoint db is broken (file is too short, length=0x%x)",
path, length);
return false;
}
f.read((char*)(&version), sizeof(version));
if (version != bpdb_version)
{
LOG_ERROR(LOADER,
"'%s' breakpoint db version is unsupported (version=0x%x, length=0x%x)",
path, version, length);
return false;
}
f.read((char*)(&break_count), sizeof(break_count));
f.read((char*)(&marked_count), sizeof(marked_count));
expected_length += break_count * sizeof(u64) + marked_count * sizeof(u64);
if (expected_length != length)
{
LOG_ERROR(LOADER,
"'%s' breakpoint db format is incorrect "
"(version=0x%x, break_count=0x%x, marked_count=0x%x, length=0x%x)",
path, version, break_count, marked_count, length);
return false;
}
if (break_count > 0)
{
m_break_points.resize(break_count);
f.read((char*)(m_break_points.data()), sizeof(u64) * break_count);
}
if (marked_count > 0)
{
m_marked_points.resize(marked_count);
f.read((char*)(m_marked_points.data()), sizeof(u64) * marked_count);
}
return true;
}
Emulator Emu;
CallAfterCbType CallAfterCallback = nullptr;
void CallAfter(std::function<void()> func)
{
CallAfterCallback(func);
}
void SetCallAfterCallback(CallAfterCbType cb)
{
CallAfterCallback = cb;
}
| thatguyehler/rpcs3 | rpcs3/Emu/System.cpp | C++ | gpl-2.0 | 11,861 |
<?php
/**
* @version 3.2.11 September 8, 2011
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
defined('GANTRY_VERSION') or die;
gantry_import('core.config.gantryformgroup');
gantry_import('core.config.gantryformfield');
class GantryFormGroupEnabledGroup extends GantryFormGroup
{
protected $type = 'enabledgroup';
protected $baseetype = 'group';
protected $sets = array();
protected $enabler;
public function getInput()
{
global $gantry;
$buffer = '';
// get the sets just below
foreach ($this->fields as $field)
{
if ($field->type == 'set')
{
$this->sets[] = $field;
}
}
$buffer .= "<div class='wrapper'>\n";
foreach ($this->fields as $field)
{
if ((string)$field->type != 'set')
{
$enabler = false;
if ($field->element['enabler'] && (string)$field->element['enabler'] == true){
$this->enabler = $field;
$enabler = true;
}
$itemName = $this->fieldname . "-" . $field->fieldname;
$buffer .= '<div class="chain ' . $itemName . ' chain-' . strtolower($field->type) . '">' . "\n";
if (strlen($field->getLabel())) $buffer .= '<span class="chain-label">' . JText::_($field->getLabel()) . '</span>' . "\n";
if ($enabler) $buffer .= '<div class="enabledset-enabler">'."\n";
$buffer .= $field->getInput();
if ($enabler) $buffer .= '</div>'."\n";
$buffer .= "</div>" . "\n";
}
}
$buffer .= "</div>" . "\n";
return $buffer;
}
public function render($callback)
{
$buffer = parent::render($callback);
$cls = ' enabledset-hidden-field';
if (!empty($this->sets)){
$set = array_shift($this->sets);
if (isset($this->enabler) && (int)$this->enabler->value == 0){
$cls = ' enabledset-hidden-field';
}
$buffer .= '<div class="enabledset-fields'.$cls.'" id="set-'.(string)$set->element['name'].'">';
foreach ($set->fields as $field)
{
if ($field->type == 'hidden')
$buffer .= $field->getInput();
else
{
$buffer .= $field->render($callback);
}
}
$buffer .= '</div>';
}
return $buffer;
}
} | epireve/joomla | libraries/gantry/admin/forms/groups/enabledgroup.php | PHP | gpl-2.0 | 2,633 |
# -*- coding: utf-8 -*-
import time
import EafIO
import warnings
class Eaf:
"""Read and write Elan's Eaf files.
.. note:: All times are in milliseconds and can't have decimals.
:var dict annotation_document: Annotation document TAG entries.
:var dict licences: Licences included in the file.
:var dict header: XML header.
:var list media_descriptors: Linked files, where every file is of the
form: ``{attrib}``.
:var list properties: Properties, where every property is of the form:
``(value, {attrib})``.
:var list linked_file_descriptors: Secondary linked files, where every
linked file is of the form:
``{attrib}``.
:var dict timeslots: Timeslot data of the form:
``{TimslotID -> time(ms)}``.
:var dict tiers: Tier data of the form:
``{tier_name -> (aligned_annotations,
reference_annotations, attributes, ordinal)}``,
aligned_annotations of the form:
``[{annotation_id ->
(begin_ts, end_ts, value, svg_ref)}]``,
reference annotations of the form:
``[{annotation_id ->
(reference, value, previous, svg_ref)}]``.
:var list linguistic_types: Linguistic types, where every type is of the
form: ``{id -> attrib}``.
:var list locales: Locales, where every locale is of the form:
``{attrib}``.
:var dict constraints: Constraint data of the form:
``{stereotype -> description}``.
:var dict controlled_vocabularies: Controlled vocabulary data of the
form: ``{id ->
(descriptions, entries, ext_ref)}``,
descriptions of the form:
``[(lang_ref, text)]``,
entries of the form:
``{id -> (values, ext_ref)}``,
values of the form:
``[(lang_ref, description, text)]``.
:var list external_refs: External references, where every reference is of
the form ``[id, type, value]``.
:var list lexicon_refs: Lexicon references, where every reference is of
the form: ``[{attribs}]``.
"""
def __init__(self, file_path=None, author='pympi'):
"""Construct either a new Eaf file or read on from a file/stream.
:param str file_path: Path to read from, - for stdin. If ``None`` an
empty Eaf file will be created.
:param str author: Author of the file.
"""
self.naive_gen_ann, self.naive_gen_ts = False, False
self.annotation_document = {
'AUTHOR': author,
'DATE': time.strftime("%Y-%m-%dT%H:%M:%S%z"),
'VERSION': '2.8',
'FORMAT': '2.8',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:noNamespaceSchemaLocation':
'http://www.mpi.nl/tools/elan/EAFv2.8.xsd'}
self.constraints = {}
self.controlled_vocabularies = {}
self.header = {}
self.licences = {}
self.linguistic_types = {}
self.tiers = {}
self.timeslots = {}
self.external_refs = []
self.lexicon_refs = []
self.linked_file_descriptors = []
self.locales = []
self.media_descriptors = []
self.properties = []
self.new_time, self.new_ann = 0, 0
if file_path is None:
self.add_linguistic_type('default-lt', None)
self.constraints = {'Time_Subdivision': 'Time subdivision of paren'
't annotation\'s time interval, no time gaps a'
'llowed within this interval',
'Symbolic_Subdivision': 'Symbolic subdivision '
'of a parent annotation. Annotations refering '
'to the same parent are ordered',
'Symbolic_Association': '1-1 association with '
'a parent annotation',
'Included_In': 'Time alignable annotations wit'
'hin the parent annotation\'s time interval, g'
'aps are allowed'}
self.properties.append(('0', {'NAME': 'lastUsedAnnotation'}))
self.add_tier('default')
else:
EafIO.parse_eaf(file_path, self)
def to_file(self, file_path, pretty=True):
"""Write the object to a file, if the file already exists a backup will
be created with the ``.bak`` suffix.
:param str file_path: Path to write to, - for stdout.
:param bool pretty: Flag for pretty XML printing.
"""
EafIO.to_eaf(file_path, self, pretty)
def to_textgrid(self, excluded_tiers=[], included_tiers=[]):
"""Convert the object to a :class:`pympi.Praat.TextGrid` object.
:param list excluded_tiers: Specifically exclude these tiers.
:param list included_tiers: Only include this tiers, when empty all are
included.
:returns: :class:`pympi.Praat.TextGrid` object
:raises ImportError: If the pympi.Praat module can't be loaded.
"""
from Praat import TextGrid
tgout = TextGrid()
tiers = [a for a in self.tiers if a not in excluded_tiers]
if included_tiers:
tiers = [a for a in tiers if a in included_tiers]
for tier in tiers:
currentTier = tgout.add_tier(tier)
for interval in self.get_annotation_data_for_tier(tier):
if interval[0] == interval[1]:
continue
currentTier.add_interval(interval[0]/1000.0,
interval[1]/1000.0, interval[2])
return tgout
def extract(self, start, end):
"""Extracts the selected time frame as a new object.
:param int start: Start time.
:param int end: End time.
:returns: The extracted frame in a new object.
"""
from copy import deepcopy
eaf_out = deepcopy(self)
for tier in eaf_out.tiers.itervalues():
rems = []
for ann in tier[0]:
if eaf_out.timeslots[tier[0][ann][1]] > end or\
eaf_out.timeslots[tier[0][ann][0]] < start:
rems.append(ann)
for r in rems:
del tier[0][r]
return eaf_out
def get_linked_files(self):
"""Give all linked files."""
return self.media_descriptors
def add_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, ex_from=None):
"""Add a linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` it tries to
guess it according to the file extension which
currently only works for wav, mpg, mpeg and xml.
:param int time_origin: Time origin for the media file.
:param str ex_from: Extracted from field.
:raises KeyError: If mimetype had to be guessed and a non standard
extension or an unknown mimetype.
"""
if mimetype is None:
mimes = {'wav': 'audio/x-wav', 'mpg': 'video/mpeg',
'mpeg': 'video/mpg', 'xml': 'text/xml'}
mimetype = mimes[file_path.split('.')[-1]]
self.media_descriptors.append({
'MEDIA_URL': file_path, 'RELATIVE_MEDIA_URL': relpath,
'MIME_TYPE': mimetype, 'TIME_ORIGIN': time_origin,
'EXTRACTED_FROM': ex_from})
def copy_tier(self, eaf_obj, tier_name):
"""Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
"""
eaf_obj.remove_tier(tier_name)
eaf_obj.add_tier(tier_name, tier_dict=self.tiers[tier_name][3])
for ann in self.get_annotation_data_for_tier(tier_name):
eaf_obj.insert_annotation(tier_name, ann[0], ann[1], ann[2])
def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None,
part=None, ann=None, tier_dict=None):
"""Add a tier.
:param str tier_id: Name of the tier.
:param str ling: Linguistic type, if the type is not available it will
warn and pick the first available type.
:param str parent: Parent tier name.
:param str locale: Locale.
:param str part: Participant.
:param str ann: Annotator.
:param dict tier_dict: TAG attributes, when this is not ``None`` it
will ignore all other options.
"""
if ling not in self.linguistic_types:
warnings.warn(
'add_tier: Linguistic type non existent, choosing the first')
ling = self.linguistic_types.keys()[0]
if tier_dict is None:
self.tiers[tier_id] = ({}, {}, {
'TIER_ID': tier_id,
'LINGUISTIC_TYPE_REF': ling,
'PARENT_REF': parent,
'PARTICIPANT': part,
'DEFAULT_LOCALE': locale,
'ANNOTATOR': ann}, len(self.tiers))
else:
self.tiers[tier_id] = ({}, {}, tier_dict, len(self.tiers))
def remove_tiers(self, tiers):
"""Remove multiple tiers, note that this is a lot faster then removing
them individually because of the delayed cleaning of timeslots.
:param list tiers: Names of the tier to remove.
:raises KeyError: If a tier is non existent.
"""
for a in tiers:
self.remove_tier(a, check=False, clean=False)
self.clean_time_slots()
def remove_tier(self, id_tier, clean=True):
"""Remove tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent.
"""
del(self.tiers[id_tier])
if clean:
self.clean_time_slots()
def get_tier_names(self):
"""List all the tier names.
:returns: List of all tier names
"""
return self.tiers.keys()
def get_parameters_for_tier(self, id_tier):
"""Give the parameter dictionary, this is usaable in :func:`add_tier`.
:param str id_tier: Name of the tier.
:returns: Dictionary of parameters.
:raises KeyError: If the tier is non existent.
"""
return self.tiers[id_tier][2]
def child_tiers_for(self, id_tier):
"""Give all child tiers for a tier.
:param str id_tier: Name of the tier.
:returns: List of all children
:raises KeyError: If the tier is non existent.
"""
return [m for m in self.tiers if 'PARENT_REF' in self.tiers[m][2] and
self.tiers[m][2]['PARENT_REF'] == id_tier]
def get_annotation_data_for_tier(self, id_tier):
"""Gives a list of annotations of the form: ``(begin, end, value)``
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
a = self.tiers[id_tier][0]
return [(self.timeslots[a[b][0]], self.timeslots[a[b][1]], a[b][2])
for b in a]
def get_annotation_data_at_time(self, id_tier, time):
"""Give the annotations at the given time.
:param str id_tier: Name of the tier.
:param int time: Time of the annotation.
:returns: List of annotations at that time.
:raises KeyError: If the tier is non existent.
"""
anns = self.tiers[id_tier][0]
return sorted(
[(self.timeslots[m[0]], self.timeslots[m[1]], m[2])
for m in anns.itervalues() if
self.timeslots[m[0]] <= time and
self.timeslots[m[1]] >= time])
def get_annotation_datas_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:returns: List of annotations within that time.
:raises KeyError: If the tier is non existent.
"""
anns = self.tiers[id_tier][0]
return sorted([
(self.timeslots[m[0]], self.timeslots[m[1]], m[2])
for m in anns.itervalues() if self.timeslots[m[1]] >= start and
self.timeslots[m[0]] <= end])
def remove_all_annotations_from_tier(self, id_tier):
"""remove all annotations from a tier
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier][0], self.tiers[id_tier][1] = {}, {}
self.clean_time_slots()
def insert_annotation(self, id_tier, start, end, value='', svg_ref=None):
"""Insert an annotation.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:param str value: Value of the annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
"""
start_ts = self.generate_ts_id(start)
end_ts = self.generate_ts_id(end)
self.tiers[id_tier][0][self.generate_annotation_id()] =\
(start_ts, end_ts, value, svg_ref)
def remove_annotation(self, id_tier, time, clean=True):
"""Remove an annotation in a tier, if you need speed the best thing is
to clean the timeslots after the last removal.
:param str id_tier: Name of the tier.
:param int time: Timepoint within the annotation.
:param bool clean: Flag to clean the timeslots afterwards.
:raises KeyError: If the tier is non existent.
"""
for b in [a for a in self.tiers[id_tier][0].iteritems() if
a[1][0] >= time and a[1][1] <= time]:
del(self.tiers[id_tier][0][b[0]])
if clean:
self.clean_time_slots()
def insert_ref_annotation(self, id_tier, ref, value, prev, svg_ref=None):
"""Insert a reference annotation.
:param str id_tier: Name of the tier.
:param str ref: Id of the referenced annotation.
:param str value: Value of the annotation.
:param str prev: Id of the previous annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier][1][self.generate_annotation_id()] =\
(ref, value, prev, svg_ref)
def get_ref_annotation_data_for_tier(self, id_tier):
""""Give a list of all reference annotations of the form:
``[{id -> (ref, value, previous, svg_ref}]``
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
return self.tiers[id_tier][1]
def remove_controlled_vocabulary(self, cv):
"""Remove a controlled vocabulary.
:param str cv: Controlled vocabulary id.
:raises KeyError: If the controlled vocabulary is non existent.
"""
del(self.controlled_vocabularies[cv])
def generate_annotation_id(self):
"""Generate the next annotation id, this function is mainly used
internally.
"""
if self.naive_gen_ann:
new = self.last_ann+1
self.last_ann = new
else:
new = 1
anns = {int(ann[1:]) for tier in self.tiers.itervalues()
for ann in tier[0]}
if len(anns) > 0:
newann = set(xrange(1, max(anns))).difference(anns)
if len(newann) == 0:
new = max(anns)+1
self.naive_gen_ann = True
self.last_ann = new
else:
new = sorted(newann)[0]
return 'a%d' % new
def generate_ts_id(self, time=None):
"""Generate the next timeslot id, this function is mainly used
internally
:param int time: Initial time to assign to the timeslot
"""
if self.naive_gen_ts:
new = self.last_ts+1
self.last_ts = new
else:
new = 1
tss = {int(x[2:]) for x in self.timeslots}
if len(tss) > 0:
newts = set(xrange(1, max(tss))).difference(tss)
if len(newts) == 0:
new = max(tss)+1
self.naive_gen_ts = True
self.last_ts = new
else:
new = sorted(newts)[0]
ts = 'ts%d' % new
self.timeslots[ts] = time
return ts
def clean_time_slots(self):
"""Clean up all unused timeslots.
.. warning:: This can and will take time for larger tiers. When you
want to do a lot of operations on a lot of tiers please
unset the flags for cleaning in the functions so that the
cleaning is only performed afterwards.
"""
ts_in_tier = set(sum([a[0:2] for tier in self.tiers.itervalues()
for a in tier[0].itervalues()], ()))
ts_avail = set(self.timeslots)
for a in ts_in_tier.symmetric_difference(ts_avail):
del(self.timeslots[a])
self.naive_gen_ts = False
self.naive_gen_ann = False
def generate_annotation_concat(self, tiers, start, end, sep='-'):
"""Give a string of concatenated annotation values for annotations
within a timeframe.
:param list tiers: List of tier names.
:param int start: Start time.
:param int end: End time.
:param str sep: Separator string to use.
:returns: String containing a concatenation of annotation values.
:raises KeyError: If a tier is non existent.
"""
return sep.join(
set(d[2] for t in tiers if t in self.tiers for d in
self.get_annotation_datas_between_times(t, start, end)))
def merge_tiers(self, tiers, tiernew=None, gaptresh=1):
"""Merge tiers into a new tier and when the gap is lower then the
threshhold glue the annotations together.
:param list tiers: List of tier names.
:param str tiernew: Name for the new tier, if ``None`` the name will be
generated.
:param int gapthresh: Threshhold for the gaps.
:raises KeyError: If a tier is non existent.
:raises TypeError: If there are no annotations within the tiers.
"""
if tiernew is None:
tiernew = '%s_Merged' % '_'.join(tiers)
self.remove_tier(tiernew)
self.add_tier(tiernew)
timepts = sorted(set.union(
*[set(j for j in xrange(d[0], d[1])) for d in
[ann for tier in tiers for ann in
self.get_annotation_data_for_tier(tier)]]))
if len(timepts) > 1:
start = timepts[0]
for i in xrange(1, len(timepts)):
if timepts[i]-timepts[i-1] > gaptresh:
self.insert_annotation(
tiernew, start, timepts[i-1],
self.generate_annotation_concat(tiers, start,
timepts[i-1]))
start = timepts[i]
self.insert_annotation(
tiernew, start, timepts[i-1],
self.generate_annotation_concat(tiers, start, timepts[i-1]))
def shift_annotations(self, time):
"""Shift all annotations in time, this creates a new object.
:param int time: Time shift width, negative numbers make a right shift.
:returns: Shifted :class:`pympi.Elan.Eaf' object.
"""
e = self.extract(
-1*time, self.get_full_time_interval()[1]) if time < 0 else\
self.extract(0, self.get_full_time_interval()[1]-time)
for tier in e.tiers.itervalues():
for ann in tier[0].itervalues():
e.timeslots[ann[0]] = e.timeslots[ann[0]]+time
e.timeslots[ann[1]] = e.timeslots[ann[1]]+time
e.clean_time_slots()
return e
def filterAnnotations(self, tier, tier_name=None, filtin=None,
filtex=None):
"""Filter annotations in a tier
:param str tier: Name of the tier:
:param str tier_name: Name of the new tier, when ``None`` the name will
be generated.
:param list filtin: List of strings to be included, if None all
annotations all is included.
:param list filtex: List of strings to be excluded, if None no strings
are excluded.
:raises KeyError: If the tier is non existent.
"""
if tier_name is None:
tier_name = '%s_filter' % tier
self.remove_tier(tier_name)
self.add_tier(tier_name)
for a in [b for b in self.get_annotation_data_for_tier(tier)
if (filtex is None or b[2] not in filtex) and
(filtin is None or b[2] in filtin)]:
self.insert_annotation(tier_name, a[0], a[1], a[2])
def glue_annotations_in_tier(self, tier, tier_name=None, treshhold=85,
filtin=None, filtex=None):
"""Glue annotatotions together in a tier.
:param str tier: Name of the tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
be generated.
:param int threshhold: Threshhold for the maximum gap to still glue.
:param list filtin: List of strings to be included, if None all
annotations all is included.
:param list filtex: List of strings to be excluded, if None no strings
are excluded.
:raises KeyError: If the tier is non existent.
"""
if tier_name is None:
tier_name = '%s_glued' % tier
self.remove_tier(tier_name)
self.add_tier(tier_name)
tier_data = sorted(self.get_annotation_data_for_tier(tier))
tier_data = [t for t in tier_data if
(filtin is None or t[2] in filtin) and
(filtex is None or t[2] not in filtex)]
currentAnn = None
for i in xrange(0, len(tier_data)):
if currentAnn is None:
currentAnn = (tier_data[i][0], tier_data[i][1],
tier_data[i][2])
elif tier_data[i][0] - currentAnn[1] < treshhold:
currentAnn = (currentAnn[0], tier_data[i][1],
'%s_%s' % (currentAnn[2], tier_data[i][2]))
else:
self.insert_annotation(tier_name, currentAnn[0], currentAnn[1],
currentAnn[2])
currentAnn = tier_data[i]
if currentAnn is not None:
self.insert_annotation(tier_name, currentAnn[0],
tier_data[len(tier_data)-1][1],
currentAnn[2])
def get_full_time_interval(self):
"""Give the full time interval of the file.
:returns: Tuple of the form: ``(min_time, max_time``.
"""
return (min(self.timeslots.itervalues()),
max(self.timeslots.itervalues()))
def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None,
maxlen=-1):
"""Create a tier with the gaps and overlaps of the annotations.
For types see :func:`get_gaps_and_overlaps_duration`
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
be generated.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:returns: List of gaps and overlaps of the form:
``[(type, start, end)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
if tier_name is None:
tier_name = '%s_%s_ftos' % (tier1, tier2)
self.remove_tier(tier_name)
self.add_tier(tier_name)
ftos = self.get_gaps_and_overlaps_duration(tier1, tier2, maxlen)
for fto in ftos:
self.insert_annotation(tier_name, fto[1], fto[2], fto[0])
return ftos
def get_gaps_and_overlaps_duration(self, tier1, tier2, maxlen=-1,
progressbar=False):
"""Give gaps and overlaps. The return types are shown in the table
below. The string will be of the format: ``id_tiername_tiername``.
For example when a gap occurs between tier1 and tier2 and they are
called ``speakerA`` and ``speakerB`` the annotation value of that gap
will be ``G12_speakerA_speakerB``.
| The gaps and overlaps are calculated using Heldner and Edlunds
method found in:
| *Heldner, M., & Edlund, J. (2010). Pauses, gaps and overlaps in
conversations. Journal of Phonetics, 38(4), 555–568.
doi:10.1016/j.wocn.2010.08.002*
+-----+--------------------------------------------+
| id | Description |
+=====+============================================+
| O12 | Overlap from tier1 to tier2 |
+-----+--------------------------------------------+
| O21 | Overlap from tier2 to tier1 |
+-----+--------------------------------------------+
| G12 | Gap from tier1 to tier2 |
+-----+--------------------------------------------+
| G21 | Gap from tier2 to tier1 |
+-----+--------------------------------------------+
| P1 | Pause for tier1 |
+-----+--------------------------------------------+
| P2 | Pause for tier2 |
+-----+--------------------------------------------+
| B12 | Within speaker overlap from tier1 to tier2 |
+-----+--------------------------------------------+
| B21 | Within speaker overlap from tier2 to tier1 |
+-----+--------------------------------------------+
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:param bool progressbar: Flag for debugging purposes that shows the
progress during the process.
:returns: List of gaps and overlaps of the form:
``[(type, start, end)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
spkr1anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier1][0].values())
spkr2anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier2][0].values())
line1 = []
isin = lambda x, lst: False if\
len([i for i in lst if i[0] <= x and i[1] >= x]) == 0 else True
minmax = (min(spkr1anns[0][0], spkr2anns[0][0]),
max(spkr1anns[-1][1], spkr2anns[-1][1]))
last = (1, minmax[0])
lastP = 0
for ts in xrange(*minmax):
in1, in2 = isin(ts, spkr1anns), isin(ts, spkr2anns)
if in1 and in2: # Both speaking
if last[0] == 'B':
continue
ty = 'B'
elif in1: # Only 1 speaking
if last[0] == '1':
continue
ty = '1'
elif in2: # Only 2 speaking
if last[0] == '2':
continue
ty = '2'
else: # None speaking
if last[0] == 'N':
continue
ty = 'N'
line1.append((last[0], last[1], ts))
last = (ty, ts)
if progressbar and int((ts*1.0/minmax[1])*100) > lastP:
lastP = int((ts*1.0/minmax[1])*100)
print '%d%%' % lastP
line1.append((last[0], last[1], minmax[1]))
ftos = []
for i in xrange(len(line1)):
if line1[i][0] == 'N':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
ftos.append(('G12_%s_%s' % (tier1, tier2)
if line1[i-1][0] == '1' else 'G21_%s_%s' %
(tier2, tier1), line1[i][1], line1[i][2]))
else:
ftos.append(('P_%s' %
(tier1 if line1[i-1][0] == '1' else tier2),
line1[i][1], line1[i][2]))
elif line1[i][0] == 'B':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
ftos.append(('O12_%s_%s' % ((tier1, tier2)
if line1[i-1][0] else 'O21_%s_%s' %
(tier2, tier1)), line1[i][1], line1[i][2]))
else:
ftos.append(('B_%s_%s' % ((tier1, tier2)
if line1[i-1][0] == '1' else
(tier2, tier1)), line1[i][1], line1[i][2]))
return [f for f in ftos if maxlen == -1 or abs(f[2] - f[1]) < maxlen]
def create_controlled_vocabulary(self, cv_id, descriptions, entries,
ext_ref=None):
"""Create a controlled vocabulary.
.. warning:: This is a very raw implementation and you should check the
Eaf file format specification for the entries.
:param str cv_id: Name of the controlled vocabulary.
:param list descriptions: List of descriptions.
:param dict entries: Entries dictionary.
:param str ext_ref: External reference.
"""
self.controlledvocabularies[cv_id] = (descriptions, entries, ext_ref)
def get_tier_ids_for_linguistic_type(self, ling_type, parent=None):
"""Give a list of all tiers matching a linguistic type.
:param str ling_type: Name of the linguistic type.
:param str parent: Only match tiers from this parent, when ``None``
this option will be ignored.
:returns: List of tiernames.
:raises KeyError: If a tier or linguistic type is non existent.
"""
return [t for t in self.tiers if
self.tiers[t][2]['LINGUISTIC_TYPE_REF'] == ling_type and
(parent is None or self.tiers[t][2]['PARENT_REF'] == parent)]
def remove_linguistic_type(self, ling_type):
"""Remove a linguistic type.
:param str ling_type: Name of the linguistic type.
"""
del(self.linguistic_types[ling_type])
def add_linguistic_type(self, lingtype, constraints=None,
timealignable=True, graphicreferences=False,
extref=None):
"""Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param list constraints: Constraint names.
:param bool timealignable: Flag for time alignable.
:param bool graphicreferences: Flag for graphic references.
:param str extref: External reference.
"""
self.linguistic_types[lingtype] = {
'LINGUISTIC_TYPE_ID': lingtype,
'TIME_ALIGNABLE': str(timealignable).lower(),
'GRAPHIC_REFERENCES': str(graphicreferences).lower(),
'CONSTRAINTS': constraints}
if extref is not None:
self.linguistic_types[lingtype]['EXT_REF'] = extref
def get_linguistic_types(self):
"""Give a list of available linguistic types.
:returns: List of linguistic type names.
"""
return self.linguistic_types.keys()
| acuriel/Nixtla | nixtla/core/tools/pympi/Elan.py | Python | gpl-2.0 | 33,330 |
// <copyright file="Collision.cs" company="LeagueSharp">
// Copyright (c) 2015 LeagueSharp.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
// </copyright>
namespace LeagueSharp.SDK
{
using System;
using System.Collections.Generic;
using System.Linq;
using LeagueSharp.Data.Enumerations;
using LeagueSharp.SDK.Polygons;
using LeagueSharp.SDK.Utils;
using SharpDX;
/// <summary>
/// Collision class, calculates collision for moving objects.
/// </summary>
public static class Collision
{
#region Static Fields
private static MissileClient yasuoWallLeft, yasuoWallRight;
private static RectanglePoly yasuoWallPoly;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes static members of the <see cref="Collision" /> class.
/// Static Constructor
/// </summary>
static Collision()
{
GameObject.OnCreate += (sender, args) =>
{
var missile = sender as MissileClient;
var spellCaster = missile?.SpellCaster as Obj_AI_Hero;
if (spellCaster == null || spellCaster.ChampionName != "Yasuo"
|| spellCaster.Team == GameObjects.Player.Team)
{
return;
}
switch (missile.SData.Name)
{
case "YasuoWMovingWallMisL":
yasuoWallLeft = missile;
break;
case "YasuoWMovingWallMisR":
yasuoWallRight = missile;
break;
case "YasuoWMovingWallMisVis":
yasuoWallRight = missile;
break;
}
};
GameObject.OnDelete += (sender, args) =>
{
var missile = sender as MissileClient;
if (missile == null)
{
return;
}
if (missile.Compare(yasuoWallLeft))
{
yasuoWallLeft = null;
}
else if (missile.Compare(yasuoWallRight))
{
yasuoWallRight = null;
}
};
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Returns the list of the units that the skill-shot will hit before reaching the set positions.
/// </summary>
/// <param name="positions">
/// The positions.
/// </param>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// A list of <c>Obj_AI_Base</c>s which the input collides with.
/// </returns>
public static List<Obj_AI_Base> GetCollision(List<Vector3> positions, PredictionInput input)
{
var result = new List<Obj_AI_Base>();
foreach (var position in positions)
{
if (input.CollisionObjects.HasFlag(CollisionableObjects.Minions))
{
result.AddRange(
GameObjects.EnemyMinions.Where(i => i.IsMinion() || i.IsPet())
.Concat(GameObjects.Jungle)
.Where(
minion =>
minion.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(minion, input, position, 20)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Heroes))
{
result.AddRange(
GameObjects.EnemyHeroes.Where(
hero =>
hero.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(hero, input, position, 50)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Walls))
{
var step = position.Distance(input.From) / 20;
for (var i = 0; i < 20; i++)
{
if (input.From.ToVector2().Extend(position, step * i).IsWall())
{
result.Add(GameObjects.Player);
}
}
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.YasuoWall))
{
if (yasuoWallLeft == null || yasuoWallRight == null)
{
continue;
}
yasuoWallPoly = new RectanglePoly(yasuoWallLeft.Position, yasuoWallRight.Position, 75);
var intersections = new List<Vector2>();
for (var i = 0; i < yasuoWallPoly.Points.Count; i++)
{
var inter =
yasuoWallPoly.Points[i].Intersection(
yasuoWallPoly.Points[i != yasuoWallPoly.Points.Count - 1 ? i + 1 : 0],
input.From.ToVector2(),
position.ToVector2());
if (inter.Intersects)
{
intersections.Add(inter.Point);
}
}
if (intersections.Count > 0)
{
result.Add(GameObjects.Player);
}
}
}
return result.Distinct().ToList();
}
#endregion
#region Methods
private static bool IsHitCollision(Obj_AI_Base collision, PredictionInput input, Vector3 pos, float extraRadius)
{
var inputSub = input.Clone() as PredictionInput;
if (inputSub == null)
{
return false;
}
inputSub.Unit = collision;
var predPos = Movement.GetPrediction(inputSub, false, false).UnitPosition.ToVector2();
return predPos.Distance(input.From) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.Distance(pos) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.DistanceSquared(input.From.ToVector2(), pos.ToVector2(), true)
<= Math.Pow(input.Radius + input.Unit.BoundingRadius + extraRadius, 2);
}
#endregion
}
}
| CjShuMoon/TwLS.SDK | Core/Math/Collision.cs | C# | gpl-2.0 | 7,683 |
var express = require('express');
var path = require('path');
var tilestrata = require('tilestrata');
var disk = require('tilestrata-disk');
var mapnik = require('tilestrata-mapnik');
var dependency = require('tilestrata-dependency');
var strata = tilestrata();
var app = express();
// define layers
strata.layer('hillshade')
.route('shade.png')
.use(disk.cache({dir: './tiles/shade/'}))
.use(mapnik({
pathname: './styles/hillshade.xml',
tileSize: 256,
scale: 1
}));
strata.layer('dem')
.route('dem.png')
.use(disk.cache({dir: './tiles/dem/'}))
.use(mapnik({
pathname: './styles/dem.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim1')
.route('sim1.png')
.use(disk.cache({dir: './tiles/sim1/'}))
.use(mapnik({
pathname: './styles/sim1.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim2')
.route('sim2.png')
.use(disk.cache({dir: './tiles/sim2/'}))
.use(mapnik({
pathname: './styles/sim2.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim3')
.route('sim3.png')
.use(disk.cache({dir: './tiles/sim3/'}))
.use(mapnik({
pathname: './styles/sim3.xml',
tileSize: 256,
scale: 1
}));
strata.layer('slope')
.route('slope.png')
.use(disk.cache({dir: './tiles/slope/'}))
.use(mapnik({
pathname: './styles/slope.xml',
tileSize: 256,
scale: 1
}));
var staticPath = path.resolve(__dirname, './public/');
app.use(express.static(staticPath));
app.use(tilestrata.middleware({
server: strata,
prefix: ''
}));
app.listen(8080, function() {
console.log('Express server running on port 8080.');
});
| nronnei/srtm-server | app.js | JavaScript | gpl-2.0 | 1,877 |
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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 "platform/OSXUchrKeyResource.h"
#include <Carbon/Carbon.h>
//
// OSXUchrKeyResource
//
OSXUchrKeyResource::OSXUchrKeyResource(const void* resource,
UInt32 keyboardType) :
m_m(NULL),
m_cti(NULL),
m_sdi(NULL),
m_sri(NULL),
m_st(NULL)
{
m_resource = reinterpret_cast<const UCKeyboardLayout*>(resource);
if (m_resource == NULL) {
return;
}
// find the keyboard info for the current keyboard type
const UCKeyboardTypeHeader* th = NULL;
const UCKeyboardLayout* r = m_resource;
for (ItemCount i = 0; i < r->keyboardTypeCount; ++i) {
if (keyboardType >= r->keyboardTypeList[i].keyboardTypeFirst &&
keyboardType <= r->keyboardTypeList[i].keyboardTypeLast) {
th = r->keyboardTypeList + i;
break;
}
if (r->keyboardTypeList[i].keyboardTypeFirst == 0) {
// found the default. use it unless we find a match.
th = r->keyboardTypeList + i;
}
}
if (th == NULL) {
// cannot find a suitable keyboard type
return;
}
// get tables for keyboard type
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
m_m = reinterpret_cast<const UCKeyModifiersToTableNum*>(base +
th->keyModifiersToTableNumOffset);
m_cti = reinterpret_cast<const UCKeyToCharTableIndex*>(base +
th->keyToCharTableIndexOffset);
m_sdi = reinterpret_cast<const UCKeySequenceDataIndex*>(base +
th->keySequenceDataIndexOffset);
if (th->keyStateRecordsIndexOffset != 0) {
m_sri = reinterpret_cast<const UCKeyStateRecordsIndex*>(base +
th->keyStateRecordsIndexOffset);
}
if (th->keyStateTerminatorsOffset != 0) {
m_st = reinterpret_cast<const UCKeyStateTerminators*>(base +
th->keyStateTerminatorsOffset);
}
// find the space key, but only if it can combine with dead keys.
// a dead key followed by a space yields the non-dead version of
// the dead key.
m_spaceOutput = 0xffffu;
UInt32 table = getTableForModifier(0);
for (UInt32 button = 0, n = getNumButtons(); button < n; ++button) {
KeyID id = getKey(table, button);
if (id == 0x20) {
UCKeyOutput c =
reinterpret_cast<const UCKeyOutput*>(base +
m_cti->keyToCharTableOffsets[table])[button];
if ((c & kUCKeyOutputTestForIndexMask) ==
kUCKeyOutputStateIndexMask) {
m_spaceOutput = (c & kUCKeyOutputGetIndexMask);
break;
}
}
}
}
bool
OSXUchrKeyResource::isValid() const
{
return (m_m != NULL);
}
UInt32
OSXUchrKeyResource::getNumModifierCombinations() const
{
// only 32 (not 256) because the righthanded modifier bits are ignored
return 32;
}
UInt32
OSXUchrKeyResource::getNumTables() const
{
return m_cti->keyToCharTableCount;
}
UInt32
OSXUchrKeyResource::getNumButtons() const
{
return m_cti->keyToCharTableSize;
}
UInt32
OSXUchrKeyResource::getTableForModifier(UInt32 mask) const
{
if (mask >= m_m->modifiersCount) {
return m_m->defaultTableNum;
}
else {
return m_m->tableNum[mask];
}
}
KeyID
OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const
{
assert(table < getNumTables());
assert(button < getNumButtons());
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
const UCKeyOutput* cPtr = reinterpret_cast<const UCKeyOutput*>(base +
m_cti->keyToCharTableOffsets[table]);
const UCKeyOutput c = cPtr[button];
KeySequence keys;
switch (c & kUCKeyOutputTestForIndexMask) {
case kUCKeyOutputStateIndexMask:
if (!getDeadKey(keys, c & kUCKeyOutputGetIndexMask)) {
return kKeyNone;
}
break;
case kUCKeyOutputSequenceIndexMask:
default:
if (!addSequence(keys, c)) {
return kKeyNone;
}
break;
}
// XXX -- no support for multiple characters
if (keys.size() != 1) {
return kKeyNone;
}
return keys.front();
}
bool
OSXUchrKeyResource::getDeadKey(
KeySequence& keys, UInt16 index) const
{
if (m_sri == NULL || index >= m_sri->keyStateRecordCount) {
// XXX -- should we be using some other fallback?
return false;
}
UInt16 state = 0;
if (!getKeyRecord(keys, index, state)) {
return false;
}
if (state == 0) {
// not a dead key
return true;
}
// no dead keys if we couldn't find the space key
if (m_spaceOutput == 0xffffu) {
return false;
}
// the dead key should not have put anything in the key list
if (!keys.empty()) {
return false;
}
// get the character generated by pressing the space key after the
// dead key. if we're still in a compose state afterwards then we're
// confused so we bail.
if (!getKeyRecord(keys, m_spaceOutput, state) || state != 0) {
return false;
}
// convert keys to their dead counterparts
for (KeySequence::iterator i = keys.begin(); i != keys.end(); ++i) {
*i = synergy::KeyMap::getDeadKey(*i);
}
return true;
}
bool
OSXUchrKeyResource::getKeyRecord(
KeySequence& keys, UInt16 index, UInt16& state) const
{
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
const UCKeyStateRecord* sr =
reinterpret_cast<const UCKeyStateRecord*>(base +
m_sri->keyStateRecordOffsets[index]);
const UCKeyStateEntryTerminal* kset =
reinterpret_cast<const UCKeyStateEntryTerminal*>(sr->stateEntryData);
UInt16 nextState = 0;
bool found = false;
if (state == 0) {
found = true;
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
}
else {
// we have a next entry
switch (sr->stateEntryFormat) {
case kUCKeyStateEntryTerminalFormat:
for (UInt16 j = 0; j < sr->stateEntryCount; ++j) {
if (kset[j].curState == state) {
if (!addSequence(keys, kset[j].charData)) {
return false;
}
nextState = 0;
found = true;
break;
}
}
break;
case kUCKeyStateEntryRangeFormat:
// XXX -- not supported yet
break;
default:
// XXX -- unknown format
return false;
}
}
if (!found) {
// use a terminator
if (m_st != NULL && state < m_st->keyStateTerminatorCount) {
if (!addSequence(keys, m_st->keyStateTerminators[state - 1])) {
return false;
}
}
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
}
// next
state = nextState;
return true;
}
bool
OSXUchrKeyResource::addSequence(
KeySequence& keys, UCKeyCharSeq c) const
{
if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputSequenceIndexMask) {
UInt16 index = (c & kUCKeyOutputGetIndexMask);
if (index < m_sdi->charSequenceCount &&
m_sdi->charSequenceOffsets[index] !=
m_sdi->charSequenceOffsets[index + 1]) {
// XXX -- sequences not supported yet
return false;
}
}
if (c != 0xfffe && c != 0xffff) {
KeyID id = unicharToKeyID(c);
if (id != kKeyNone) {
keys.push_back(id);
}
}
return true;
}
| hunterua/synergy | src/lib/platform/OSXUchrKeyResource.cpp | C++ | gpl-2.0 | 7,325 |
<?php
include_once "srcPHP/View/View.php";
include_once "srcPHP/Model/ResearchModel.php";
class Mosaic implements View{
var $model = NULL;
var $array = NULL;
function Mosaic(){
$this->model = new ResearchModel("dbserver", "xjouveno", "xjouveno", "pdp");
$this->array = $this->model->getAllVideo();
}
function linkCSS(){ echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mosaic.css\">"; }
function linkJS(){ }
function onLoadJS(){ }
function draw(){
echo "<section>";
echo "<ul class=\"patients\">";
echo $tmp = NULL;
for($i=0; $i<count($this->array); $i++){
// Patient suivant
if($tmp != $this->array[$i]["IdPatient"]){
$tmp = $this->array[$i]["IdPatient"];
if($i != 0){
echo "</ul>";
echo "</li>";
}
echo "<li>";
echo "<h3>".$this->array[$i]["Name"]." - ".$this->array[$i]["IdPatient"]."</h3>";
echo "<ul>";
}
//Video Suivante
echo "<li>";
echo "<span>";
// echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/video.png\" /></a>";
echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/".$this->array[$i]["IdVideo"].".jpg\" /></a>";
echo "<label>".$this->array[$i]["Title"]."</label>";
echo "</span>";
echo "</li>";
}
echo "</ul>";
echo "</section>";
}
}
?>
| s4e-tom/navideo | Trunk/srcPHP/View/Section/GuestSection/Mosaic.php | PHP | gpl-2.0 | 1,462 |